babylon.viewer.max.js 5.2 MB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755775677577758775977607761776277637764776577667767776877697770777177727773777477757776777777787779778077817782778377847785778677877788778977907791779277937794779577967797779877997800780178027803780478057806780778087809781078117812781378147815781678177818781978207821782278237824782578267827782878297830783178327833783478357836783778387839784078417842784378447845784678477848784978507851785278537854785578567857785878597860786178627863786478657866786778687869787078717872787378747875787678777878787978807881788278837884788578867887788878897890789178927893789478957896789778987899790079017902790379047905790679077908790979107911791279137914791579167917791879197920792179227923792479257926792779287929793079317932793379347935793679377938793979407941794279437944794579467947794879497950795179527953795479557956795779587959796079617962796379647965796679677968796979707971797279737974797579767977797879797980798179827983798479857986798779887989799079917992799379947995799679977998799980008001800280038004800580068007800880098010801180128013801480158016801780188019802080218022802380248025802680278028802980308031803280338034803580368037803880398040804180428043804480458046804780488049805080518052805380548055805680578058805980608061806280638064806580668067806880698070807180728073807480758076807780788079808080818082808380848085808680878088808980908091809280938094809580968097809880998100810181028103810481058106810781088109811081118112811381148115811681178118811981208121812281238124812581268127812881298130813181328133813481358136813781388139814081418142814381448145814681478148814981508151815281538154815581568157815881598160816181628163816481658166816781688169817081718172817381748175817681778178817981808181818281838184818581868187818881898190819181928193819481958196819781988199820082018202820382048205820682078208820982108211821282138214821582168217821882198220822182228223822482258226822782288229823082318232823382348235823682378238823982408241824282438244824582468247824882498250825182528253825482558256825782588259826082618262826382648265826682678268826982708271827282738274827582768277827882798280828182828283828482858286828782888289829082918292829382948295829682978298829983008301830283038304830583068307830883098310831183128313831483158316831783188319832083218322832383248325832683278328832983308331833283338334833583368337833883398340834183428343834483458346834783488349835083518352835383548355835683578358835983608361836283638364836583668367836883698370837183728373837483758376837783788379838083818382838383848385838683878388838983908391839283938394839583968397839883998400840184028403840484058406840784088409841084118412841384148415841684178418841984208421842284238424842584268427842884298430843184328433843484358436843784388439844084418442844384448445844684478448844984508451845284538454845584568457845884598460846184628463846484658466846784688469847084718472847384748475847684778478847984808481848284838484848584868487848884898490849184928493849484958496849784988499850085018502850385048505850685078508850985108511851285138514851585168517851885198520852185228523852485258526852785288529853085318532853385348535853685378538853985408541854285438544854585468547854885498550855185528553855485558556855785588559856085618562856385648565856685678568856985708571857285738574857585768577857885798580858185828583858485858586858785888589859085918592859385948595859685978598859986008601860286038604860586068607860886098610861186128613861486158616861786188619862086218622862386248625862686278628862986308631863286338634863586368637863886398640864186428643864486458646864786488649865086518652865386548655865686578658865986608661866286638664866586668667866886698670867186728673867486758676867786788679868086818682868386848685868686878688868986908691869286938694869586968697869886998700870187028703870487058706870787088709871087118712871387148715871687178718871987208721872287238724872587268727872887298730873187328733873487358736873787388739874087418742874387448745874687478748874987508751875287538754875587568757875887598760876187628763876487658766876787688769877087718772877387748775877687778778877987808781878287838784878587868787878887898790879187928793879487958796879787988799880088018802880388048805880688078808880988108811881288138814881588168817881888198820882188228823882488258826882788288829883088318832883388348835883688378838883988408841884288438844884588468847884888498850885188528853885488558856885788588859886088618862886388648865886688678868886988708871887288738874887588768877887888798880888188828883888488858886888788888889889088918892889388948895889688978898889989008901890289038904890589068907890889098910891189128913891489158916891789188919892089218922892389248925892689278928892989308931893289338934893589368937893889398940894189428943894489458946894789488949895089518952895389548955895689578958895989608961896289638964896589668967896889698970897189728973897489758976897789788979898089818982898389848985898689878988898989908991899289938994899589968997899889999000900190029003900490059006900790089009901090119012901390149015901690179018901990209021902290239024902590269027902890299030903190329033903490359036903790389039904090419042904390449045904690479048904990509051905290539054905590569057905890599060906190629063906490659066906790689069907090719072907390749075907690779078907990809081908290839084908590869087908890899090909190929093909490959096909790989099910091019102910391049105910691079108910991109111911291139114911591169117911891199120912191229123912491259126912791289129913091319132913391349135913691379138913991409141914291439144914591469147914891499150915191529153915491559156915791589159916091619162916391649165916691679168916991709171917291739174917591769177917891799180918191829183918491859186918791889189919091919192919391949195919691979198919992009201920292039204920592069207920892099210921192129213921492159216921792189219922092219222922392249225922692279228922992309231923292339234923592369237923892399240924192429243924492459246924792489249925092519252925392549255925692579258925992609261926292639264926592669267926892699270927192729273927492759276927792789279928092819282928392849285928692879288928992909291929292939294929592969297929892999300930193029303930493059306930793089309931093119312931393149315931693179318931993209321932293239324932593269327932893299330933193329333933493359336933793389339934093419342934393449345934693479348934993509351935293539354935593569357935893599360936193629363936493659366936793689369937093719372937393749375937693779378937993809381938293839384938593869387938893899390939193929393939493959396939793989399940094019402940394049405940694079408940994109411941294139414941594169417941894199420942194229423942494259426942794289429943094319432943394349435943694379438943994409441944294439444944594469447944894499450945194529453945494559456945794589459946094619462946394649465946694679468946994709471947294739474947594769477947894799480948194829483948494859486948794889489949094919492949394949495949694979498949995009501950295039504950595069507950895099510951195129513951495159516951795189519952095219522952395249525952695279528952995309531953295339534953595369537953895399540954195429543954495459546954795489549955095519552955395549555955695579558955995609561956295639564956595669567956895699570957195729573957495759576957795789579958095819582958395849585958695879588958995909591959295939594959595969597959895999600960196029603960496059606960796089609961096119612961396149615961696179618961996209621962296239624962596269627962896299630963196329633963496359636963796389639964096419642964396449645964696479648964996509651965296539654965596569657965896599660966196629663966496659666966796689669967096719672967396749675967696779678967996809681968296839684968596869687968896899690969196929693969496959696969796989699970097019702970397049705970697079708970997109711971297139714971597169717971897199720972197229723972497259726972797289729973097319732973397349735973697379738973997409741974297439744974597469747974897499750975197529753975497559756975797589759976097619762976397649765976697679768976997709771977297739774977597769777977897799780978197829783978497859786978797889789979097919792979397949795979697979798979998009801980298039804980598069807980898099810981198129813981498159816981798189819982098219822982398249825982698279828982998309831983298339834983598369837983898399840984198429843984498459846984798489849985098519852985398549855985698579858985998609861986298639864986598669867986898699870987198729873987498759876987798789879988098819882988398849885988698879888988998909891989298939894989598969897989898999900990199029903990499059906990799089909991099119912991399149915991699179918991999209921992299239924992599269927992899299930993199329933993499359936993799389939994099419942994399449945994699479948994999509951995299539954995599569957995899599960996199629963996499659966996799689969997099719972997399749975997699779978997999809981998299839984998599869987998899899990999199929993999499959996999799989999100001000110002100031000410005100061000710008100091001010011100121001310014100151001610017100181001910020100211002210023100241002510026100271002810029100301003110032100331003410035100361003710038100391004010041100421004310044100451004610047100481004910050100511005210053100541005510056100571005810059100601006110062100631006410065100661006710068100691007010071100721007310074100751007610077100781007910080100811008210083100841008510086100871008810089100901009110092100931009410095100961009710098100991010010101101021010310104101051010610107101081010910110101111011210113101141011510116101171011810119101201012110122101231012410125101261012710128101291013010131101321013310134101351013610137101381013910140101411014210143101441014510146101471014810149101501015110152101531015410155101561015710158101591016010161101621016310164101651016610167101681016910170101711017210173101741017510176101771017810179101801018110182101831018410185101861018710188101891019010191101921019310194101951019610197101981019910200102011020210203102041020510206102071020810209102101021110212102131021410215102161021710218102191022010221102221022310224102251022610227102281022910230102311023210233102341023510236102371023810239102401024110242102431024410245102461024710248102491025010251102521025310254102551025610257102581025910260102611026210263102641026510266102671026810269102701027110272102731027410275102761027710278102791028010281102821028310284102851028610287102881028910290102911029210293102941029510296102971029810299103001030110302103031030410305103061030710308103091031010311103121031310314103151031610317103181031910320103211032210323103241032510326103271032810329103301033110332103331033410335103361033710338103391034010341103421034310344103451034610347103481034910350103511035210353103541035510356103571035810359103601036110362103631036410365103661036710368103691037010371103721037310374103751037610377103781037910380103811038210383103841038510386103871038810389103901039110392103931039410395103961039710398103991040010401104021040310404104051040610407104081040910410104111041210413104141041510416104171041810419104201042110422104231042410425104261042710428104291043010431104321043310434104351043610437104381043910440104411044210443104441044510446104471044810449104501045110452104531045410455104561045710458104591046010461104621046310464104651046610467104681046910470104711047210473104741047510476104771047810479104801048110482104831048410485104861048710488104891049010491104921049310494104951049610497104981049910500105011050210503105041050510506105071050810509105101051110512105131051410515105161051710518105191052010521105221052310524105251052610527105281052910530105311053210533105341053510536105371053810539105401054110542105431054410545105461054710548105491055010551105521055310554105551055610557105581055910560105611056210563105641056510566105671056810569105701057110572105731057410575105761057710578105791058010581105821058310584105851058610587105881058910590105911059210593105941059510596105971059810599106001060110602106031060410605106061060710608106091061010611106121061310614106151061610617106181061910620106211062210623106241062510626106271062810629106301063110632106331063410635106361063710638106391064010641106421064310644106451064610647106481064910650106511065210653106541065510656106571065810659106601066110662106631066410665106661066710668106691067010671106721067310674106751067610677106781067910680106811068210683106841068510686106871068810689106901069110692106931069410695106961069710698106991070010701107021070310704107051070610707107081070910710107111071210713107141071510716107171071810719107201072110722107231072410725107261072710728107291073010731107321073310734107351073610737107381073910740107411074210743107441074510746107471074810749107501075110752107531075410755107561075710758107591076010761107621076310764107651076610767107681076910770107711077210773107741077510776107771077810779107801078110782107831078410785107861078710788107891079010791107921079310794107951079610797107981079910800108011080210803108041080510806108071080810809108101081110812108131081410815108161081710818108191082010821108221082310824108251082610827108281082910830108311083210833108341083510836108371083810839108401084110842108431084410845108461084710848108491085010851108521085310854108551085610857108581085910860108611086210863108641086510866108671086810869108701087110872108731087410875108761087710878108791088010881108821088310884108851088610887108881088910890108911089210893108941089510896108971089810899109001090110902109031090410905109061090710908109091091010911109121091310914109151091610917109181091910920109211092210923109241092510926109271092810929109301093110932109331093410935109361093710938109391094010941109421094310944109451094610947109481094910950109511095210953109541095510956109571095810959109601096110962109631096410965109661096710968109691097010971109721097310974109751097610977109781097910980109811098210983109841098510986109871098810989109901099110992109931099410995109961099710998109991100011001110021100311004110051100611007110081100911010110111101211013110141101511016110171101811019110201102111022110231102411025110261102711028110291103011031110321103311034110351103611037110381103911040110411104211043110441104511046110471104811049110501105111052110531105411055110561105711058110591106011061110621106311064110651106611067110681106911070110711107211073110741107511076110771107811079110801108111082110831108411085110861108711088110891109011091110921109311094110951109611097110981109911100111011110211103111041110511106111071110811109111101111111112111131111411115111161111711118111191112011121111221112311124111251112611127111281112911130111311113211133111341113511136111371113811139111401114111142111431114411145111461114711148111491115011151111521115311154111551115611157111581115911160111611116211163111641116511166111671116811169111701117111172111731117411175111761117711178111791118011181111821118311184111851118611187111881118911190111911119211193111941119511196111971119811199112001120111202112031120411205112061120711208112091121011211112121121311214112151121611217112181121911220112211122211223112241122511226112271122811229112301123111232112331123411235112361123711238112391124011241112421124311244112451124611247112481124911250112511125211253112541125511256112571125811259112601126111262112631126411265112661126711268112691127011271112721127311274112751127611277112781127911280112811128211283112841128511286112871128811289112901129111292112931129411295112961129711298112991130011301113021130311304113051130611307113081130911310113111131211313113141131511316113171131811319113201132111322113231132411325113261132711328113291133011331113321133311334113351133611337113381133911340113411134211343113441134511346113471134811349113501135111352113531135411355113561135711358113591136011361113621136311364113651136611367113681136911370113711137211373113741137511376113771137811379113801138111382113831138411385113861138711388113891139011391113921139311394113951139611397113981139911400114011140211403114041140511406114071140811409114101141111412114131141411415114161141711418114191142011421114221142311424114251142611427114281142911430114311143211433114341143511436114371143811439114401144111442114431144411445114461144711448114491145011451114521145311454114551145611457114581145911460114611146211463114641146511466114671146811469114701147111472114731147411475114761147711478114791148011481114821148311484114851148611487114881148911490114911149211493114941149511496114971149811499115001150111502115031150411505115061150711508115091151011511115121151311514115151151611517115181151911520115211152211523115241152511526115271152811529115301153111532115331153411535115361153711538115391154011541115421154311544115451154611547115481154911550115511155211553115541155511556115571155811559115601156111562115631156411565115661156711568115691157011571115721157311574115751157611577115781157911580115811158211583115841158511586115871158811589115901159111592115931159411595115961159711598115991160011601116021160311604116051160611607116081160911610116111161211613116141161511616116171161811619116201162111622116231162411625116261162711628116291163011631116321163311634116351163611637116381163911640116411164211643116441164511646116471164811649116501165111652116531165411655116561165711658116591166011661116621166311664116651166611667116681166911670116711167211673116741167511676116771167811679116801168111682116831168411685116861168711688116891169011691116921169311694116951169611697116981169911700117011170211703117041170511706117071170811709117101171111712117131171411715117161171711718117191172011721117221172311724117251172611727117281172911730117311173211733117341173511736117371173811739117401174111742117431174411745117461174711748117491175011751117521175311754117551175611757117581175911760117611176211763117641176511766117671176811769117701177111772117731177411775117761177711778117791178011781117821178311784117851178611787117881178911790117911179211793117941179511796117971179811799118001180111802118031180411805118061180711808118091181011811118121181311814118151181611817118181181911820118211182211823118241182511826118271182811829118301183111832118331183411835118361183711838118391184011841118421184311844118451184611847118481184911850118511185211853118541185511856118571185811859118601186111862118631186411865118661186711868118691187011871118721187311874118751187611877118781187911880118811188211883118841188511886118871188811889118901189111892118931189411895118961189711898118991190011901119021190311904119051190611907119081190911910119111191211913119141191511916119171191811919119201192111922119231192411925119261192711928119291193011931119321193311934119351193611937119381193911940119411194211943119441194511946119471194811949119501195111952119531195411955119561195711958119591196011961119621196311964119651196611967119681196911970119711197211973119741197511976119771197811979119801198111982119831198411985119861198711988119891199011991119921199311994119951199611997119981199912000120011200212003120041200512006120071200812009120101201112012120131201412015120161201712018120191202012021120221202312024120251202612027120281202912030120311203212033120341203512036120371203812039120401204112042120431204412045120461204712048120491205012051120521205312054120551205612057120581205912060120611206212063120641206512066120671206812069120701207112072120731207412075120761207712078120791208012081120821208312084120851208612087120881208912090120911209212093120941209512096120971209812099121001210112102121031210412105121061210712108121091211012111121121211312114121151211612117121181211912120121211212212123121241212512126121271212812129121301213112132121331213412135121361213712138121391214012141121421214312144121451214612147121481214912150121511215212153121541215512156121571215812159121601216112162121631216412165121661216712168121691217012171121721217312174121751217612177121781217912180121811218212183121841218512186121871218812189121901219112192121931219412195121961219712198121991220012201122021220312204122051220612207122081220912210122111221212213122141221512216122171221812219122201222112222122231222412225122261222712228122291223012231122321223312234122351223612237122381223912240122411224212243122441224512246122471224812249122501225112252122531225412255122561225712258122591226012261122621226312264122651226612267122681226912270122711227212273122741227512276122771227812279122801228112282122831228412285122861228712288122891229012291122921229312294122951229612297122981229912300123011230212303123041230512306123071230812309123101231112312123131231412315123161231712318123191232012321123221232312324123251232612327123281232912330123311233212333123341233512336123371233812339123401234112342123431234412345123461234712348123491235012351123521235312354123551235612357123581235912360123611236212363123641236512366123671236812369123701237112372123731237412375123761237712378123791238012381123821238312384123851238612387123881238912390123911239212393123941239512396123971239812399124001240112402124031240412405124061240712408124091241012411124121241312414124151241612417124181241912420124211242212423124241242512426124271242812429124301243112432124331243412435124361243712438124391244012441124421244312444124451244612447124481244912450124511245212453124541245512456124571245812459124601246112462124631246412465124661246712468124691247012471124721247312474124751247612477124781247912480124811248212483124841248512486124871248812489124901249112492124931249412495124961249712498124991250012501125021250312504125051250612507125081250912510125111251212513125141251512516125171251812519125201252112522125231252412525125261252712528125291253012531125321253312534125351253612537125381253912540125411254212543125441254512546125471254812549125501255112552125531255412555125561255712558125591256012561125621256312564125651256612567125681256912570125711257212573125741257512576125771257812579125801258112582125831258412585125861258712588125891259012591125921259312594125951259612597125981259912600126011260212603126041260512606126071260812609126101261112612126131261412615126161261712618126191262012621126221262312624126251262612627126281262912630126311263212633126341263512636126371263812639126401264112642126431264412645126461264712648126491265012651126521265312654126551265612657126581265912660126611266212663126641266512666126671266812669126701267112672126731267412675126761267712678126791268012681126821268312684126851268612687126881268912690126911269212693126941269512696126971269812699127001270112702127031270412705127061270712708127091271012711127121271312714127151271612717127181271912720127211272212723127241272512726127271272812729127301273112732127331273412735127361273712738127391274012741127421274312744127451274612747127481274912750127511275212753127541275512756127571275812759127601276112762127631276412765127661276712768127691277012771127721277312774127751277612777127781277912780127811278212783127841278512786127871278812789127901279112792127931279412795127961279712798127991280012801128021280312804128051280612807128081280912810128111281212813128141281512816128171281812819128201282112822128231282412825128261282712828128291283012831128321283312834128351283612837128381283912840128411284212843128441284512846128471284812849128501285112852128531285412855128561285712858128591286012861128621286312864128651286612867128681286912870128711287212873128741287512876128771287812879128801288112882128831288412885128861288712888128891289012891128921289312894128951289612897128981289912900129011290212903129041290512906129071290812909129101291112912129131291412915129161291712918129191292012921129221292312924129251292612927129281292912930129311293212933129341293512936129371293812939129401294112942129431294412945129461294712948129491295012951129521295312954129551295612957129581295912960129611296212963129641296512966129671296812969129701297112972129731297412975129761297712978129791298012981129821298312984129851298612987129881298912990129911299212993129941299512996129971299812999130001300113002130031300413005130061300713008130091301013011130121301313014130151301613017130181301913020130211302213023130241302513026130271302813029130301303113032130331303413035130361303713038130391304013041130421304313044130451304613047130481304913050130511305213053130541305513056130571305813059130601306113062130631306413065130661306713068130691307013071130721307313074130751307613077130781307913080130811308213083130841308513086130871308813089130901309113092130931309413095130961309713098130991310013101131021310313104131051310613107131081310913110131111311213113131141311513116131171311813119131201312113122131231312413125131261312713128131291313013131131321313313134131351313613137131381313913140131411314213143131441314513146131471314813149131501315113152131531315413155131561315713158131591316013161131621316313164131651316613167131681316913170131711317213173131741317513176131771317813179131801318113182131831318413185131861318713188131891319013191131921319313194131951319613197131981319913200132011320213203132041320513206132071320813209132101321113212132131321413215132161321713218132191322013221132221322313224132251322613227132281322913230132311323213233132341323513236132371323813239132401324113242132431324413245132461324713248132491325013251132521325313254132551325613257132581325913260132611326213263132641326513266132671326813269132701327113272132731327413275132761327713278132791328013281132821328313284132851328613287132881328913290132911329213293132941329513296132971329813299133001330113302133031330413305133061330713308133091331013311133121331313314133151331613317133181331913320133211332213323133241332513326133271332813329133301333113332133331333413335133361333713338133391334013341133421334313344133451334613347133481334913350133511335213353133541335513356133571335813359133601336113362133631336413365133661336713368133691337013371133721337313374133751337613377133781337913380133811338213383133841338513386133871338813389133901339113392133931339413395133961339713398133991340013401134021340313404134051340613407134081340913410134111341213413134141341513416134171341813419134201342113422134231342413425134261342713428134291343013431134321343313434134351343613437134381343913440134411344213443134441344513446134471344813449134501345113452134531345413455134561345713458134591346013461134621346313464134651346613467134681346913470134711347213473134741347513476134771347813479134801348113482134831348413485134861348713488134891349013491134921349313494134951349613497134981349913500135011350213503135041350513506135071350813509135101351113512135131351413515135161351713518135191352013521135221352313524135251352613527135281352913530135311353213533135341353513536135371353813539135401354113542135431354413545135461354713548135491355013551135521355313554135551355613557135581355913560135611356213563135641356513566135671356813569135701357113572135731357413575135761357713578135791358013581135821358313584135851358613587135881358913590135911359213593135941359513596135971359813599136001360113602136031360413605136061360713608136091361013611136121361313614136151361613617136181361913620136211362213623136241362513626136271362813629136301363113632136331363413635136361363713638136391364013641136421364313644136451364613647136481364913650136511365213653136541365513656136571365813659136601366113662136631366413665136661366713668136691367013671136721367313674136751367613677136781367913680136811368213683136841368513686136871368813689136901369113692136931369413695136961369713698136991370013701137021370313704137051370613707137081370913710137111371213713137141371513716137171371813719137201372113722137231372413725137261372713728137291373013731137321373313734137351373613737137381373913740137411374213743137441374513746137471374813749137501375113752137531375413755137561375713758137591376013761137621376313764137651376613767137681376913770137711377213773137741377513776137771377813779137801378113782137831378413785137861378713788137891379013791137921379313794137951379613797137981379913800138011380213803138041380513806138071380813809138101381113812138131381413815138161381713818138191382013821138221382313824138251382613827138281382913830138311383213833138341383513836138371383813839138401384113842138431384413845138461384713848138491385013851138521385313854138551385613857138581385913860138611386213863138641386513866138671386813869138701387113872138731387413875138761387713878138791388013881138821388313884138851388613887138881388913890138911389213893138941389513896138971389813899139001390113902139031390413905139061390713908139091391013911139121391313914139151391613917139181391913920139211392213923139241392513926139271392813929139301393113932139331393413935139361393713938139391394013941139421394313944139451394613947139481394913950139511395213953139541395513956139571395813959139601396113962139631396413965139661396713968139691397013971139721397313974139751397613977139781397913980139811398213983139841398513986139871398813989139901399113992139931399413995139961399713998139991400014001140021400314004140051400614007140081400914010140111401214013140141401514016140171401814019140201402114022140231402414025140261402714028140291403014031140321403314034140351403614037140381403914040140411404214043140441404514046140471404814049140501405114052140531405414055140561405714058140591406014061140621406314064140651406614067140681406914070140711407214073140741407514076140771407814079140801408114082140831408414085140861408714088140891409014091140921409314094140951409614097140981409914100141011410214103141041410514106141071410814109141101411114112141131411414115141161411714118141191412014121141221412314124141251412614127141281412914130141311413214133141341413514136141371413814139141401414114142141431414414145141461414714148141491415014151141521415314154141551415614157141581415914160141611416214163141641416514166141671416814169141701417114172141731417414175141761417714178141791418014181141821418314184141851418614187141881418914190141911419214193141941419514196141971419814199142001420114202142031420414205142061420714208142091421014211142121421314214142151421614217142181421914220142211422214223142241422514226142271422814229142301423114232142331423414235142361423714238142391424014241142421424314244142451424614247142481424914250142511425214253142541425514256142571425814259142601426114262142631426414265142661426714268142691427014271142721427314274142751427614277142781427914280142811428214283142841428514286142871428814289142901429114292142931429414295142961429714298142991430014301143021430314304143051430614307143081430914310143111431214313143141431514316143171431814319143201432114322143231432414325143261432714328143291433014331143321433314334143351433614337143381433914340143411434214343143441434514346143471434814349143501435114352143531435414355143561435714358143591436014361143621436314364143651436614367143681436914370143711437214373143741437514376143771437814379143801438114382143831438414385143861438714388143891439014391143921439314394143951439614397143981439914400144011440214403144041440514406144071440814409144101441114412144131441414415144161441714418144191442014421144221442314424144251442614427144281442914430144311443214433144341443514436144371443814439144401444114442144431444414445144461444714448144491445014451144521445314454144551445614457144581445914460144611446214463144641446514466144671446814469144701447114472144731447414475144761447714478144791448014481144821448314484144851448614487144881448914490144911449214493144941449514496144971449814499145001450114502145031450414505145061450714508145091451014511145121451314514145151451614517145181451914520145211452214523145241452514526145271452814529145301453114532145331453414535145361453714538145391454014541145421454314544145451454614547145481454914550145511455214553145541455514556145571455814559145601456114562145631456414565145661456714568145691457014571145721457314574145751457614577145781457914580145811458214583145841458514586145871458814589145901459114592145931459414595145961459714598145991460014601146021460314604146051460614607146081460914610146111461214613146141461514616146171461814619146201462114622146231462414625146261462714628146291463014631146321463314634146351463614637146381463914640146411464214643146441464514646146471464814649146501465114652146531465414655146561465714658146591466014661146621466314664146651466614667146681466914670146711467214673146741467514676146771467814679146801468114682146831468414685146861468714688146891469014691146921469314694146951469614697146981469914700147011470214703147041470514706147071470814709147101471114712147131471414715147161471714718147191472014721147221472314724147251472614727147281472914730147311473214733147341473514736147371473814739147401474114742147431474414745147461474714748147491475014751147521475314754147551475614757147581475914760147611476214763147641476514766147671476814769147701477114772147731477414775147761477714778147791478014781147821478314784147851478614787147881478914790147911479214793147941479514796147971479814799148001480114802148031480414805148061480714808148091481014811148121481314814148151481614817148181481914820148211482214823148241482514826148271482814829148301483114832148331483414835148361483714838148391484014841148421484314844148451484614847148481484914850148511485214853148541485514856148571485814859148601486114862148631486414865148661486714868148691487014871148721487314874148751487614877148781487914880148811488214883148841488514886148871488814889148901489114892148931489414895148961489714898148991490014901149021490314904149051490614907149081490914910149111491214913149141491514916149171491814919149201492114922149231492414925149261492714928149291493014931149321493314934149351493614937149381493914940149411494214943149441494514946149471494814949149501495114952149531495414955149561495714958149591496014961149621496314964149651496614967149681496914970149711497214973149741497514976149771497814979149801498114982149831498414985149861498714988149891499014991149921499314994149951499614997149981499915000150011500215003150041500515006150071500815009150101501115012150131501415015150161501715018150191502015021150221502315024150251502615027150281502915030150311503215033150341503515036150371503815039150401504115042150431504415045150461504715048150491505015051150521505315054150551505615057150581505915060150611506215063150641506515066150671506815069150701507115072150731507415075150761507715078150791508015081150821508315084150851508615087150881508915090150911509215093150941509515096150971509815099151001510115102151031510415105151061510715108151091511015111151121511315114151151511615117151181511915120151211512215123151241512515126151271512815129151301513115132151331513415135151361513715138151391514015141151421514315144151451514615147151481514915150151511515215153151541515515156151571515815159151601516115162151631516415165151661516715168151691517015171151721517315174151751517615177151781517915180151811518215183151841518515186151871518815189151901519115192151931519415195151961519715198151991520015201152021520315204152051520615207152081520915210152111521215213152141521515216152171521815219152201522115222152231522415225152261522715228152291523015231152321523315234152351523615237152381523915240152411524215243152441524515246152471524815249152501525115252152531525415255152561525715258152591526015261152621526315264152651526615267152681526915270152711527215273152741527515276152771527815279152801528115282152831528415285152861528715288152891529015291152921529315294152951529615297152981529915300153011530215303153041530515306153071530815309153101531115312153131531415315153161531715318153191532015321153221532315324153251532615327153281532915330153311533215333153341533515336153371533815339153401534115342153431534415345153461534715348153491535015351153521535315354153551535615357153581535915360153611536215363153641536515366153671536815369153701537115372153731537415375153761537715378153791538015381153821538315384153851538615387153881538915390153911539215393153941539515396153971539815399154001540115402154031540415405154061540715408154091541015411154121541315414154151541615417154181541915420154211542215423154241542515426154271542815429154301543115432154331543415435154361543715438154391544015441154421544315444154451544615447154481544915450154511545215453154541545515456154571545815459154601546115462154631546415465154661546715468154691547015471154721547315474154751547615477154781547915480154811548215483154841548515486154871548815489154901549115492154931549415495154961549715498154991550015501155021550315504155051550615507155081550915510155111551215513155141551515516155171551815519155201552115522155231552415525155261552715528155291553015531155321553315534155351553615537155381553915540155411554215543155441554515546155471554815549155501555115552155531555415555155561555715558155591556015561155621556315564155651556615567155681556915570155711557215573155741557515576155771557815579155801558115582155831558415585155861558715588155891559015591155921559315594155951559615597155981559915600156011560215603156041560515606156071560815609156101561115612156131561415615156161561715618156191562015621156221562315624156251562615627156281562915630156311563215633156341563515636156371563815639156401564115642156431564415645156461564715648156491565015651156521565315654156551565615657156581565915660156611566215663156641566515666156671566815669156701567115672156731567415675156761567715678156791568015681156821568315684156851568615687156881568915690156911569215693156941569515696156971569815699157001570115702157031570415705157061570715708157091571015711157121571315714157151571615717157181571915720157211572215723157241572515726157271572815729157301573115732157331573415735157361573715738157391574015741157421574315744157451574615747157481574915750157511575215753157541575515756157571575815759157601576115762157631576415765157661576715768157691577015771157721577315774157751577615777157781577915780157811578215783157841578515786157871578815789157901579115792157931579415795157961579715798157991580015801158021580315804158051580615807158081580915810158111581215813158141581515816158171581815819158201582115822158231582415825158261582715828158291583015831158321583315834158351583615837158381583915840158411584215843158441584515846158471584815849158501585115852158531585415855158561585715858158591586015861158621586315864158651586615867158681586915870158711587215873158741587515876158771587815879158801588115882158831588415885158861588715888158891589015891158921589315894158951589615897158981589915900159011590215903159041590515906159071590815909159101591115912159131591415915159161591715918159191592015921159221592315924159251592615927159281592915930159311593215933159341593515936159371593815939159401594115942159431594415945159461594715948159491595015951159521595315954159551595615957159581595915960159611596215963159641596515966159671596815969159701597115972159731597415975159761597715978159791598015981159821598315984159851598615987159881598915990159911599215993159941599515996159971599815999160001600116002160031600416005160061600716008160091601016011160121601316014160151601616017160181601916020160211602216023160241602516026160271602816029160301603116032160331603416035160361603716038160391604016041160421604316044160451604616047160481604916050160511605216053160541605516056160571605816059160601606116062160631606416065160661606716068160691607016071160721607316074160751607616077160781607916080160811608216083160841608516086160871608816089160901609116092160931609416095160961609716098160991610016101161021610316104161051610616107161081610916110161111611216113161141611516116161171611816119161201612116122161231612416125161261612716128161291613016131161321613316134161351613616137161381613916140161411614216143161441614516146161471614816149161501615116152161531615416155161561615716158161591616016161161621616316164161651616616167161681616916170161711617216173161741617516176161771617816179161801618116182161831618416185161861618716188161891619016191161921619316194161951619616197161981619916200162011620216203162041620516206162071620816209162101621116212162131621416215162161621716218162191622016221162221622316224162251622616227162281622916230162311623216233162341623516236162371623816239162401624116242162431624416245162461624716248162491625016251162521625316254162551625616257162581625916260162611626216263162641626516266162671626816269162701627116272162731627416275162761627716278162791628016281162821628316284162851628616287162881628916290162911629216293162941629516296162971629816299163001630116302163031630416305163061630716308163091631016311163121631316314163151631616317163181631916320163211632216323163241632516326163271632816329163301633116332163331633416335163361633716338163391634016341163421634316344163451634616347163481634916350163511635216353163541635516356163571635816359163601636116362163631636416365163661636716368163691637016371163721637316374163751637616377163781637916380163811638216383163841638516386163871638816389163901639116392163931639416395163961639716398163991640016401164021640316404164051640616407164081640916410164111641216413164141641516416164171641816419164201642116422164231642416425164261642716428164291643016431164321643316434164351643616437164381643916440164411644216443164441644516446164471644816449164501645116452164531645416455164561645716458164591646016461164621646316464164651646616467164681646916470164711647216473164741647516476164771647816479164801648116482164831648416485164861648716488164891649016491164921649316494164951649616497164981649916500165011650216503165041650516506165071650816509165101651116512165131651416515165161651716518165191652016521165221652316524165251652616527165281652916530165311653216533165341653516536165371653816539165401654116542165431654416545165461654716548165491655016551165521655316554165551655616557165581655916560165611656216563165641656516566165671656816569165701657116572165731657416575165761657716578165791658016581165821658316584165851658616587165881658916590165911659216593165941659516596165971659816599166001660116602166031660416605166061660716608166091661016611166121661316614166151661616617166181661916620166211662216623166241662516626166271662816629166301663116632166331663416635166361663716638166391664016641166421664316644166451664616647166481664916650166511665216653166541665516656166571665816659166601666116662166631666416665166661666716668166691667016671166721667316674166751667616677166781667916680166811668216683166841668516686166871668816689166901669116692166931669416695166961669716698166991670016701167021670316704167051670616707167081670916710167111671216713167141671516716167171671816719167201672116722167231672416725167261672716728167291673016731167321673316734167351673616737167381673916740167411674216743167441674516746167471674816749167501675116752167531675416755167561675716758167591676016761167621676316764167651676616767167681676916770167711677216773167741677516776167771677816779167801678116782167831678416785167861678716788167891679016791167921679316794167951679616797167981679916800168011680216803168041680516806168071680816809168101681116812168131681416815168161681716818168191682016821168221682316824168251682616827168281682916830168311683216833168341683516836168371683816839168401684116842168431684416845168461684716848168491685016851168521685316854168551685616857168581685916860168611686216863168641686516866168671686816869168701687116872168731687416875168761687716878168791688016881168821688316884168851688616887168881688916890168911689216893168941689516896168971689816899169001690116902169031690416905169061690716908169091691016911169121691316914169151691616917169181691916920169211692216923169241692516926169271692816929169301693116932169331693416935169361693716938169391694016941169421694316944169451694616947169481694916950169511695216953169541695516956169571695816959169601696116962169631696416965169661696716968169691697016971169721697316974169751697616977169781697916980169811698216983169841698516986169871698816989169901699116992169931699416995169961699716998169991700017001170021700317004170051700617007170081700917010170111701217013170141701517016170171701817019170201702117022170231702417025170261702717028170291703017031170321703317034170351703617037170381703917040170411704217043170441704517046170471704817049170501705117052170531705417055170561705717058170591706017061170621706317064170651706617067170681706917070170711707217073170741707517076170771707817079170801708117082170831708417085170861708717088170891709017091170921709317094170951709617097170981709917100171011710217103171041710517106171071710817109171101711117112171131711417115171161711717118171191712017121171221712317124171251712617127171281712917130171311713217133171341713517136171371713817139171401714117142171431714417145171461714717148171491715017151171521715317154171551715617157171581715917160171611716217163171641716517166171671716817169171701717117172171731717417175171761717717178171791718017181171821718317184171851718617187171881718917190171911719217193171941719517196171971719817199172001720117202172031720417205172061720717208172091721017211172121721317214172151721617217172181721917220172211722217223172241722517226172271722817229172301723117232172331723417235172361723717238172391724017241172421724317244172451724617247172481724917250172511725217253172541725517256172571725817259172601726117262172631726417265172661726717268172691727017271172721727317274172751727617277172781727917280172811728217283172841728517286172871728817289172901729117292172931729417295172961729717298172991730017301173021730317304173051730617307173081730917310173111731217313173141731517316173171731817319173201732117322173231732417325173261732717328173291733017331173321733317334173351733617337173381733917340173411734217343173441734517346173471734817349173501735117352173531735417355173561735717358173591736017361173621736317364173651736617367173681736917370173711737217373173741737517376173771737817379173801738117382173831738417385173861738717388173891739017391173921739317394173951739617397173981739917400174011740217403174041740517406174071740817409174101741117412174131741417415174161741717418174191742017421174221742317424174251742617427174281742917430174311743217433174341743517436174371743817439174401744117442174431744417445174461744717448174491745017451174521745317454174551745617457174581745917460174611746217463174641746517466174671746817469174701747117472174731747417475174761747717478174791748017481174821748317484174851748617487174881748917490174911749217493174941749517496174971749817499175001750117502175031750417505175061750717508175091751017511175121751317514175151751617517175181751917520175211752217523175241752517526175271752817529175301753117532175331753417535175361753717538175391754017541175421754317544175451754617547175481754917550175511755217553175541755517556175571755817559175601756117562175631756417565175661756717568175691757017571175721757317574175751757617577175781757917580175811758217583175841758517586175871758817589175901759117592175931759417595175961759717598175991760017601176021760317604176051760617607176081760917610176111761217613176141761517616176171761817619176201762117622176231762417625176261762717628176291763017631176321763317634176351763617637176381763917640176411764217643176441764517646176471764817649176501765117652176531765417655176561765717658176591766017661176621766317664176651766617667176681766917670176711767217673176741767517676176771767817679176801768117682176831768417685176861768717688176891769017691176921769317694176951769617697176981769917700177011770217703177041770517706177071770817709177101771117712177131771417715177161771717718177191772017721177221772317724177251772617727177281772917730177311773217733177341773517736177371773817739177401774117742177431774417745177461774717748177491775017751177521775317754177551775617757177581775917760177611776217763177641776517766177671776817769177701777117772177731777417775177761777717778177791778017781177821778317784177851778617787177881778917790177911779217793177941779517796177971779817799178001780117802178031780417805178061780717808178091781017811178121781317814178151781617817178181781917820178211782217823178241782517826178271782817829178301783117832178331783417835178361783717838178391784017841178421784317844178451784617847178481784917850178511785217853178541785517856178571785817859178601786117862178631786417865178661786717868178691787017871178721787317874178751787617877178781787917880178811788217883178841788517886178871788817889178901789117892178931789417895178961789717898178991790017901179021790317904179051790617907179081790917910179111791217913179141791517916179171791817919179201792117922179231792417925179261792717928179291793017931179321793317934179351793617937179381793917940179411794217943179441794517946179471794817949179501795117952179531795417955179561795717958179591796017961179621796317964179651796617967179681796917970179711797217973179741797517976179771797817979179801798117982179831798417985179861798717988179891799017991179921799317994179951799617997179981799918000180011800218003180041800518006180071800818009180101801118012180131801418015180161801718018180191802018021180221802318024180251802618027180281802918030180311803218033180341803518036180371803818039180401804118042180431804418045180461804718048180491805018051180521805318054180551805618057180581805918060180611806218063180641806518066180671806818069180701807118072180731807418075180761807718078180791808018081180821808318084180851808618087180881808918090180911809218093180941809518096180971809818099181001810118102181031810418105181061810718108181091811018111181121811318114181151811618117181181811918120181211812218123181241812518126181271812818129181301813118132181331813418135181361813718138181391814018141181421814318144181451814618147181481814918150181511815218153181541815518156181571815818159181601816118162181631816418165181661816718168181691817018171181721817318174181751817618177181781817918180181811818218183181841818518186181871818818189181901819118192181931819418195181961819718198181991820018201182021820318204182051820618207182081820918210182111821218213182141821518216182171821818219182201822118222182231822418225182261822718228182291823018231182321823318234182351823618237182381823918240182411824218243182441824518246182471824818249182501825118252182531825418255182561825718258182591826018261182621826318264182651826618267182681826918270182711827218273182741827518276182771827818279182801828118282182831828418285182861828718288182891829018291182921829318294182951829618297182981829918300183011830218303183041830518306183071830818309183101831118312183131831418315183161831718318183191832018321183221832318324183251832618327183281832918330183311833218333183341833518336183371833818339183401834118342183431834418345183461834718348183491835018351183521835318354183551835618357183581835918360183611836218363183641836518366183671836818369183701837118372183731837418375183761837718378183791838018381183821838318384183851838618387183881838918390183911839218393183941839518396183971839818399184001840118402184031840418405184061840718408184091841018411184121841318414184151841618417184181841918420184211842218423184241842518426184271842818429184301843118432184331843418435184361843718438184391844018441184421844318444184451844618447184481844918450184511845218453184541845518456184571845818459184601846118462184631846418465184661846718468184691847018471184721847318474184751847618477184781847918480184811848218483184841848518486184871848818489184901849118492184931849418495184961849718498184991850018501185021850318504185051850618507185081850918510185111851218513185141851518516185171851818519185201852118522185231852418525185261852718528185291853018531185321853318534185351853618537185381853918540185411854218543185441854518546185471854818549185501855118552185531855418555185561855718558185591856018561185621856318564185651856618567185681856918570185711857218573185741857518576185771857818579185801858118582185831858418585185861858718588185891859018591185921859318594185951859618597185981859918600186011860218603186041860518606186071860818609186101861118612186131861418615186161861718618186191862018621186221862318624186251862618627186281862918630186311863218633186341863518636186371863818639186401864118642186431864418645186461864718648186491865018651186521865318654186551865618657186581865918660186611866218663186641866518666186671866818669186701867118672186731867418675186761867718678186791868018681186821868318684186851868618687186881868918690186911869218693186941869518696186971869818699187001870118702187031870418705187061870718708187091871018711187121871318714187151871618717187181871918720187211872218723187241872518726187271872818729187301873118732187331873418735187361873718738187391874018741187421874318744187451874618747187481874918750187511875218753187541875518756187571875818759187601876118762187631876418765187661876718768187691877018771187721877318774187751877618777187781877918780187811878218783187841878518786187871878818789187901879118792187931879418795187961879718798187991880018801188021880318804188051880618807188081880918810188111881218813188141881518816188171881818819188201882118822188231882418825188261882718828188291883018831188321883318834188351883618837188381883918840188411884218843188441884518846188471884818849188501885118852188531885418855188561885718858188591886018861188621886318864188651886618867188681886918870188711887218873188741887518876188771887818879188801888118882188831888418885188861888718888188891889018891188921889318894188951889618897188981889918900189011890218903189041890518906189071890818909189101891118912189131891418915189161891718918189191892018921189221892318924189251892618927189281892918930189311893218933189341893518936189371893818939189401894118942189431894418945189461894718948189491895018951189521895318954189551895618957189581895918960189611896218963189641896518966189671896818969189701897118972189731897418975189761897718978189791898018981189821898318984189851898618987189881898918990189911899218993189941899518996189971899818999190001900119002190031900419005190061900719008190091901019011190121901319014190151901619017190181901919020190211902219023190241902519026190271902819029190301903119032190331903419035190361903719038190391904019041190421904319044190451904619047190481904919050190511905219053190541905519056190571905819059190601906119062190631906419065190661906719068190691907019071190721907319074190751907619077190781907919080190811908219083190841908519086190871908819089190901909119092190931909419095190961909719098190991910019101191021910319104191051910619107191081910919110191111911219113191141911519116191171911819119191201912119122191231912419125191261912719128191291913019131191321913319134191351913619137191381913919140191411914219143191441914519146191471914819149191501915119152191531915419155191561915719158191591916019161191621916319164191651916619167191681916919170191711917219173191741917519176191771917819179191801918119182191831918419185191861918719188191891919019191191921919319194191951919619197191981919919200192011920219203192041920519206192071920819209192101921119212192131921419215192161921719218192191922019221192221922319224192251922619227192281922919230192311923219233192341923519236192371923819239192401924119242192431924419245192461924719248192491925019251192521925319254192551925619257192581925919260192611926219263192641926519266192671926819269192701927119272192731927419275192761927719278192791928019281192821928319284192851928619287192881928919290192911929219293192941929519296192971929819299193001930119302193031930419305193061930719308193091931019311193121931319314193151931619317193181931919320193211932219323193241932519326193271932819329193301933119332193331933419335193361933719338193391934019341193421934319344193451934619347193481934919350193511935219353193541935519356193571935819359193601936119362193631936419365193661936719368193691937019371193721937319374193751937619377193781937919380193811938219383193841938519386193871938819389193901939119392193931939419395193961939719398193991940019401194021940319404194051940619407194081940919410194111941219413194141941519416194171941819419194201942119422194231942419425194261942719428194291943019431194321943319434194351943619437194381943919440194411944219443194441944519446194471944819449194501945119452194531945419455194561945719458194591946019461194621946319464194651946619467194681946919470194711947219473194741947519476194771947819479194801948119482194831948419485194861948719488194891949019491194921949319494194951949619497194981949919500195011950219503195041950519506195071950819509195101951119512195131951419515195161951719518195191952019521195221952319524195251952619527195281952919530195311953219533195341953519536195371953819539195401954119542195431954419545195461954719548195491955019551195521955319554195551955619557195581955919560195611956219563195641956519566195671956819569195701957119572195731957419575195761957719578195791958019581195821958319584195851958619587195881958919590195911959219593195941959519596195971959819599196001960119602196031960419605196061960719608196091961019611196121961319614196151961619617196181961919620196211962219623196241962519626196271962819629196301963119632196331963419635196361963719638196391964019641196421964319644196451964619647196481964919650196511965219653196541965519656196571965819659196601966119662196631966419665196661966719668196691967019671196721967319674196751967619677196781967919680196811968219683196841968519686196871968819689196901969119692196931969419695196961969719698196991970019701197021970319704197051970619707197081970919710197111971219713197141971519716197171971819719197201972119722197231972419725197261972719728197291973019731197321973319734197351973619737197381973919740197411974219743197441974519746197471974819749197501975119752197531975419755197561975719758197591976019761197621976319764197651976619767197681976919770197711977219773197741977519776197771977819779197801978119782197831978419785197861978719788197891979019791197921979319794197951979619797197981979919800198011980219803198041980519806198071980819809198101981119812198131981419815198161981719818198191982019821198221982319824198251982619827198281982919830198311983219833198341983519836198371983819839198401984119842198431984419845198461984719848198491985019851198521985319854198551985619857198581985919860198611986219863198641986519866198671986819869198701987119872198731987419875198761987719878198791988019881198821988319884198851988619887198881988919890198911989219893198941989519896198971989819899199001990119902199031990419905199061990719908199091991019911199121991319914199151991619917199181991919920199211992219923199241992519926199271992819929199301993119932199331993419935199361993719938199391994019941199421994319944199451994619947199481994919950199511995219953199541995519956199571995819959199601996119962199631996419965199661996719968199691997019971199721997319974199751997619977199781997919980199811998219983199841998519986199871998819989199901999119992199931999419995199961999719998199992000020001200022000320004200052000620007200082000920010200112001220013200142001520016200172001820019200202002120022200232002420025200262002720028200292003020031200322003320034200352003620037200382003920040200412004220043200442004520046200472004820049200502005120052200532005420055200562005720058200592006020061200622006320064200652006620067200682006920070200712007220073200742007520076200772007820079200802008120082200832008420085200862008720088200892009020091200922009320094200952009620097200982009920100201012010220103201042010520106201072010820109201102011120112201132011420115201162011720118201192012020121201222012320124201252012620127201282012920130201312013220133201342013520136201372013820139201402014120142201432014420145201462014720148201492015020151201522015320154201552015620157201582015920160201612016220163201642016520166201672016820169201702017120172201732017420175201762017720178201792018020181201822018320184201852018620187201882018920190201912019220193201942019520196201972019820199202002020120202202032020420205202062020720208202092021020211202122021320214202152021620217202182021920220202212022220223202242022520226202272022820229202302023120232202332023420235202362023720238202392024020241202422024320244202452024620247202482024920250202512025220253202542025520256202572025820259202602026120262202632026420265202662026720268202692027020271202722027320274202752027620277202782027920280202812028220283202842028520286202872028820289202902029120292202932029420295202962029720298202992030020301203022030320304203052030620307203082030920310203112031220313203142031520316203172031820319203202032120322203232032420325203262032720328203292033020331203322033320334203352033620337203382033920340203412034220343203442034520346203472034820349203502035120352203532035420355203562035720358203592036020361203622036320364203652036620367203682036920370203712037220373203742037520376203772037820379203802038120382203832038420385203862038720388203892039020391203922039320394203952039620397203982039920400204012040220403204042040520406204072040820409204102041120412204132041420415204162041720418204192042020421204222042320424204252042620427204282042920430204312043220433204342043520436204372043820439204402044120442204432044420445204462044720448204492045020451204522045320454204552045620457204582045920460204612046220463204642046520466204672046820469204702047120472204732047420475204762047720478204792048020481204822048320484204852048620487204882048920490204912049220493204942049520496204972049820499205002050120502205032050420505205062050720508205092051020511205122051320514205152051620517205182051920520205212052220523205242052520526205272052820529205302053120532205332053420535205362053720538205392054020541205422054320544205452054620547205482054920550205512055220553205542055520556205572055820559205602056120562205632056420565205662056720568205692057020571205722057320574205752057620577205782057920580205812058220583205842058520586205872058820589205902059120592205932059420595205962059720598205992060020601206022060320604206052060620607206082060920610206112061220613206142061520616206172061820619206202062120622206232062420625206262062720628206292063020631206322063320634206352063620637206382063920640206412064220643206442064520646206472064820649206502065120652206532065420655206562065720658206592066020661206622066320664206652066620667206682066920670206712067220673206742067520676206772067820679206802068120682206832068420685206862068720688206892069020691206922069320694206952069620697206982069920700207012070220703207042070520706207072070820709207102071120712207132071420715207162071720718207192072020721207222072320724207252072620727207282072920730207312073220733207342073520736207372073820739207402074120742207432074420745207462074720748207492075020751207522075320754207552075620757207582075920760207612076220763207642076520766207672076820769207702077120772207732077420775207762077720778207792078020781207822078320784207852078620787207882078920790207912079220793207942079520796207972079820799208002080120802208032080420805208062080720808208092081020811208122081320814208152081620817208182081920820208212082220823208242082520826208272082820829208302083120832208332083420835208362083720838208392084020841208422084320844208452084620847208482084920850208512085220853208542085520856208572085820859208602086120862208632086420865208662086720868208692087020871208722087320874208752087620877208782087920880208812088220883208842088520886208872088820889208902089120892208932089420895208962089720898208992090020901209022090320904209052090620907209082090920910209112091220913209142091520916209172091820919209202092120922209232092420925209262092720928209292093020931209322093320934209352093620937209382093920940209412094220943209442094520946209472094820949209502095120952209532095420955209562095720958209592096020961209622096320964209652096620967209682096920970209712097220973209742097520976209772097820979209802098120982209832098420985209862098720988209892099020991209922099320994209952099620997209982099921000210012100221003210042100521006210072100821009210102101121012210132101421015210162101721018210192102021021210222102321024210252102621027210282102921030210312103221033210342103521036210372103821039210402104121042210432104421045210462104721048210492105021051210522105321054210552105621057210582105921060210612106221063210642106521066210672106821069210702107121072210732107421075210762107721078210792108021081210822108321084210852108621087210882108921090210912109221093210942109521096210972109821099211002110121102211032110421105211062110721108211092111021111211122111321114211152111621117211182111921120211212112221123211242112521126211272112821129211302113121132211332113421135211362113721138211392114021141211422114321144211452114621147211482114921150211512115221153211542115521156211572115821159211602116121162211632116421165211662116721168211692117021171211722117321174211752117621177211782117921180211812118221183211842118521186211872118821189211902119121192211932119421195211962119721198211992120021201212022120321204212052120621207212082120921210212112121221213212142121521216212172121821219212202122121222212232122421225212262122721228212292123021231212322123321234212352123621237212382123921240212412124221243212442124521246212472124821249212502125121252212532125421255212562125721258212592126021261212622126321264212652126621267212682126921270212712127221273212742127521276212772127821279212802128121282212832128421285212862128721288212892129021291212922129321294212952129621297212982129921300213012130221303213042130521306213072130821309213102131121312213132131421315213162131721318213192132021321213222132321324213252132621327213282132921330213312133221333213342133521336213372133821339213402134121342213432134421345213462134721348213492135021351213522135321354213552135621357213582135921360213612136221363213642136521366213672136821369213702137121372213732137421375213762137721378213792138021381213822138321384213852138621387213882138921390213912139221393213942139521396213972139821399214002140121402214032140421405214062140721408214092141021411214122141321414214152141621417214182141921420214212142221423214242142521426214272142821429214302143121432214332143421435214362143721438214392144021441214422144321444214452144621447214482144921450214512145221453214542145521456214572145821459214602146121462214632146421465214662146721468214692147021471214722147321474214752147621477214782147921480214812148221483214842148521486214872148821489214902149121492214932149421495214962149721498214992150021501215022150321504215052150621507215082150921510215112151221513215142151521516215172151821519215202152121522215232152421525215262152721528215292153021531215322153321534215352153621537215382153921540215412154221543215442154521546215472154821549215502155121552215532155421555215562155721558215592156021561215622156321564215652156621567215682156921570215712157221573215742157521576215772157821579215802158121582215832158421585215862158721588215892159021591215922159321594215952159621597215982159921600216012160221603216042160521606216072160821609216102161121612216132161421615216162161721618216192162021621216222162321624216252162621627216282162921630216312163221633216342163521636216372163821639216402164121642216432164421645216462164721648216492165021651216522165321654216552165621657216582165921660216612166221663216642166521666216672166821669216702167121672216732167421675216762167721678216792168021681216822168321684216852168621687216882168921690216912169221693216942169521696216972169821699217002170121702217032170421705217062170721708217092171021711217122171321714217152171621717217182171921720217212172221723217242172521726217272172821729217302173121732217332173421735217362173721738217392174021741217422174321744217452174621747217482174921750217512175221753217542175521756217572175821759217602176121762217632176421765217662176721768217692177021771217722177321774217752177621777217782177921780217812178221783217842178521786217872178821789217902179121792217932179421795217962179721798217992180021801218022180321804218052180621807218082180921810218112181221813218142181521816218172181821819218202182121822218232182421825218262182721828218292183021831218322183321834218352183621837218382183921840218412184221843218442184521846218472184821849218502185121852218532185421855218562185721858218592186021861218622186321864218652186621867218682186921870218712187221873218742187521876218772187821879218802188121882218832188421885218862188721888218892189021891218922189321894218952189621897218982189921900219012190221903219042190521906219072190821909219102191121912219132191421915219162191721918219192192021921219222192321924219252192621927219282192921930219312193221933219342193521936219372193821939219402194121942219432194421945219462194721948219492195021951219522195321954219552195621957219582195921960219612196221963219642196521966219672196821969219702197121972219732197421975219762197721978219792198021981219822198321984219852198621987219882198921990219912199221993219942199521996219972199821999220002200122002220032200422005220062200722008220092201022011220122201322014220152201622017220182201922020220212202222023220242202522026220272202822029220302203122032220332203422035220362203722038220392204022041220422204322044220452204622047220482204922050220512205222053220542205522056220572205822059220602206122062220632206422065220662206722068220692207022071220722207322074220752207622077220782207922080220812208222083220842208522086220872208822089220902209122092220932209422095220962209722098220992210022101221022210322104221052210622107221082210922110221112211222113221142211522116221172211822119221202212122122221232212422125221262212722128221292213022131221322213322134221352213622137221382213922140221412214222143221442214522146221472214822149221502215122152221532215422155221562215722158221592216022161221622216322164221652216622167221682216922170221712217222173221742217522176221772217822179221802218122182221832218422185221862218722188221892219022191221922219322194221952219622197221982219922200222012220222203222042220522206222072220822209222102221122212222132221422215222162221722218222192222022221222222222322224222252222622227222282222922230222312223222233222342223522236222372223822239222402224122242222432224422245222462224722248222492225022251222522225322254222552225622257222582225922260222612226222263222642226522266222672226822269222702227122272222732227422275222762227722278222792228022281222822228322284222852228622287222882228922290222912229222293222942229522296222972229822299223002230122302223032230422305223062230722308223092231022311223122231322314223152231622317223182231922320223212232222323223242232522326223272232822329223302233122332223332233422335223362233722338223392234022341223422234322344223452234622347223482234922350223512235222353223542235522356223572235822359223602236122362223632236422365223662236722368223692237022371223722237322374223752237622377223782237922380223812238222383223842238522386223872238822389223902239122392223932239422395223962239722398223992240022401224022240322404224052240622407224082240922410224112241222413224142241522416224172241822419224202242122422224232242422425224262242722428224292243022431224322243322434224352243622437224382243922440224412244222443224442244522446224472244822449224502245122452224532245422455224562245722458224592246022461224622246322464224652246622467224682246922470224712247222473224742247522476224772247822479224802248122482224832248422485224862248722488224892249022491224922249322494224952249622497224982249922500225012250222503225042250522506225072250822509225102251122512225132251422515225162251722518225192252022521225222252322524225252252622527225282252922530225312253222533225342253522536225372253822539225402254122542225432254422545225462254722548225492255022551225522255322554225552255622557225582255922560225612256222563225642256522566225672256822569225702257122572225732257422575225762257722578225792258022581225822258322584225852258622587225882258922590225912259222593225942259522596225972259822599226002260122602226032260422605226062260722608226092261022611226122261322614226152261622617226182261922620226212262222623226242262522626226272262822629226302263122632226332263422635226362263722638226392264022641226422264322644226452264622647226482264922650226512265222653226542265522656226572265822659226602266122662226632266422665226662266722668226692267022671226722267322674226752267622677226782267922680226812268222683226842268522686226872268822689226902269122692226932269422695226962269722698226992270022701227022270322704227052270622707227082270922710227112271222713227142271522716227172271822719227202272122722227232272422725227262272722728227292273022731227322273322734227352273622737227382273922740227412274222743227442274522746227472274822749227502275122752227532275422755227562275722758227592276022761227622276322764227652276622767227682276922770227712277222773227742277522776227772277822779227802278122782227832278422785227862278722788227892279022791227922279322794227952279622797227982279922800228012280222803228042280522806228072280822809228102281122812228132281422815228162281722818228192282022821228222282322824228252282622827228282282922830228312283222833228342283522836228372283822839228402284122842228432284422845228462284722848228492285022851228522285322854228552285622857228582285922860228612286222863228642286522866228672286822869228702287122872228732287422875228762287722878228792288022881228822288322884228852288622887228882288922890228912289222893228942289522896228972289822899229002290122902229032290422905229062290722908229092291022911229122291322914229152291622917229182291922920229212292222923229242292522926229272292822929229302293122932229332293422935229362293722938229392294022941229422294322944229452294622947229482294922950229512295222953229542295522956229572295822959229602296122962229632296422965229662296722968229692297022971229722297322974229752297622977229782297922980229812298222983229842298522986229872298822989229902299122992229932299422995229962299722998229992300023001230022300323004230052300623007230082300923010230112301223013230142301523016230172301823019230202302123022230232302423025230262302723028230292303023031230322303323034230352303623037230382303923040230412304223043230442304523046230472304823049230502305123052230532305423055230562305723058230592306023061230622306323064230652306623067230682306923070230712307223073230742307523076230772307823079230802308123082230832308423085230862308723088230892309023091230922309323094230952309623097230982309923100231012310223103231042310523106231072310823109231102311123112231132311423115231162311723118231192312023121231222312323124231252312623127231282312923130231312313223133231342313523136231372313823139231402314123142231432314423145231462314723148231492315023151231522315323154231552315623157231582315923160231612316223163231642316523166231672316823169231702317123172231732317423175231762317723178231792318023181231822318323184231852318623187231882318923190231912319223193231942319523196231972319823199232002320123202232032320423205232062320723208232092321023211232122321323214232152321623217232182321923220232212322223223232242322523226232272322823229232302323123232232332323423235232362323723238232392324023241232422324323244232452324623247232482324923250232512325223253232542325523256232572325823259232602326123262232632326423265232662326723268232692327023271232722327323274232752327623277232782327923280232812328223283232842328523286232872328823289232902329123292232932329423295232962329723298232992330023301233022330323304233052330623307233082330923310233112331223313233142331523316233172331823319233202332123322233232332423325233262332723328233292333023331233322333323334233352333623337233382333923340233412334223343233442334523346233472334823349233502335123352233532335423355233562335723358233592336023361233622336323364233652336623367233682336923370233712337223373233742337523376233772337823379233802338123382233832338423385233862338723388233892339023391233922339323394233952339623397233982339923400234012340223403234042340523406234072340823409234102341123412234132341423415234162341723418234192342023421234222342323424234252342623427234282342923430234312343223433234342343523436234372343823439234402344123442234432344423445234462344723448234492345023451234522345323454234552345623457234582345923460234612346223463234642346523466234672346823469234702347123472234732347423475234762347723478234792348023481234822348323484234852348623487234882348923490234912349223493234942349523496234972349823499235002350123502235032350423505235062350723508235092351023511235122351323514235152351623517235182351923520235212352223523235242352523526235272352823529235302353123532235332353423535235362353723538235392354023541235422354323544235452354623547235482354923550235512355223553235542355523556235572355823559235602356123562235632356423565235662356723568235692357023571235722357323574235752357623577235782357923580235812358223583235842358523586235872358823589235902359123592235932359423595235962359723598235992360023601236022360323604236052360623607236082360923610236112361223613236142361523616236172361823619236202362123622236232362423625236262362723628236292363023631236322363323634236352363623637236382363923640236412364223643236442364523646236472364823649236502365123652236532365423655236562365723658236592366023661236622366323664236652366623667236682366923670236712367223673236742367523676236772367823679236802368123682236832368423685236862368723688236892369023691236922369323694236952369623697236982369923700237012370223703237042370523706237072370823709237102371123712237132371423715237162371723718237192372023721237222372323724237252372623727237282372923730237312373223733237342373523736237372373823739237402374123742237432374423745237462374723748237492375023751237522375323754237552375623757237582375923760237612376223763237642376523766237672376823769237702377123772237732377423775237762377723778237792378023781237822378323784237852378623787237882378923790237912379223793237942379523796237972379823799238002380123802238032380423805238062380723808238092381023811238122381323814238152381623817238182381923820238212382223823238242382523826238272382823829238302383123832238332383423835238362383723838238392384023841238422384323844238452384623847238482384923850238512385223853238542385523856238572385823859238602386123862238632386423865238662386723868238692387023871238722387323874238752387623877238782387923880238812388223883238842388523886238872388823889238902389123892238932389423895238962389723898238992390023901239022390323904239052390623907239082390923910239112391223913239142391523916239172391823919239202392123922239232392423925239262392723928239292393023931239322393323934239352393623937239382393923940239412394223943239442394523946239472394823949239502395123952239532395423955239562395723958239592396023961239622396323964239652396623967239682396923970239712397223973239742397523976239772397823979239802398123982239832398423985239862398723988239892399023991239922399323994239952399623997239982399924000240012400224003240042400524006240072400824009240102401124012240132401424015240162401724018240192402024021240222402324024240252402624027240282402924030240312403224033240342403524036240372403824039240402404124042240432404424045240462404724048240492405024051240522405324054240552405624057240582405924060240612406224063240642406524066240672406824069240702407124072240732407424075240762407724078240792408024081240822408324084240852408624087240882408924090240912409224093240942409524096240972409824099241002410124102241032410424105241062410724108241092411024111241122411324114241152411624117241182411924120241212412224123241242412524126241272412824129241302413124132241332413424135241362413724138241392414024141241422414324144241452414624147241482414924150241512415224153241542415524156241572415824159241602416124162241632416424165241662416724168241692417024171241722417324174241752417624177241782417924180241812418224183241842418524186241872418824189241902419124192241932419424195241962419724198241992420024201242022420324204242052420624207242082420924210242112421224213242142421524216242172421824219242202422124222242232422424225242262422724228242292423024231242322423324234242352423624237242382423924240242412424224243242442424524246242472424824249242502425124252242532425424255242562425724258242592426024261242622426324264242652426624267242682426924270242712427224273242742427524276242772427824279242802428124282242832428424285242862428724288242892429024291242922429324294242952429624297242982429924300243012430224303243042430524306243072430824309243102431124312243132431424315243162431724318243192432024321243222432324324243252432624327243282432924330243312433224333243342433524336243372433824339243402434124342243432434424345243462434724348243492435024351243522435324354243552435624357243582435924360243612436224363243642436524366243672436824369243702437124372243732437424375243762437724378243792438024381243822438324384243852438624387243882438924390243912439224393243942439524396243972439824399244002440124402244032440424405244062440724408244092441024411244122441324414244152441624417244182441924420244212442224423244242442524426244272442824429244302443124432244332443424435244362443724438244392444024441244422444324444244452444624447244482444924450244512445224453244542445524456244572445824459244602446124462244632446424465244662446724468244692447024471244722447324474244752447624477244782447924480244812448224483244842448524486244872448824489244902449124492244932449424495244962449724498244992450024501245022450324504245052450624507245082450924510245112451224513245142451524516245172451824519245202452124522245232452424525245262452724528245292453024531245322453324534245352453624537245382453924540245412454224543245442454524546245472454824549245502455124552245532455424555245562455724558245592456024561245622456324564245652456624567245682456924570245712457224573245742457524576245772457824579245802458124582245832458424585245862458724588245892459024591245922459324594245952459624597245982459924600246012460224603246042460524606246072460824609246102461124612246132461424615246162461724618246192462024621246222462324624246252462624627246282462924630246312463224633246342463524636246372463824639246402464124642246432464424645246462464724648246492465024651246522465324654246552465624657246582465924660246612466224663246642466524666246672466824669246702467124672246732467424675246762467724678246792468024681246822468324684246852468624687246882468924690246912469224693246942469524696246972469824699247002470124702247032470424705247062470724708247092471024711247122471324714247152471624717247182471924720247212472224723247242472524726247272472824729247302473124732247332473424735247362473724738247392474024741247422474324744247452474624747247482474924750247512475224753247542475524756247572475824759247602476124762247632476424765247662476724768247692477024771247722477324774247752477624777247782477924780247812478224783247842478524786247872478824789247902479124792247932479424795247962479724798247992480024801248022480324804248052480624807248082480924810248112481224813248142481524816248172481824819248202482124822248232482424825248262482724828248292483024831248322483324834248352483624837248382483924840248412484224843248442484524846248472484824849248502485124852248532485424855248562485724858248592486024861248622486324864248652486624867248682486924870248712487224873248742487524876248772487824879248802488124882248832488424885248862488724888248892489024891248922489324894248952489624897248982489924900249012490224903249042490524906249072490824909249102491124912249132491424915249162491724918249192492024921249222492324924249252492624927249282492924930249312493224933249342493524936249372493824939249402494124942249432494424945249462494724948249492495024951249522495324954249552495624957249582495924960249612496224963249642496524966249672496824969249702497124972249732497424975249762497724978249792498024981249822498324984249852498624987249882498924990249912499224993249942499524996249972499824999250002500125002250032500425005250062500725008250092501025011250122501325014250152501625017250182501925020250212502225023250242502525026250272502825029250302503125032250332503425035250362503725038250392504025041250422504325044250452504625047250482504925050250512505225053250542505525056250572505825059250602506125062250632506425065250662506725068250692507025071250722507325074250752507625077250782507925080250812508225083250842508525086250872508825089250902509125092250932509425095250962509725098250992510025101251022510325104251052510625107251082510925110251112511225113251142511525116251172511825119251202512125122251232512425125251262512725128251292513025131251322513325134251352513625137251382513925140251412514225143251442514525146251472514825149251502515125152251532515425155251562515725158251592516025161251622516325164251652516625167251682516925170251712517225173251742517525176251772517825179251802518125182251832518425185251862518725188251892519025191251922519325194251952519625197251982519925200252012520225203252042520525206252072520825209252102521125212252132521425215252162521725218252192522025221252222522325224252252522625227252282522925230252312523225233252342523525236252372523825239252402524125242252432524425245252462524725248252492525025251252522525325254252552525625257252582525925260252612526225263252642526525266252672526825269252702527125272252732527425275252762527725278252792528025281252822528325284252852528625287252882528925290252912529225293252942529525296252972529825299253002530125302253032530425305253062530725308253092531025311253122531325314253152531625317253182531925320253212532225323253242532525326253272532825329253302533125332253332533425335253362533725338253392534025341253422534325344253452534625347253482534925350253512535225353253542535525356253572535825359253602536125362253632536425365253662536725368253692537025371253722537325374253752537625377253782537925380253812538225383253842538525386253872538825389253902539125392253932539425395253962539725398253992540025401254022540325404254052540625407254082540925410254112541225413254142541525416254172541825419254202542125422254232542425425254262542725428254292543025431254322543325434254352543625437254382543925440254412544225443254442544525446254472544825449254502545125452254532545425455254562545725458254592546025461254622546325464254652546625467254682546925470254712547225473254742547525476254772547825479254802548125482254832548425485254862548725488254892549025491254922549325494254952549625497254982549925500255012550225503255042550525506255072550825509255102551125512255132551425515255162551725518255192552025521255222552325524255252552625527255282552925530255312553225533255342553525536255372553825539255402554125542255432554425545255462554725548255492555025551255522555325554255552555625557255582555925560255612556225563255642556525566255672556825569255702557125572255732557425575255762557725578255792558025581255822558325584255852558625587255882558925590255912559225593255942559525596255972559825599256002560125602256032560425605256062560725608256092561025611256122561325614256152561625617256182561925620256212562225623256242562525626256272562825629256302563125632256332563425635256362563725638256392564025641256422564325644256452564625647256482564925650256512565225653256542565525656256572565825659256602566125662256632566425665256662566725668256692567025671256722567325674256752567625677256782567925680256812568225683256842568525686256872568825689256902569125692256932569425695256962569725698256992570025701257022570325704257052570625707257082570925710257112571225713257142571525716257172571825719257202572125722257232572425725257262572725728257292573025731257322573325734257352573625737257382573925740257412574225743257442574525746257472574825749257502575125752257532575425755257562575725758257592576025761257622576325764257652576625767257682576925770257712577225773257742577525776257772577825779257802578125782257832578425785257862578725788257892579025791257922579325794257952579625797257982579925800258012580225803258042580525806258072580825809258102581125812258132581425815258162581725818258192582025821258222582325824258252582625827258282582925830258312583225833258342583525836258372583825839258402584125842258432584425845258462584725848258492585025851258522585325854258552585625857258582585925860258612586225863258642586525866258672586825869258702587125872258732587425875258762587725878258792588025881258822588325884258852588625887258882588925890258912589225893258942589525896258972589825899259002590125902259032590425905259062590725908259092591025911259122591325914259152591625917259182591925920259212592225923259242592525926259272592825929259302593125932259332593425935259362593725938259392594025941259422594325944259452594625947259482594925950259512595225953259542595525956259572595825959259602596125962259632596425965259662596725968259692597025971259722597325974259752597625977259782597925980259812598225983259842598525986259872598825989259902599125992259932599425995259962599725998259992600026001260022600326004260052600626007260082600926010260112601226013260142601526016260172601826019260202602126022260232602426025260262602726028260292603026031260322603326034260352603626037260382603926040260412604226043260442604526046260472604826049260502605126052260532605426055260562605726058260592606026061260622606326064260652606626067260682606926070260712607226073260742607526076260772607826079260802608126082260832608426085260862608726088260892609026091260922609326094260952609626097260982609926100261012610226103261042610526106261072610826109261102611126112261132611426115261162611726118261192612026121261222612326124261252612626127261282612926130261312613226133261342613526136261372613826139261402614126142261432614426145261462614726148261492615026151261522615326154261552615626157261582615926160261612616226163261642616526166261672616826169261702617126172261732617426175261762617726178261792618026181261822618326184261852618626187261882618926190261912619226193261942619526196261972619826199262002620126202262032620426205262062620726208262092621026211262122621326214262152621626217262182621926220262212622226223262242622526226262272622826229262302623126232262332623426235262362623726238262392624026241262422624326244262452624626247262482624926250262512625226253262542625526256262572625826259262602626126262262632626426265262662626726268262692627026271262722627326274262752627626277262782627926280262812628226283262842628526286262872628826289262902629126292262932629426295262962629726298262992630026301263022630326304263052630626307263082630926310263112631226313263142631526316263172631826319263202632126322263232632426325263262632726328263292633026331263322633326334263352633626337263382633926340263412634226343263442634526346263472634826349263502635126352263532635426355263562635726358263592636026361263622636326364263652636626367263682636926370263712637226373263742637526376263772637826379263802638126382263832638426385263862638726388263892639026391263922639326394263952639626397263982639926400264012640226403264042640526406264072640826409264102641126412264132641426415264162641726418264192642026421264222642326424264252642626427264282642926430264312643226433264342643526436264372643826439264402644126442264432644426445264462644726448264492645026451264522645326454264552645626457264582645926460264612646226463264642646526466264672646826469264702647126472264732647426475264762647726478264792648026481264822648326484264852648626487264882648926490264912649226493264942649526496264972649826499265002650126502265032650426505265062650726508265092651026511265122651326514265152651626517265182651926520265212652226523265242652526526265272652826529265302653126532265332653426535265362653726538265392654026541265422654326544265452654626547265482654926550265512655226553265542655526556265572655826559265602656126562265632656426565265662656726568265692657026571265722657326574265752657626577265782657926580265812658226583265842658526586265872658826589265902659126592265932659426595265962659726598265992660026601266022660326604266052660626607266082660926610266112661226613266142661526616266172661826619266202662126622266232662426625266262662726628266292663026631266322663326634266352663626637266382663926640266412664226643266442664526646266472664826649266502665126652266532665426655266562665726658266592666026661266622666326664266652666626667266682666926670266712667226673266742667526676266772667826679266802668126682266832668426685266862668726688266892669026691266922669326694266952669626697266982669926700267012670226703267042670526706267072670826709267102671126712267132671426715267162671726718267192672026721267222672326724267252672626727267282672926730267312673226733267342673526736267372673826739267402674126742267432674426745267462674726748267492675026751267522675326754267552675626757267582675926760267612676226763267642676526766267672676826769267702677126772267732677426775267762677726778267792678026781267822678326784267852678626787267882678926790267912679226793267942679526796267972679826799268002680126802268032680426805268062680726808268092681026811268122681326814268152681626817268182681926820268212682226823268242682526826268272682826829268302683126832268332683426835268362683726838268392684026841268422684326844268452684626847268482684926850268512685226853268542685526856268572685826859268602686126862268632686426865268662686726868268692687026871268722687326874268752687626877268782687926880268812688226883268842688526886268872688826889268902689126892268932689426895268962689726898268992690026901269022690326904269052690626907269082690926910269112691226913269142691526916269172691826919269202692126922269232692426925269262692726928269292693026931269322693326934269352693626937269382693926940269412694226943269442694526946269472694826949269502695126952269532695426955269562695726958269592696026961269622696326964269652696626967269682696926970269712697226973269742697526976269772697826979269802698126982269832698426985269862698726988269892699026991269922699326994269952699626997269982699927000270012700227003270042700527006270072700827009270102701127012270132701427015270162701727018270192702027021270222702327024270252702627027270282702927030270312703227033270342703527036270372703827039270402704127042270432704427045270462704727048270492705027051270522705327054270552705627057270582705927060270612706227063270642706527066270672706827069270702707127072270732707427075270762707727078270792708027081270822708327084270852708627087270882708927090270912709227093270942709527096270972709827099271002710127102271032710427105271062710727108271092711027111271122711327114271152711627117271182711927120271212712227123271242712527126271272712827129271302713127132271332713427135271362713727138271392714027141271422714327144271452714627147271482714927150271512715227153271542715527156271572715827159271602716127162271632716427165271662716727168271692717027171271722717327174271752717627177271782717927180271812718227183271842718527186271872718827189271902719127192271932719427195271962719727198271992720027201272022720327204272052720627207272082720927210272112721227213272142721527216272172721827219272202722127222272232722427225272262722727228272292723027231272322723327234272352723627237272382723927240272412724227243272442724527246272472724827249272502725127252272532725427255272562725727258272592726027261272622726327264272652726627267272682726927270272712727227273272742727527276272772727827279272802728127282272832728427285272862728727288272892729027291272922729327294272952729627297272982729927300273012730227303273042730527306273072730827309273102731127312273132731427315273162731727318273192732027321273222732327324273252732627327273282732927330273312733227333273342733527336273372733827339273402734127342273432734427345273462734727348273492735027351273522735327354273552735627357273582735927360273612736227363273642736527366273672736827369273702737127372273732737427375273762737727378273792738027381273822738327384273852738627387273882738927390273912739227393273942739527396273972739827399274002740127402274032740427405274062740727408274092741027411274122741327414274152741627417274182741927420274212742227423274242742527426274272742827429274302743127432274332743427435274362743727438274392744027441274422744327444274452744627447274482744927450274512745227453274542745527456274572745827459274602746127462274632746427465274662746727468274692747027471274722747327474274752747627477274782747927480274812748227483274842748527486274872748827489274902749127492274932749427495274962749727498274992750027501275022750327504275052750627507275082750927510275112751227513275142751527516275172751827519275202752127522275232752427525275262752727528275292753027531275322753327534275352753627537275382753927540275412754227543275442754527546275472754827549275502755127552275532755427555275562755727558275592756027561275622756327564275652756627567275682756927570275712757227573275742757527576275772757827579275802758127582275832758427585275862758727588275892759027591275922759327594275952759627597275982759927600276012760227603276042760527606276072760827609276102761127612276132761427615276162761727618276192762027621276222762327624276252762627627276282762927630276312763227633276342763527636276372763827639276402764127642276432764427645276462764727648276492765027651276522765327654276552765627657276582765927660276612766227663276642766527666276672766827669276702767127672276732767427675276762767727678276792768027681276822768327684276852768627687276882768927690276912769227693276942769527696276972769827699277002770127702277032770427705277062770727708277092771027711277122771327714277152771627717277182771927720277212772227723277242772527726277272772827729277302773127732277332773427735277362773727738277392774027741277422774327744277452774627747277482774927750277512775227753277542775527756277572775827759277602776127762277632776427765277662776727768277692777027771277722777327774277752777627777277782777927780277812778227783277842778527786277872778827789277902779127792277932779427795277962779727798277992780027801278022780327804278052780627807278082780927810278112781227813278142781527816278172781827819278202782127822278232782427825278262782727828278292783027831278322783327834278352783627837278382783927840278412784227843278442784527846278472784827849278502785127852278532785427855278562785727858278592786027861278622786327864278652786627867278682786927870278712787227873278742787527876278772787827879278802788127882278832788427885278862788727888278892789027891278922789327894278952789627897278982789927900279012790227903279042790527906279072790827909279102791127912279132791427915279162791727918279192792027921279222792327924279252792627927279282792927930279312793227933279342793527936279372793827939279402794127942279432794427945279462794727948279492795027951279522795327954279552795627957279582795927960279612796227963279642796527966279672796827969279702797127972279732797427975279762797727978279792798027981279822798327984279852798627987279882798927990279912799227993279942799527996279972799827999280002800128002280032800428005280062800728008280092801028011280122801328014280152801628017280182801928020280212802228023280242802528026280272802828029280302803128032280332803428035280362803728038280392804028041280422804328044280452804628047280482804928050280512805228053280542805528056280572805828059280602806128062280632806428065280662806728068280692807028071280722807328074280752807628077280782807928080280812808228083280842808528086280872808828089280902809128092280932809428095280962809728098280992810028101281022810328104281052810628107281082810928110281112811228113281142811528116281172811828119281202812128122281232812428125281262812728128281292813028131281322813328134281352813628137281382813928140281412814228143281442814528146281472814828149281502815128152281532815428155281562815728158281592816028161281622816328164281652816628167281682816928170281712817228173281742817528176281772817828179281802818128182281832818428185281862818728188281892819028191281922819328194281952819628197281982819928200282012820228203282042820528206282072820828209282102821128212282132821428215282162821728218282192822028221282222822328224282252822628227282282822928230282312823228233282342823528236282372823828239282402824128242282432824428245282462824728248282492825028251282522825328254282552825628257282582825928260282612826228263282642826528266282672826828269282702827128272282732827428275282762827728278282792828028281282822828328284282852828628287282882828928290282912829228293282942829528296282972829828299283002830128302283032830428305283062830728308283092831028311283122831328314283152831628317283182831928320283212832228323283242832528326283272832828329283302833128332283332833428335283362833728338283392834028341283422834328344283452834628347283482834928350283512835228353283542835528356283572835828359283602836128362283632836428365283662836728368283692837028371283722837328374283752837628377283782837928380283812838228383283842838528386283872838828389283902839128392283932839428395283962839728398283992840028401284022840328404284052840628407284082840928410284112841228413284142841528416284172841828419284202842128422284232842428425284262842728428284292843028431284322843328434284352843628437284382843928440284412844228443284442844528446284472844828449284502845128452284532845428455284562845728458284592846028461284622846328464284652846628467284682846928470284712847228473284742847528476284772847828479284802848128482284832848428485284862848728488284892849028491284922849328494284952849628497284982849928500285012850228503285042850528506285072850828509285102851128512285132851428515285162851728518285192852028521285222852328524285252852628527285282852928530285312853228533285342853528536285372853828539285402854128542285432854428545285462854728548285492855028551285522855328554285552855628557285582855928560285612856228563285642856528566285672856828569285702857128572285732857428575285762857728578285792858028581285822858328584285852858628587285882858928590285912859228593285942859528596285972859828599286002860128602286032860428605286062860728608286092861028611286122861328614286152861628617286182861928620286212862228623286242862528626286272862828629286302863128632286332863428635286362863728638286392864028641286422864328644286452864628647286482864928650286512865228653286542865528656286572865828659286602866128662286632866428665286662866728668286692867028671286722867328674286752867628677286782867928680286812868228683286842868528686286872868828689286902869128692286932869428695286962869728698286992870028701287022870328704287052870628707287082870928710287112871228713287142871528716287172871828719287202872128722287232872428725287262872728728287292873028731287322873328734287352873628737287382873928740287412874228743287442874528746287472874828749287502875128752287532875428755287562875728758287592876028761287622876328764287652876628767287682876928770287712877228773287742877528776287772877828779287802878128782287832878428785287862878728788287892879028791287922879328794287952879628797287982879928800288012880228803288042880528806288072880828809288102881128812288132881428815288162881728818288192882028821288222882328824288252882628827288282882928830288312883228833288342883528836288372883828839288402884128842288432884428845288462884728848288492885028851288522885328854288552885628857288582885928860288612886228863288642886528866288672886828869288702887128872288732887428875288762887728878288792888028881288822888328884288852888628887288882888928890288912889228893288942889528896288972889828899289002890128902289032890428905289062890728908289092891028911289122891328914289152891628917289182891928920289212892228923289242892528926289272892828929289302893128932289332893428935289362893728938289392894028941289422894328944289452894628947289482894928950289512895228953289542895528956289572895828959289602896128962289632896428965289662896728968289692897028971289722897328974289752897628977289782897928980289812898228983289842898528986289872898828989289902899128992289932899428995289962899728998289992900029001290022900329004290052900629007290082900929010290112901229013290142901529016290172901829019290202902129022290232902429025290262902729028290292903029031290322903329034290352903629037290382903929040290412904229043290442904529046290472904829049290502905129052290532905429055290562905729058290592906029061290622906329064290652906629067290682906929070290712907229073290742907529076290772907829079290802908129082290832908429085290862908729088290892909029091290922909329094290952909629097290982909929100291012910229103291042910529106291072910829109291102911129112291132911429115291162911729118291192912029121291222912329124291252912629127291282912929130291312913229133291342913529136291372913829139291402914129142291432914429145291462914729148291492915029151291522915329154291552915629157291582915929160291612916229163291642916529166291672916829169291702917129172291732917429175291762917729178291792918029181291822918329184291852918629187291882918929190291912919229193291942919529196291972919829199292002920129202292032920429205292062920729208292092921029211292122921329214292152921629217292182921929220292212922229223292242922529226292272922829229292302923129232292332923429235292362923729238292392924029241292422924329244292452924629247292482924929250292512925229253292542925529256292572925829259292602926129262292632926429265292662926729268292692927029271292722927329274292752927629277292782927929280292812928229283292842928529286292872928829289292902929129292292932929429295292962929729298292992930029301293022930329304293052930629307293082930929310293112931229313293142931529316293172931829319293202932129322293232932429325293262932729328293292933029331293322933329334293352933629337293382933929340293412934229343293442934529346293472934829349293502935129352293532935429355293562935729358293592936029361293622936329364293652936629367293682936929370293712937229373293742937529376293772937829379293802938129382293832938429385293862938729388293892939029391293922939329394293952939629397293982939929400294012940229403294042940529406294072940829409294102941129412294132941429415294162941729418294192942029421294222942329424294252942629427294282942929430294312943229433294342943529436294372943829439294402944129442294432944429445294462944729448294492945029451294522945329454294552945629457294582945929460294612946229463294642946529466294672946829469294702947129472294732947429475294762947729478294792948029481294822948329484294852948629487294882948929490294912949229493294942949529496294972949829499295002950129502295032950429505295062950729508295092951029511295122951329514295152951629517295182951929520295212952229523295242952529526295272952829529295302953129532295332953429535295362953729538295392954029541295422954329544295452954629547295482954929550295512955229553295542955529556295572955829559295602956129562295632956429565295662956729568295692957029571295722957329574295752957629577295782957929580295812958229583295842958529586295872958829589295902959129592295932959429595295962959729598295992960029601296022960329604296052960629607296082960929610296112961229613296142961529616296172961829619296202962129622296232962429625296262962729628296292963029631296322963329634296352963629637296382963929640296412964229643296442964529646296472964829649296502965129652296532965429655296562965729658296592966029661296622966329664296652966629667296682966929670296712967229673296742967529676296772967829679296802968129682296832968429685296862968729688296892969029691296922969329694296952969629697296982969929700297012970229703297042970529706297072970829709297102971129712297132971429715297162971729718297192972029721297222972329724297252972629727297282972929730297312973229733297342973529736297372973829739297402974129742297432974429745297462974729748297492975029751297522975329754297552975629757297582975929760297612976229763297642976529766297672976829769297702977129772297732977429775297762977729778297792978029781297822978329784297852978629787297882978929790297912979229793297942979529796297972979829799298002980129802298032980429805298062980729808298092981029811298122981329814298152981629817298182981929820298212982229823298242982529826298272982829829298302983129832298332983429835298362983729838298392984029841298422984329844298452984629847298482984929850298512985229853298542985529856298572985829859298602986129862298632986429865298662986729868298692987029871298722987329874298752987629877298782987929880298812988229883298842988529886298872988829889298902989129892298932989429895298962989729898298992990029901299022990329904299052990629907299082990929910299112991229913299142991529916299172991829919299202992129922299232992429925299262992729928299292993029931299322993329934299352993629937299382993929940299412994229943299442994529946299472994829949299502995129952299532995429955299562995729958299592996029961299622996329964299652996629967299682996929970299712997229973299742997529976299772997829979299802998129982299832998429985299862998729988299892999029991299922999329994299952999629997299982999930000300013000230003300043000530006300073000830009300103001130012300133001430015300163001730018300193002030021300223002330024300253002630027300283002930030300313003230033300343003530036300373003830039300403004130042300433004430045300463004730048300493005030051300523005330054300553005630057300583005930060300613006230063300643006530066300673006830069300703007130072300733007430075300763007730078300793008030081300823008330084300853008630087300883008930090300913009230093300943009530096300973009830099301003010130102301033010430105301063010730108301093011030111301123011330114301153011630117301183011930120301213012230123301243012530126301273012830129301303013130132301333013430135301363013730138301393014030141301423014330144301453014630147301483014930150301513015230153301543015530156301573015830159301603016130162301633016430165301663016730168301693017030171301723017330174301753017630177301783017930180301813018230183301843018530186301873018830189301903019130192301933019430195301963019730198301993020030201302023020330204302053020630207302083020930210302113021230213302143021530216302173021830219302203022130222302233022430225302263022730228302293023030231302323023330234302353023630237302383023930240302413024230243302443024530246302473024830249302503025130252302533025430255302563025730258302593026030261302623026330264302653026630267302683026930270302713027230273302743027530276302773027830279302803028130282302833028430285302863028730288302893029030291302923029330294302953029630297302983029930300303013030230303303043030530306303073030830309303103031130312303133031430315303163031730318303193032030321303223032330324303253032630327303283032930330303313033230333303343033530336303373033830339303403034130342303433034430345303463034730348303493035030351303523035330354303553035630357303583035930360303613036230363303643036530366303673036830369303703037130372303733037430375303763037730378303793038030381303823038330384303853038630387303883038930390303913039230393303943039530396303973039830399304003040130402304033040430405304063040730408304093041030411304123041330414304153041630417304183041930420304213042230423304243042530426304273042830429304303043130432304333043430435304363043730438304393044030441304423044330444304453044630447304483044930450304513045230453304543045530456304573045830459304603046130462304633046430465304663046730468304693047030471304723047330474304753047630477304783047930480304813048230483304843048530486304873048830489304903049130492304933049430495304963049730498304993050030501305023050330504305053050630507305083050930510305113051230513305143051530516305173051830519305203052130522305233052430525305263052730528305293053030531305323053330534305353053630537305383053930540305413054230543305443054530546305473054830549305503055130552305533055430555305563055730558305593056030561305623056330564305653056630567305683056930570305713057230573305743057530576305773057830579305803058130582305833058430585305863058730588305893059030591305923059330594305953059630597305983059930600306013060230603306043060530606306073060830609306103061130612306133061430615306163061730618306193062030621306223062330624306253062630627306283062930630306313063230633306343063530636306373063830639306403064130642306433064430645306463064730648306493065030651306523065330654306553065630657306583065930660306613066230663306643066530666306673066830669306703067130672306733067430675306763067730678306793068030681306823068330684306853068630687306883068930690306913069230693306943069530696306973069830699307003070130702307033070430705307063070730708307093071030711307123071330714307153071630717307183071930720307213072230723307243072530726307273072830729307303073130732307333073430735307363073730738307393074030741307423074330744307453074630747307483074930750307513075230753307543075530756307573075830759307603076130762307633076430765307663076730768307693077030771307723077330774307753077630777307783077930780307813078230783307843078530786307873078830789307903079130792307933079430795307963079730798307993080030801308023080330804308053080630807308083080930810308113081230813308143081530816308173081830819308203082130822308233082430825308263082730828308293083030831308323083330834308353083630837308383083930840308413084230843308443084530846308473084830849308503085130852308533085430855308563085730858308593086030861308623086330864308653086630867308683086930870308713087230873308743087530876308773087830879308803088130882308833088430885308863088730888308893089030891308923089330894308953089630897308983089930900309013090230903309043090530906309073090830909309103091130912309133091430915309163091730918309193092030921309223092330924309253092630927309283092930930309313093230933309343093530936309373093830939309403094130942309433094430945309463094730948309493095030951309523095330954309553095630957309583095930960309613096230963309643096530966309673096830969309703097130972309733097430975309763097730978309793098030981309823098330984309853098630987309883098930990309913099230993309943099530996309973099830999310003100131002310033100431005310063100731008310093101031011310123101331014310153101631017310183101931020310213102231023310243102531026310273102831029310303103131032310333103431035310363103731038310393104031041310423104331044310453104631047310483104931050310513105231053310543105531056310573105831059310603106131062310633106431065310663106731068310693107031071310723107331074310753107631077310783107931080310813108231083310843108531086310873108831089310903109131092310933109431095310963109731098310993110031101311023110331104311053110631107311083110931110311113111231113311143111531116311173111831119311203112131122311233112431125311263112731128311293113031131311323113331134311353113631137311383113931140311413114231143311443114531146311473114831149311503115131152311533115431155311563115731158311593116031161311623116331164311653116631167311683116931170311713117231173311743117531176311773117831179311803118131182311833118431185311863118731188311893119031191311923119331194311953119631197311983119931200312013120231203312043120531206312073120831209312103121131212312133121431215312163121731218312193122031221312223122331224312253122631227312283122931230312313123231233312343123531236312373123831239312403124131242312433124431245312463124731248312493125031251312523125331254312553125631257312583125931260312613126231263312643126531266312673126831269312703127131272312733127431275312763127731278312793128031281312823128331284312853128631287312883128931290312913129231293312943129531296312973129831299313003130131302313033130431305313063130731308313093131031311313123131331314313153131631317313183131931320313213132231323313243132531326313273132831329313303133131332313333133431335313363133731338313393134031341313423134331344313453134631347313483134931350313513135231353313543135531356313573135831359313603136131362313633136431365313663136731368313693137031371313723137331374313753137631377313783137931380313813138231383313843138531386313873138831389313903139131392313933139431395313963139731398313993140031401314023140331404314053140631407314083140931410314113141231413314143141531416314173141831419314203142131422314233142431425314263142731428314293143031431314323143331434314353143631437314383143931440314413144231443314443144531446314473144831449314503145131452314533145431455314563145731458314593146031461314623146331464314653146631467314683146931470314713147231473314743147531476314773147831479314803148131482314833148431485314863148731488314893149031491314923149331494314953149631497314983149931500315013150231503315043150531506315073150831509315103151131512315133151431515315163151731518315193152031521315223152331524315253152631527315283152931530315313153231533315343153531536315373153831539315403154131542315433154431545315463154731548315493155031551315523155331554315553155631557315583155931560315613156231563315643156531566315673156831569315703157131572315733157431575315763157731578315793158031581315823158331584315853158631587315883158931590315913159231593315943159531596315973159831599316003160131602316033160431605316063160731608316093161031611316123161331614316153161631617316183161931620316213162231623316243162531626316273162831629316303163131632316333163431635316363163731638316393164031641316423164331644316453164631647316483164931650316513165231653316543165531656316573165831659316603166131662316633166431665316663166731668316693167031671316723167331674316753167631677316783167931680316813168231683316843168531686316873168831689316903169131692316933169431695316963169731698316993170031701317023170331704317053170631707317083170931710317113171231713317143171531716317173171831719317203172131722317233172431725317263172731728317293173031731317323173331734317353173631737317383173931740317413174231743317443174531746317473174831749317503175131752317533175431755317563175731758317593176031761317623176331764317653176631767317683176931770317713177231773317743177531776317773177831779317803178131782317833178431785317863178731788317893179031791317923179331794317953179631797317983179931800318013180231803318043180531806318073180831809318103181131812318133181431815318163181731818318193182031821318223182331824318253182631827318283182931830318313183231833318343183531836318373183831839318403184131842318433184431845318463184731848318493185031851318523185331854318553185631857318583185931860318613186231863318643186531866318673186831869318703187131872318733187431875318763187731878318793188031881318823188331884318853188631887318883188931890318913189231893318943189531896318973189831899319003190131902319033190431905319063190731908319093191031911319123191331914319153191631917319183191931920319213192231923319243192531926319273192831929319303193131932319333193431935319363193731938319393194031941319423194331944319453194631947319483194931950319513195231953319543195531956319573195831959319603196131962319633196431965319663196731968319693197031971319723197331974319753197631977319783197931980319813198231983319843198531986319873198831989319903199131992319933199431995319963199731998319993200032001320023200332004320053200632007320083200932010320113201232013320143201532016320173201832019320203202132022320233202432025320263202732028320293203032031320323203332034320353203632037320383203932040320413204232043320443204532046320473204832049320503205132052320533205432055320563205732058320593206032061320623206332064320653206632067320683206932070320713207232073320743207532076320773207832079320803208132082320833208432085320863208732088320893209032091320923209332094320953209632097320983209932100321013210232103321043210532106321073210832109321103211132112321133211432115321163211732118321193212032121321223212332124321253212632127321283212932130321313213232133321343213532136321373213832139321403214132142321433214432145321463214732148321493215032151321523215332154321553215632157321583215932160321613216232163321643216532166321673216832169321703217132172321733217432175321763217732178321793218032181321823218332184321853218632187321883218932190321913219232193321943219532196321973219832199322003220132202322033220432205322063220732208322093221032211322123221332214322153221632217322183221932220322213222232223322243222532226322273222832229322303223132232322333223432235322363223732238322393224032241322423224332244322453224632247322483224932250322513225232253322543225532256322573225832259322603226132262322633226432265322663226732268322693227032271322723227332274322753227632277322783227932280322813228232283322843228532286322873228832289322903229132292322933229432295322963229732298322993230032301323023230332304323053230632307323083230932310323113231232313323143231532316323173231832319323203232132322323233232432325323263232732328323293233032331323323233332334323353233632337323383233932340323413234232343323443234532346323473234832349323503235132352323533235432355323563235732358323593236032361323623236332364323653236632367323683236932370323713237232373323743237532376323773237832379323803238132382323833238432385323863238732388323893239032391323923239332394323953239632397323983239932400324013240232403324043240532406324073240832409324103241132412324133241432415324163241732418324193242032421324223242332424324253242632427324283242932430324313243232433324343243532436324373243832439324403244132442324433244432445324463244732448324493245032451324523245332454324553245632457324583245932460324613246232463324643246532466324673246832469324703247132472324733247432475324763247732478324793248032481324823248332484324853248632487324883248932490324913249232493324943249532496324973249832499325003250132502325033250432505325063250732508325093251032511325123251332514325153251632517325183251932520325213252232523325243252532526325273252832529325303253132532325333253432535325363253732538325393254032541325423254332544325453254632547325483254932550325513255232553325543255532556325573255832559325603256132562325633256432565325663256732568325693257032571325723257332574325753257632577325783257932580325813258232583325843258532586325873258832589325903259132592325933259432595325963259732598325993260032601326023260332604326053260632607326083260932610326113261232613326143261532616326173261832619326203262132622326233262432625326263262732628326293263032631326323263332634326353263632637326383263932640326413264232643326443264532646326473264832649326503265132652326533265432655326563265732658326593266032661326623266332664326653266632667326683266932670326713267232673326743267532676326773267832679326803268132682326833268432685326863268732688326893269032691326923269332694326953269632697326983269932700327013270232703327043270532706327073270832709327103271132712327133271432715327163271732718327193272032721327223272332724327253272632727327283272932730327313273232733327343273532736327373273832739327403274132742327433274432745327463274732748327493275032751327523275332754327553275632757327583275932760327613276232763327643276532766327673276832769327703277132772327733277432775327763277732778327793278032781327823278332784327853278632787327883278932790327913279232793327943279532796327973279832799328003280132802328033280432805328063280732808328093281032811328123281332814328153281632817328183281932820328213282232823328243282532826328273282832829328303283132832328333283432835328363283732838328393284032841328423284332844328453284632847328483284932850328513285232853328543285532856328573285832859328603286132862328633286432865328663286732868328693287032871328723287332874328753287632877328783287932880328813288232883328843288532886328873288832889328903289132892328933289432895328963289732898328993290032901329023290332904329053290632907329083290932910329113291232913329143291532916329173291832919329203292132922329233292432925329263292732928329293293032931329323293332934329353293632937329383293932940329413294232943329443294532946329473294832949329503295132952329533295432955329563295732958329593296032961329623296332964329653296632967329683296932970329713297232973329743297532976329773297832979329803298132982329833298432985329863298732988329893299032991329923299332994329953299632997329983299933000330013300233003330043300533006330073300833009330103301133012330133301433015330163301733018330193302033021330223302333024330253302633027330283302933030330313303233033330343303533036330373303833039330403304133042330433304433045330463304733048330493305033051330523305333054330553305633057330583305933060330613306233063330643306533066330673306833069330703307133072330733307433075330763307733078330793308033081330823308333084330853308633087330883308933090330913309233093330943309533096330973309833099331003310133102331033310433105331063310733108331093311033111331123311333114331153311633117331183311933120331213312233123331243312533126331273312833129331303313133132331333313433135331363313733138331393314033141331423314333144331453314633147331483314933150331513315233153331543315533156331573315833159331603316133162331633316433165331663316733168331693317033171331723317333174331753317633177331783317933180331813318233183331843318533186331873318833189331903319133192331933319433195331963319733198331993320033201332023320333204332053320633207332083320933210332113321233213332143321533216332173321833219332203322133222332233322433225332263322733228332293323033231332323323333234332353323633237332383323933240332413324233243332443324533246332473324833249332503325133252332533325433255332563325733258332593326033261332623326333264332653326633267332683326933270332713327233273332743327533276332773327833279332803328133282332833328433285332863328733288332893329033291332923329333294332953329633297332983329933300333013330233303333043330533306333073330833309333103331133312333133331433315333163331733318333193332033321333223332333324333253332633327333283332933330333313333233333333343333533336333373333833339333403334133342333433334433345333463334733348333493335033351333523335333354333553335633357333583335933360333613336233363333643336533366333673336833369333703337133372333733337433375333763337733378333793338033381333823338333384333853338633387333883338933390333913339233393333943339533396333973339833399334003340133402334033340433405334063340733408334093341033411334123341333414334153341633417334183341933420334213342233423334243342533426334273342833429334303343133432334333343433435334363343733438334393344033441334423344333444334453344633447334483344933450334513345233453334543345533456334573345833459334603346133462334633346433465334663346733468334693347033471334723347333474334753347633477334783347933480334813348233483334843348533486334873348833489334903349133492334933349433495334963349733498334993350033501335023350333504335053350633507335083350933510335113351233513335143351533516335173351833519335203352133522335233352433525335263352733528335293353033531335323353333534335353353633537335383353933540335413354233543335443354533546335473354833549335503355133552335533355433555335563355733558335593356033561335623356333564335653356633567335683356933570335713357233573335743357533576335773357833579335803358133582335833358433585335863358733588335893359033591335923359333594335953359633597335983359933600336013360233603336043360533606336073360833609336103361133612336133361433615336163361733618336193362033621336223362333624336253362633627336283362933630336313363233633336343363533636336373363833639336403364133642336433364433645336463364733648336493365033651336523365333654336553365633657336583365933660336613366233663336643366533666336673366833669336703367133672336733367433675336763367733678336793368033681336823368333684336853368633687336883368933690336913369233693336943369533696336973369833699337003370133702337033370433705337063370733708337093371033711337123371333714337153371633717337183371933720337213372233723337243372533726337273372833729337303373133732337333373433735337363373733738337393374033741337423374333744337453374633747337483374933750337513375233753337543375533756337573375833759337603376133762337633376433765337663376733768337693377033771337723377333774337753377633777337783377933780337813378233783337843378533786337873378833789337903379133792337933379433795337963379733798337993380033801338023380333804338053380633807338083380933810338113381233813338143381533816338173381833819338203382133822338233382433825338263382733828338293383033831338323383333834338353383633837338383383933840338413384233843338443384533846338473384833849338503385133852338533385433855338563385733858338593386033861338623386333864338653386633867338683386933870338713387233873338743387533876338773387833879338803388133882338833388433885338863388733888338893389033891338923389333894338953389633897338983389933900339013390233903339043390533906339073390833909339103391133912339133391433915339163391733918339193392033921339223392333924339253392633927339283392933930339313393233933339343393533936339373393833939339403394133942339433394433945339463394733948339493395033951339523395333954339553395633957339583395933960339613396233963339643396533966339673396833969339703397133972339733397433975339763397733978339793398033981339823398333984339853398633987339883398933990339913399233993339943399533996339973399833999340003400134002340033400434005340063400734008340093401034011340123401334014340153401634017340183401934020340213402234023340243402534026340273402834029340303403134032340333403434035340363403734038340393404034041340423404334044340453404634047340483404934050340513405234053340543405534056340573405834059340603406134062340633406434065340663406734068340693407034071340723407334074340753407634077340783407934080340813408234083340843408534086340873408834089340903409134092340933409434095340963409734098340993410034101341023410334104341053410634107341083410934110341113411234113341143411534116341173411834119341203412134122341233412434125341263412734128341293413034131341323413334134341353413634137341383413934140341413414234143341443414534146341473414834149341503415134152341533415434155341563415734158341593416034161341623416334164341653416634167341683416934170341713417234173341743417534176341773417834179341803418134182341833418434185341863418734188341893419034191341923419334194341953419634197341983419934200342013420234203342043420534206342073420834209342103421134212342133421434215342163421734218342193422034221342223422334224342253422634227342283422934230342313423234233342343423534236342373423834239342403424134242342433424434245342463424734248342493425034251342523425334254342553425634257342583425934260342613426234263342643426534266342673426834269342703427134272342733427434275342763427734278342793428034281342823428334284342853428634287342883428934290342913429234293342943429534296342973429834299343003430134302343033430434305343063430734308343093431034311343123431334314343153431634317343183431934320343213432234323343243432534326343273432834329343303433134332343333433434335343363433734338343393434034341343423434334344343453434634347343483434934350343513435234353343543435534356343573435834359343603436134362343633436434365343663436734368343693437034371343723437334374343753437634377343783437934380343813438234383343843438534386343873438834389343903439134392343933439434395343963439734398343993440034401344023440334404344053440634407344083440934410344113441234413344143441534416344173441834419344203442134422344233442434425344263442734428344293443034431344323443334434344353443634437344383443934440344413444234443344443444534446344473444834449344503445134452344533445434455344563445734458344593446034461344623446334464344653446634467344683446934470344713447234473344743447534476344773447834479344803448134482344833448434485344863448734488344893449034491344923449334494344953449634497344983449934500345013450234503345043450534506345073450834509345103451134512345133451434515345163451734518345193452034521345223452334524345253452634527345283452934530345313453234533345343453534536345373453834539345403454134542345433454434545345463454734548345493455034551345523455334554345553455634557345583455934560345613456234563345643456534566345673456834569345703457134572345733457434575345763457734578345793458034581345823458334584345853458634587345883458934590345913459234593345943459534596345973459834599346003460134602346033460434605346063460734608346093461034611346123461334614346153461634617346183461934620346213462234623346243462534626346273462834629346303463134632346333463434635346363463734638346393464034641346423464334644346453464634647346483464934650346513465234653346543465534656346573465834659346603466134662346633466434665346663466734668346693467034671346723467334674346753467634677346783467934680346813468234683346843468534686346873468834689346903469134692346933469434695346963469734698346993470034701347023470334704347053470634707347083470934710347113471234713347143471534716347173471834719347203472134722347233472434725347263472734728347293473034731347323473334734347353473634737347383473934740347413474234743347443474534746347473474834749347503475134752347533475434755347563475734758347593476034761347623476334764347653476634767347683476934770347713477234773347743477534776347773477834779347803478134782347833478434785347863478734788347893479034791347923479334794347953479634797347983479934800348013480234803348043480534806348073480834809348103481134812348133481434815348163481734818348193482034821348223482334824348253482634827348283482934830348313483234833348343483534836348373483834839348403484134842348433484434845348463484734848348493485034851348523485334854348553485634857348583485934860348613486234863348643486534866348673486834869348703487134872348733487434875348763487734878348793488034881348823488334884348853488634887348883488934890348913489234893348943489534896348973489834899349003490134902349033490434905349063490734908349093491034911349123491334914349153491634917349183491934920349213492234923349243492534926349273492834929349303493134932349333493434935349363493734938349393494034941349423494334944349453494634947349483494934950349513495234953349543495534956349573495834959349603496134962349633496434965349663496734968349693497034971349723497334974349753497634977349783497934980349813498234983349843498534986349873498834989349903499134992349933499434995349963499734998349993500035001350023500335004350053500635007350083500935010350113501235013350143501535016350173501835019350203502135022350233502435025350263502735028350293503035031350323503335034350353503635037350383503935040350413504235043350443504535046350473504835049350503505135052350533505435055350563505735058350593506035061350623506335064350653506635067350683506935070350713507235073350743507535076350773507835079350803508135082350833508435085350863508735088350893509035091350923509335094350953509635097350983509935100351013510235103351043510535106351073510835109351103511135112351133511435115351163511735118351193512035121351223512335124351253512635127351283512935130351313513235133351343513535136351373513835139351403514135142351433514435145351463514735148351493515035151351523515335154351553515635157351583515935160351613516235163351643516535166351673516835169351703517135172351733517435175351763517735178351793518035181351823518335184351853518635187351883518935190351913519235193351943519535196351973519835199352003520135202352033520435205352063520735208352093521035211352123521335214352153521635217352183521935220352213522235223352243522535226352273522835229352303523135232352333523435235352363523735238352393524035241352423524335244352453524635247352483524935250352513525235253352543525535256352573525835259352603526135262352633526435265352663526735268352693527035271352723527335274352753527635277352783527935280352813528235283352843528535286352873528835289352903529135292352933529435295352963529735298352993530035301353023530335304353053530635307353083530935310353113531235313353143531535316353173531835319353203532135322353233532435325353263532735328353293533035331353323533335334353353533635337353383533935340353413534235343353443534535346353473534835349353503535135352353533535435355353563535735358353593536035361353623536335364353653536635367353683536935370353713537235373353743537535376353773537835379353803538135382353833538435385353863538735388353893539035391353923539335394353953539635397353983539935400354013540235403354043540535406354073540835409354103541135412354133541435415354163541735418354193542035421354223542335424354253542635427354283542935430354313543235433354343543535436354373543835439354403544135442354433544435445354463544735448354493545035451354523545335454354553545635457354583545935460354613546235463354643546535466354673546835469354703547135472354733547435475354763547735478354793548035481354823548335484354853548635487354883548935490354913549235493354943549535496354973549835499355003550135502355033550435505355063550735508355093551035511355123551335514355153551635517355183551935520355213552235523355243552535526355273552835529355303553135532355333553435535355363553735538355393554035541355423554335544355453554635547355483554935550355513555235553355543555535556355573555835559355603556135562355633556435565355663556735568355693557035571355723557335574355753557635577355783557935580355813558235583355843558535586355873558835589355903559135592355933559435595355963559735598355993560035601356023560335604356053560635607356083560935610356113561235613356143561535616356173561835619356203562135622356233562435625356263562735628356293563035631356323563335634356353563635637356383563935640356413564235643356443564535646356473564835649356503565135652356533565435655356563565735658356593566035661356623566335664356653566635667356683566935670356713567235673356743567535676356773567835679356803568135682356833568435685356863568735688356893569035691356923569335694356953569635697356983569935700357013570235703357043570535706357073570835709357103571135712357133571435715357163571735718357193572035721357223572335724357253572635727357283572935730357313573235733357343573535736357373573835739357403574135742357433574435745357463574735748357493575035751357523575335754357553575635757357583575935760357613576235763357643576535766357673576835769357703577135772357733577435775357763577735778357793578035781357823578335784357853578635787357883578935790357913579235793357943579535796357973579835799358003580135802358033580435805358063580735808358093581035811358123581335814358153581635817358183581935820358213582235823358243582535826358273582835829358303583135832358333583435835358363583735838358393584035841358423584335844358453584635847358483584935850358513585235853358543585535856358573585835859358603586135862358633586435865358663586735868358693587035871358723587335874358753587635877358783587935880358813588235883358843588535886358873588835889358903589135892358933589435895358963589735898358993590035901359023590335904359053590635907359083590935910359113591235913359143591535916359173591835919359203592135922359233592435925359263592735928359293593035931359323593335934359353593635937359383593935940359413594235943359443594535946359473594835949359503595135952359533595435955359563595735958359593596035961359623596335964359653596635967359683596935970359713597235973359743597535976359773597835979359803598135982359833598435985359863598735988359893599035991359923599335994359953599635997359983599936000360013600236003360043600536006360073600836009360103601136012360133601436015360163601736018360193602036021360223602336024360253602636027360283602936030360313603236033360343603536036360373603836039360403604136042360433604436045360463604736048360493605036051360523605336054360553605636057360583605936060360613606236063360643606536066360673606836069360703607136072360733607436075360763607736078360793608036081360823608336084360853608636087360883608936090360913609236093360943609536096360973609836099361003610136102361033610436105361063610736108361093611036111361123611336114361153611636117361183611936120361213612236123361243612536126361273612836129361303613136132361333613436135361363613736138361393614036141361423614336144361453614636147361483614936150361513615236153361543615536156361573615836159361603616136162361633616436165361663616736168361693617036171361723617336174361753617636177361783617936180361813618236183361843618536186361873618836189361903619136192361933619436195361963619736198361993620036201362023620336204362053620636207362083620936210362113621236213362143621536216362173621836219362203622136222362233622436225362263622736228362293623036231362323623336234362353623636237362383623936240362413624236243362443624536246362473624836249362503625136252362533625436255362563625736258362593626036261362623626336264362653626636267362683626936270362713627236273362743627536276362773627836279362803628136282362833628436285362863628736288362893629036291362923629336294362953629636297362983629936300363013630236303363043630536306363073630836309363103631136312363133631436315363163631736318363193632036321363223632336324363253632636327363283632936330363313633236333363343633536336363373633836339363403634136342363433634436345363463634736348363493635036351363523635336354363553635636357363583635936360363613636236363363643636536366363673636836369363703637136372363733637436375363763637736378363793638036381363823638336384363853638636387363883638936390363913639236393363943639536396363973639836399364003640136402364033640436405364063640736408364093641036411364123641336414364153641636417364183641936420364213642236423364243642536426364273642836429364303643136432364333643436435364363643736438364393644036441364423644336444364453644636447364483644936450364513645236453364543645536456364573645836459364603646136462364633646436465364663646736468364693647036471364723647336474364753647636477364783647936480364813648236483364843648536486364873648836489364903649136492364933649436495364963649736498364993650036501365023650336504365053650636507365083650936510365113651236513365143651536516365173651836519365203652136522365233652436525365263652736528365293653036531365323653336534365353653636537365383653936540365413654236543365443654536546365473654836549365503655136552365533655436555365563655736558365593656036561365623656336564365653656636567365683656936570365713657236573365743657536576365773657836579365803658136582365833658436585365863658736588365893659036591365923659336594365953659636597365983659936600366013660236603366043660536606366073660836609366103661136612366133661436615366163661736618366193662036621366223662336624366253662636627366283662936630366313663236633366343663536636366373663836639366403664136642366433664436645366463664736648366493665036651366523665336654366553665636657366583665936660366613666236663366643666536666366673666836669366703667136672366733667436675366763667736678366793668036681366823668336684366853668636687366883668936690366913669236693366943669536696366973669836699367003670136702367033670436705367063670736708367093671036711367123671336714367153671636717367183671936720367213672236723367243672536726367273672836729367303673136732367333673436735367363673736738367393674036741367423674336744367453674636747367483674936750367513675236753367543675536756367573675836759367603676136762367633676436765367663676736768367693677036771367723677336774367753677636777367783677936780367813678236783367843678536786367873678836789367903679136792367933679436795367963679736798367993680036801368023680336804368053680636807368083680936810368113681236813368143681536816368173681836819368203682136822368233682436825368263682736828368293683036831368323683336834368353683636837368383683936840368413684236843368443684536846368473684836849368503685136852368533685436855368563685736858368593686036861368623686336864368653686636867368683686936870368713687236873368743687536876368773687836879368803688136882368833688436885368863688736888368893689036891368923689336894368953689636897368983689936900369013690236903369043690536906369073690836909369103691136912369133691436915369163691736918369193692036921369223692336924369253692636927369283692936930369313693236933369343693536936369373693836939369403694136942369433694436945369463694736948369493695036951369523695336954369553695636957369583695936960369613696236963369643696536966369673696836969369703697136972369733697436975369763697736978369793698036981369823698336984369853698636987369883698936990369913699236993369943699536996369973699836999370003700137002370033700437005370063700737008370093701037011370123701337014370153701637017370183701937020370213702237023370243702537026370273702837029370303703137032370333703437035370363703737038370393704037041370423704337044370453704637047370483704937050370513705237053370543705537056370573705837059370603706137062370633706437065370663706737068370693707037071370723707337074370753707637077370783707937080370813708237083370843708537086370873708837089370903709137092370933709437095370963709737098370993710037101371023710337104371053710637107371083710937110371113711237113371143711537116371173711837119371203712137122371233712437125371263712737128371293713037131371323713337134371353713637137371383713937140371413714237143371443714537146371473714837149371503715137152371533715437155371563715737158371593716037161371623716337164371653716637167371683716937170371713717237173371743717537176371773717837179371803718137182371833718437185371863718737188371893719037191371923719337194371953719637197371983719937200372013720237203372043720537206372073720837209372103721137212372133721437215372163721737218372193722037221372223722337224372253722637227372283722937230372313723237233372343723537236372373723837239372403724137242372433724437245372463724737248372493725037251372523725337254372553725637257372583725937260372613726237263372643726537266372673726837269372703727137272372733727437275372763727737278372793728037281372823728337284372853728637287372883728937290372913729237293372943729537296372973729837299373003730137302373033730437305373063730737308373093731037311373123731337314373153731637317373183731937320373213732237323373243732537326373273732837329373303733137332373333733437335373363733737338373393734037341373423734337344373453734637347373483734937350373513735237353373543735537356373573735837359373603736137362373633736437365373663736737368373693737037371373723737337374373753737637377373783737937380373813738237383373843738537386373873738837389373903739137392373933739437395373963739737398373993740037401374023740337404374053740637407374083740937410374113741237413374143741537416374173741837419374203742137422374233742437425374263742737428374293743037431374323743337434374353743637437374383743937440374413744237443374443744537446374473744837449374503745137452374533745437455374563745737458374593746037461374623746337464374653746637467374683746937470374713747237473374743747537476374773747837479374803748137482374833748437485374863748737488374893749037491374923749337494374953749637497374983749937500375013750237503375043750537506375073750837509375103751137512375133751437515375163751737518375193752037521375223752337524375253752637527375283752937530375313753237533375343753537536375373753837539375403754137542375433754437545375463754737548375493755037551375523755337554375553755637557375583755937560375613756237563375643756537566375673756837569375703757137572375733757437575375763757737578375793758037581375823758337584375853758637587375883758937590375913759237593375943759537596375973759837599376003760137602376033760437605376063760737608376093761037611376123761337614376153761637617376183761937620376213762237623376243762537626376273762837629376303763137632376333763437635376363763737638376393764037641376423764337644376453764637647376483764937650376513765237653376543765537656376573765837659376603766137662376633766437665376663766737668376693767037671376723767337674376753767637677376783767937680376813768237683376843768537686376873768837689376903769137692376933769437695376963769737698376993770037701377023770337704377053770637707377083770937710377113771237713377143771537716377173771837719377203772137722377233772437725377263772737728377293773037731377323773337734377353773637737377383773937740377413774237743377443774537746377473774837749377503775137752377533775437755377563775737758377593776037761377623776337764377653776637767377683776937770377713777237773377743777537776377773777837779377803778137782377833778437785377863778737788377893779037791377923779337794377953779637797377983779937800378013780237803378043780537806378073780837809378103781137812378133781437815378163781737818378193782037821378223782337824378253782637827378283782937830378313783237833378343783537836378373783837839378403784137842378433784437845378463784737848378493785037851378523785337854378553785637857378583785937860378613786237863378643786537866378673786837869378703787137872378733787437875378763787737878378793788037881378823788337884378853788637887378883788937890378913789237893378943789537896378973789837899379003790137902379033790437905379063790737908379093791037911379123791337914379153791637917379183791937920379213792237923379243792537926379273792837929379303793137932379333793437935379363793737938379393794037941379423794337944379453794637947379483794937950379513795237953379543795537956379573795837959379603796137962379633796437965379663796737968379693797037971379723797337974379753797637977379783797937980379813798237983379843798537986379873798837989379903799137992379933799437995379963799737998379993800038001380023800338004380053800638007380083800938010380113801238013380143801538016380173801838019380203802138022380233802438025380263802738028380293803038031380323803338034380353803638037380383803938040380413804238043380443804538046380473804838049380503805138052380533805438055380563805738058380593806038061380623806338064380653806638067380683806938070380713807238073380743807538076380773807838079380803808138082380833808438085380863808738088380893809038091380923809338094380953809638097380983809938100381013810238103381043810538106381073810838109381103811138112381133811438115381163811738118381193812038121381223812338124381253812638127381283812938130381313813238133381343813538136381373813838139381403814138142381433814438145381463814738148381493815038151381523815338154381553815638157381583815938160381613816238163381643816538166381673816838169381703817138172381733817438175381763817738178381793818038181381823818338184381853818638187381883818938190381913819238193381943819538196381973819838199382003820138202382033820438205382063820738208382093821038211382123821338214382153821638217382183821938220382213822238223382243822538226382273822838229382303823138232382333823438235382363823738238382393824038241382423824338244382453824638247382483824938250382513825238253382543825538256382573825838259382603826138262382633826438265382663826738268382693827038271382723827338274382753827638277382783827938280382813828238283382843828538286382873828838289382903829138292382933829438295382963829738298382993830038301383023830338304383053830638307383083830938310383113831238313383143831538316383173831838319383203832138322383233832438325383263832738328383293833038331383323833338334383353833638337383383833938340383413834238343383443834538346383473834838349383503835138352383533835438355383563835738358383593836038361383623836338364383653836638367383683836938370383713837238373383743837538376383773837838379383803838138382383833838438385383863838738388383893839038391383923839338394383953839638397383983839938400384013840238403384043840538406384073840838409384103841138412384133841438415384163841738418384193842038421384223842338424384253842638427384283842938430384313843238433384343843538436384373843838439384403844138442384433844438445384463844738448384493845038451384523845338454384553845638457384583845938460384613846238463384643846538466384673846838469384703847138472384733847438475384763847738478384793848038481384823848338484384853848638487384883848938490384913849238493384943849538496384973849838499385003850138502385033850438505385063850738508385093851038511385123851338514385153851638517385183851938520385213852238523385243852538526385273852838529385303853138532385333853438535385363853738538385393854038541385423854338544385453854638547385483854938550385513855238553385543855538556385573855838559385603856138562385633856438565385663856738568385693857038571385723857338574385753857638577385783857938580385813858238583385843858538586385873858838589385903859138592385933859438595385963859738598385993860038601386023860338604386053860638607386083860938610386113861238613386143861538616386173861838619386203862138622386233862438625386263862738628386293863038631386323863338634386353863638637386383863938640386413864238643386443864538646386473864838649386503865138652386533865438655386563865738658386593866038661386623866338664386653866638667386683866938670386713867238673386743867538676386773867838679386803868138682386833868438685386863868738688386893869038691386923869338694386953869638697386983869938700387013870238703387043870538706387073870838709387103871138712387133871438715387163871738718387193872038721387223872338724387253872638727387283872938730387313873238733387343873538736387373873838739387403874138742387433874438745387463874738748387493875038751387523875338754387553875638757387583875938760387613876238763387643876538766387673876838769387703877138772387733877438775387763877738778387793878038781387823878338784387853878638787387883878938790387913879238793387943879538796387973879838799388003880138802388033880438805388063880738808388093881038811388123881338814388153881638817388183881938820388213882238823388243882538826388273882838829388303883138832388333883438835388363883738838388393884038841388423884338844388453884638847388483884938850388513885238853388543885538856388573885838859388603886138862388633886438865388663886738868388693887038871388723887338874388753887638877388783887938880388813888238883388843888538886388873888838889388903889138892388933889438895388963889738898388993890038901389023890338904389053890638907389083890938910389113891238913389143891538916389173891838919389203892138922389233892438925389263892738928389293893038931389323893338934389353893638937389383893938940389413894238943389443894538946389473894838949389503895138952389533895438955389563895738958389593896038961389623896338964389653896638967389683896938970389713897238973389743897538976389773897838979389803898138982389833898438985389863898738988389893899038991389923899338994389953899638997389983899939000390013900239003390043900539006390073900839009390103901139012390133901439015390163901739018390193902039021390223902339024390253902639027390283902939030390313903239033390343903539036390373903839039390403904139042390433904439045390463904739048390493905039051390523905339054390553905639057390583905939060390613906239063390643906539066390673906839069390703907139072390733907439075390763907739078390793908039081390823908339084390853908639087390883908939090390913909239093390943909539096390973909839099391003910139102391033910439105391063910739108391093911039111391123911339114391153911639117391183911939120391213912239123391243912539126391273912839129391303913139132391333913439135391363913739138391393914039141391423914339144391453914639147391483914939150391513915239153391543915539156391573915839159391603916139162391633916439165391663916739168391693917039171391723917339174391753917639177391783917939180391813918239183391843918539186391873918839189391903919139192391933919439195391963919739198391993920039201392023920339204392053920639207392083920939210392113921239213392143921539216392173921839219392203922139222392233922439225392263922739228392293923039231392323923339234392353923639237392383923939240392413924239243392443924539246392473924839249392503925139252392533925439255392563925739258392593926039261392623926339264392653926639267392683926939270392713927239273392743927539276392773927839279392803928139282392833928439285392863928739288392893929039291392923929339294392953929639297392983929939300393013930239303393043930539306393073930839309393103931139312393133931439315393163931739318393193932039321393223932339324393253932639327393283932939330393313933239333393343933539336393373933839339393403934139342393433934439345393463934739348393493935039351393523935339354393553935639357393583935939360393613936239363393643936539366393673936839369393703937139372393733937439375393763937739378393793938039381393823938339384393853938639387393883938939390393913939239393393943939539396393973939839399394003940139402394033940439405394063940739408394093941039411394123941339414394153941639417394183941939420394213942239423394243942539426394273942839429394303943139432394333943439435394363943739438394393944039441394423944339444394453944639447394483944939450394513945239453394543945539456394573945839459394603946139462394633946439465394663946739468394693947039471394723947339474394753947639477394783947939480394813948239483394843948539486394873948839489394903949139492394933949439495394963949739498394993950039501395023950339504395053950639507395083950939510395113951239513395143951539516395173951839519395203952139522395233952439525395263952739528395293953039531395323953339534395353953639537395383953939540395413954239543395443954539546395473954839549395503955139552395533955439555395563955739558395593956039561395623956339564395653956639567395683956939570395713957239573395743957539576395773957839579395803958139582395833958439585395863958739588395893959039591395923959339594395953959639597395983959939600396013960239603396043960539606396073960839609396103961139612396133961439615396163961739618396193962039621396223962339624396253962639627396283962939630396313963239633396343963539636396373963839639396403964139642396433964439645396463964739648396493965039651396523965339654396553965639657396583965939660396613966239663396643966539666396673966839669396703967139672396733967439675396763967739678396793968039681396823968339684396853968639687396883968939690396913969239693396943969539696396973969839699397003970139702397033970439705397063970739708397093971039711397123971339714397153971639717397183971939720397213972239723397243972539726397273972839729397303973139732397333973439735397363973739738397393974039741397423974339744397453974639747397483974939750397513975239753397543975539756397573975839759397603976139762397633976439765397663976739768397693977039771397723977339774397753977639777397783977939780397813978239783397843978539786397873978839789397903979139792397933979439795397963979739798397993980039801398023980339804398053980639807398083980939810398113981239813398143981539816398173981839819398203982139822398233982439825398263982739828398293983039831398323983339834398353983639837398383983939840398413984239843398443984539846398473984839849398503985139852398533985439855398563985739858398593986039861398623986339864398653986639867398683986939870398713987239873398743987539876398773987839879398803988139882398833988439885398863988739888398893989039891398923989339894398953989639897398983989939900399013990239903399043990539906399073990839909399103991139912399133991439915399163991739918399193992039921399223992339924399253992639927399283992939930399313993239933399343993539936399373993839939399403994139942399433994439945399463994739948399493995039951399523995339954399553995639957399583995939960399613996239963399643996539966399673996839969399703997139972399733997439975399763997739978399793998039981399823998339984399853998639987399883998939990399913999239993399943999539996399973999839999400004000140002400034000440005400064000740008400094001040011400124001340014400154001640017400184001940020400214002240023400244002540026400274002840029400304003140032400334003440035400364003740038400394004040041400424004340044400454004640047400484004940050400514005240053400544005540056400574005840059400604006140062400634006440065400664006740068400694007040071400724007340074400754007640077400784007940080400814008240083400844008540086400874008840089400904009140092400934009440095400964009740098400994010040101401024010340104401054010640107401084010940110401114011240113401144011540116401174011840119401204012140122401234012440125401264012740128401294013040131401324013340134401354013640137401384013940140401414014240143401444014540146401474014840149401504015140152401534015440155401564015740158401594016040161401624016340164401654016640167401684016940170401714017240173401744017540176401774017840179401804018140182401834018440185401864018740188401894019040191401924019340194401954019640197401984019940200402014020240203402044020540206402074020840209402104021140212402134021440215402164021740218402194022040221402224022340224402254022640227402284022940230402314023240233402344023540236402374023840239402404024140242402434024440245402464024740248402494025040251402524025340254402554025640257402584025940260402614026240263402644026540266402674026840269402704027140272402734027440275402764027740278402794028040281402824028340284402854028640287402884028940290402914029240293402944029540296402974029840299403004030140302403034030440305403064030740308403094031040311403124031340314403154031640317403184031940320403214032240323403244032540326403274032840329403304033140332403334033440335403364033740338403394034040341403424034340344403454034640347403484034940350403514035240353403544035540356403574035840359403604036140362403634036440365403664036740368403694037040371403724037340374403754037640377403784037940380403814038240383403844038540386403874038840389403904039140392403934039440395403964039740398403994040040401404024040340404404054040640407404084040940410404114041240413404144041540416404174041840419404204042140422404234042440425404264042740428404294043040431404324043340434404354043640437404384043940440404414044240443404444044540446404474044840449404504045140452404534045440455404564045740458404594046040461404624046340464404654046640467404684046940470404714047240473404744047540476404774047840479404804048140482404834048440485404864048740488404894049040491404924049340494404954049640497404984049940500405014050240503405044050540506405074050840509405104051140512405134051440515405164051740518405194052040521405224052340524405254052640527405284052940530405314053240533405344053540536405374053840539405404054140542405434054440545405464054740548405494055040551405524055340554405554055640557405584055940560405614056240563405644056540566405674056840569405704057140572405734057440575405764057740578405794058040581405824058340584405854058640587405884058940590405914059240593405944059540596405974059840599406004060140602406034060440605406064060740608406094061040611406124061340614406154061640617406184061940620406214062240623406244062540626406274062840629406304063140632406334063440635406364063740638406394064040641406424064340644406454064640647406484064940650406514065240653406544065540656406574065840659406604066140662406634066440665406664066740668406694067040671406724067340674406754067640677406784067940680406814068240683406844068540686406874068840689406904069140692406934069440695406964069740698406994070040701407024070340704407054070640707407084070940710407114071240713407144071540716407174071840719407204072140722407234072440725407264072740728407294073040731407324073340734407354073640737407384073940740407414074240743407444074540746407474074840749407504075140752407534075440755407564075740758407594076040761407624076340764407654076640767407684076940770407714077240773407744077540776407774077840779407804078140782407834078440785407864078740788407894079040791407924079340794407954079640797407984079940800408014080240803408044080540806408074080840809408104081140812408134081440815408164081740818408194082040821408224082340824408254082640827408284082940830408314083240833408344083540836408374083840839408404084140842408434084440845408464084740848408494085040851408524085340854408554085640857408584085940860408614086240863408644086540866408674086840869408704087140872408734087440875408764087740878408794088040881408824088340884408854088640887408884088940890408914089240893408944089540896408974089840899409004090140902409034090440905409064090740908409094091040911409124091340914409154091640917409184091940920409214092240923409244092540926409274092840929409304093140932409334093440935409364093740938409394094040941409424094340944409454094640947409484094940950409514095240953409544095540956409574095840959409604096140962409634096440965409664096740968409694097040971409724097340974409754097640977409784097940980409814098240983409844098540986409874098840989409904099140992409934099440995409964099740998409994100041001410024100341004410054100641007410084100941010410114101241013410144101541016410174101841019410204102141022410234102441025410264102741028410294103041031410324103341034410354103641037410384103941040410414104241043410444104541046410474104841049410504105141052410534105441055410564105741058410594106041061410624106341064410654106641067410684106941070410714107241073410744107541076410774107841079410804108141082410834108441085410864108741088410894109041091410924109341094410954109641097410984109941100411014110241103411044110541106411074110841109411104111141112411134111441115411164111741118411194112041121411224112341124411254112641127411284112941130411314113241133411344113541136411374113841139411404114141142411434114441145411464114741148411494115041151411524115341154411554115641157411584115941160411614116241163411644116541166411674116841169411704117141172411734117441175411764117741178411794118041181411824118341184411854118641187411884118941190411914119241193411944119541196411974119841199412004120141202412034120441205412064120741208412094121041211412124121341214412154121641217412184121941220412214122241223412244122541226412274122841229412304123141232412334123441235412364123741238412394124041241412424124341244412454124641247412484124941250412514125241253412544125541256412574125841259412604126141262412634126441265412664126741268412694127041271412724127341274412754127641277412784127941280412814128241283412844128541286412874128841289412904129141292412934129441295412964129741298412994130041301413024130341304413054130641307413084130941310413114131241313413144131541316413174131841319413204132141322413234132441325413264132741328413294133041331413324133341334413354133641337413384133941340413414134241343413444134541346413474134841349413504135141352413534135441355413564135741358413594136041361413624136341364413654136641367413684136941370413714137241373413744137541376413774137841379413804138141382413834138441385413864138741388413894139041391413924139341394413954139641397413984139941400414014140241403414044140541406414074140841409414104141141412414134141441415414164141741418414194142041421414224142341424414254142641427414284142941430414314143241433414344143541436414374143841439414404144141442414434144441445414464144741448414494145041451414524145341454414554145641457414584145941460414614146241463414644146541466414674146841469414704147141472414734147441475414764147741478414794148041481414824148341484414854148641487414884148941490414914149241493414944149541496414974149841499415004150141502415034150441505415064150741508415094151041511415124151341514415154151641517415184151941520415214152241523415244152541526415274152841529415304153141532415334153441535415364153741538415394154041541415424154341544415454154641547415484154941550415514155241553415544155541556415574155841559415604156141562415634156441565415664156741568415694157041571415724157341574415754157641577415784157941580415814158241583415844158541586415874158841589415904159141592415934159441595415964159741598415994160041601416024160341604416054160641607416084160941610416114161241613416144161541616416174161841619416204162141622416234162441625416264162741628416294163041631416324163341634416354163641637416384163941640416414164241643416444164541646416474164841649416504165141652416534165441655416564165741658416594166041661416624166341664416654166641667416684166941670416714167241673416744167541676416774167841679416804168141682416834168441685416864168741688416894169041691416924169341694416954169641697416984169941700417014170241703417044170541706417074170841709417104171141712417134171441715417164171741718417194172041721417224172341724417254172641727417284172941730417314173241733417344173541736417374173841739417404174141742417434174441745417464174741748417494175041751417524175341754417554175641757417584175941760417614176241763417644176541766417674176841769417704177141772417734177441775417764177741778417794178041781417824178341784417854178641787417884178941790417914179241793417944179541796417974179841799418004180141802418034180441805418064180741808418094181041811418124181341814418154181641817418184181941820418214182241823418244182541826418274182841829418304183141832418334183441835418364183741838418394184041841418424184341844418454184641847418484184941850418514185241853418544185541856418574185841859418604186141862418634186441865418664186741868418694187041871418724187341874418754187641877418784187941880418814188241883418844188541886418874188841889418904189141892418934189441895418964189741898418994190041901419024190341904419054190641907419084190941910419114191241913419144191541916419174191841919419204192141922419234192441925419264192741928419294193041931419324193341934419354193641937419384193941940419414194241943419444194541946419474194841949419504195141952419534195441955419564195741958419594196041961419624196341964419654196641967419684196941970419714197241973419744197541976419774197841979419804198141982419834198441985419864198741988419894199041991419924199341994419954199641997419984199942000420014200242003420044200542006420074200842009420104201142012420134201442015420164201742018420194202042021420224202342024420254202642027420284202942030420314203242033420344203542036420374203842039420404204142042420434204442045420464204742048420494205042051420524205342054420554205642057420584205942060420614206242063420644206542066420674206842069420704207142072420734207442075420764207742078420794208042081420824208342084420854208642087420884208942090420914209242093420944209542096420974209842099421004210142102421034210442105421064210742108421094211042111421124211342114421154211642117421184211942120421214212242123421244212542126421274212842129421304213142132421334213442135421364213742138421394214042141421424214342144421454214642147421484214942150421514215242153421544215542156421574215842159421604216142162421634216442165421664216742168421694217042171421724217342174421754217642177421784217942180421814218242183421844218542186421874218842189421904219142192421934219442195421964219742198421994220042201422024220342204422054220642207422084220942210422114221242213422144221542216422174221842219422204222142222422234222442225422264222742228422294223042231422324223342234422354223642237422384223942240422414224242243422444224542246422474224842249422504225142252422534225442255422564225742258422594226042261422624226342264422654226642267422684226942270422714227242273422744227542276422774227842279422804228142282422834228442285422864228742288422894229042291422924229342294422954229642297422984229942300423014230242303423044230542306423074230842309423104231142312423134231442315423164231742318423194232042321423224232342324423254232642327423284232942330423314233242333423344233542336423374233842339423404234142342423434234442345423464234742348423494235042351423524235342354423554235642357423584235942360423614236242363423644236542366423674236842369423704237142372423734237442375423764237742378423794238042381423824238342384423854238642387423884238942390423914239242393423944239542396423974239842399424004240142402424034240442405424064240742408424094241042411424124241342414424154241642417424184241942420424214242242423424244242542426424274242842429424304243142432424334243442435424364243742438424394244042441424424244342444424454244642447424484244942450424514245242453424544245542456424574245842459424604246142462424634246442465424664246742468424694247042471424724247342474424754247642477424784247942480424814248242483424844248542486424874248842489424904249142492424934249442495424964249742498424994250042501425024250342504425054250642507425084250942510425114251242513425144251542516425174251842519425204252142522425234252442525425264252742528425294253042531425324253342534425354253642537425384253942540425414254242543425444254542546425474254842549425504255142552425534255442555425564255742558425594256042561425624256342564425654256642567425684256942570425714257242573425744257542576425774257842579425804258142582425834258442585425864258742588425894259042591425924259342594425954259642597425984259942600426014260242603426044260542606426074260842609426104261142612426134261442615426164261742618426194262042621426224262342624426254262642627426284262942630426314263242633426344263542636426374263842639426404264142642426434264442645426464264742648426494265042651426524265342654426554265642657426584265942660426614266242663426644266542666426674266842669426704267142672426734267442675426764267742678426794268042681426824268342684426854268642687426884268942690426914269242693426944269542696426974269842699427004270142702427034270442705427064270742708427094271042711427124271342714427154271642717427184271942720427214272242723427244272542726427274272842729427304273142732427334273442735427364273742738427394274042741427424274342744427454274642747427484274942750427514275242753427544275542756427574275842759427604276142762427634276442765427664276742768427694277042771427724277342774427754277642777427784277942780427814278242783427844278542786427874278842789427904279142792427934279442795427964279742798427994280042801428024280342804428054280642807428084280942810428114281242813428144281542816428174281842819428204282142822428234282442825428264282742828428294283042831428324283342834428354283642837428384283942840428414284242843428444284542846428474284842849428504285142852428534285442855428564285742858428594286042861428624286342864428654286642867428684286942870428714287242873428744287542876428774287842879428804288142882428834288442885428864288742888428894289042891428924289342894428954289642897428984289942900429014290242903429044290542906429074290842909429104291142912429134291442915429164291742918429194292042921429224292342924429254292642927429284292942930429314293242933429344293542936429374293842939429404294142942429434294442945429464294742948429494295042951429524295342954429554295642957429584295942960429614296242963429644296542966429674296842969429704297142972429734297442975429764297742978429794298042981429824298342984429854298642987429884298942990429914299242993429944299542996429974299842999430004300143002430034300443005430064300743008430094301043011430124301343014430154301643017430184301943020430214302243023430244302543026430274302843029430304303143032430334303443035430364303743038430394304043041430424304343044430454304643047430484304943050430514305243053430544305543056430574305843059430604306143062430634306443065430664306743068430694307043071430724307343074430754307643077430784307943080430814308243083430844308543086430874308843089430904309143092430934309443095430964309743098430994310043101431024310343104431054310643107431084310943110431114311243113431144311543116431174311843119431204312143122431234312443125431264312743128431294313043131431324313343134431354313643137431384313943140431414314243143431444314543146431474314843149431504315143152431534315443155431564315743158431594316043161431624316343164431654316643167431684316943170431714317243173431744317543176431774317843179431804318143182431834318443185431864318743188431894319043191431924319343194431954319643197431984319943200432014320243203432044320543206432074320843209432104321143212432134321443215432164321743218432194322043221432224322343224432254322643227432284322943230432314323243233432344323543236432374323843239432404324143242432434324443245432464324743248432494325043251432524325343254432554325643257432584325943260432614326243263432644326543266432674326843269432704327143272432734327443275432764327743278432794328043281432824328343284432854328643287432884328943290432914329243293432944329543296432974329843299433004330143302433034330443305433064330743308433094331043311433124331343314433154331643317433184331943320433214332243323433244332543326433274332843329433304333143332433334333443335433364333743338433394334043341433424334343344433454334643347433484334943350433514335243353433544335543356433574335843359433604336143362433634336443365433664336743368433694337043371433724337343374433754337643377433784337943380433814338243383433844338543386433874338843389433904339143392433934339443395433964339743398433994340043401434024340343404434054340643407434084340943410434114341243413434144341543416434174341843419434204342143422434234342443425434264342743428434294343043431434324343343434434354343643437434384343943440434414344243443434444344543446434474344843449434504345143452434534345443455434564345743458434594346043461434624346343464434654346643467434684346943470434714347243473434744347543476434774347843479434804348143482434834348443485434864348743488434894349043491434924349343494434954349643497434984349943500435014350243503435044350543506435074350843509435104351143512435134351443515435164351743518435194352043521435224352343524435254352643527435284352943530435314353243533435344353543536435374353843539435404354143542435434354443545435464354743548435494355043551435524355343554435554355643557435584355943560435614356243563435644356543566435674356843569435704357143572435734357443575435764357743578435794358043581435824358343584435854358643587435884358943590435914359243593435944359543596435974359843599436004360143602436034360443605436064360743608436094361043611436124361343614436154361643617436184361943620436214362243623436244362543626436274362843629436304363143632436334363443635436364363743638436394364043641436424364343644436454364643647436484364943650436514365243653436544365543656436574365843659436604366143662436634366443665436664366743668436694367043671436724367343674436754367643677436784367943680436814368243683436844368543686436874368843689436904369143692436934369443695436964369743698436994370043701437024370343704437054370643707437084370943710437114371243713437144371543716437174371843719437204372143722437234372443725437264372743728437294373043731437324373343734437354373643737437384373943740437414374243743437444374543746437474374843749437504375143752437534375443755437564375743758437594376043761437624376343764437654376643767437684376943770437714377243773437744377543776437774377843779437804378143782437834378443785437864378743788437894379043791437924379343794437954379643797437984379943800438014380243803438044380543806438074380843809438104381143812438134381443815438164381743818438194382043821438224382343824438254382643827438284382943830438314383243833438344383543836438374383843839438404384143842438434384443845438464384743848438494385043851438524385343854438554385643857438584385943860438614386243863438644386543866438674386843869438704387143872438734387443875438764387743878438794388043881438824388343884438854388643887438884388943890438914389243893438944389543896438974389843899439004390143902439034390443905439064390743908439094391043911439124391343914439154391643917439184391943920439214392243923439244392543926439274392843929439304393143932439334393443935439364393743938439394394043941439424394343944439454394643947439484394943950439514395243953439544395543956439574395843959439604396143962439634396443965439664396743968439694397043971439724397343974439754397643977439784397943980439814398243983439844398543986439874398843989439904399143992439934399443995439964399743998439994400044001440024400344004440054400644007440084400944010440114401244013440144401544016440174401844019440204402144022440234402444025440264402744028440294403044031440324403344034440354403644037440384403944040440414404244043440444404544046440474404844049440504405144052440534405444055440564405744058440594406044061440624406344064440654406644067440684406944070440714407244073440744407544076440774407844079440804408144082440834408444085440864408744088440894409044091440924409344094440954409644097440984409944100441014410244103441044410544106441074410844109441104411144112441134411444115441164411744118441194412044121441224412344124441254412644127441284412944130441314413244133441344413544136441374413844139441404414144142441434414444145441464414744148441494415044151441524415344154441554415644157441584415944160441614416244163441644416544166441674416844169441704417144172441734417444175441764417744178441794418044181441824418344184441854418644187441884418944190441914419244193441944419544196441974419844199442004420144202442034420444205442064420744208442094421044211442124421344214442154421644217442184421944220442214422244223442244422544226442274422844229442304423144232442334423444235442364423744238442394424044241442424424344244442454424644247442484424944250442514425244253442544425544256442574425844259442604426144262442634426444265442664426744268442694427044271442724427344274442754427644277442784427944280442814428244283442844428544286442874428844289442904429144292442934429444295442964429744298442994430044301443024430344304443054430644307443084430944310443114431244313443144431544316443174431844319443204432144322443234432444325443264432744328443294433044331443324433344334443354433644337443384433944340443414434244343443444434544346443474434844349443504435144352443534435444355443564435744358443594436044361443624436344364443654436644367443684436944370443714437244373443744437544376443774437844379443804438144382443834438444385443864438744388443894439044391443924439344394443954439644397443984439944400444014440244403444044440544406444074440844409444104441144412444134441444415444164441744418444194442044421444224442344424444254442644427444284442944430444314443244433444344443544436444374443844439444404444144442444434444444445444464444744448444494445044451444524445344454444554445644457444584445944460444614446244463444644446544466444674446844469444704447144472444734447444475444764447744478444794448044481444824448344484444854448644487444884448944490444914449244493444944449544496444974449844499445004450144502445034450444505445064450744508445094451044511445124451344514445154451644517445184451944520445214452244523445244452544526445274452844529445304453144532445334453444535445364453744538445394454044541445424454344544445454454644547445484454944550445514455244553445544455544556445574455844559445604456144562445634456444565445664456744568445694457044571445724457344574445754457644577445784457944580445814458244583445844458544586445874458844589445904459144592445934459444595445964459744598445994460044601446024460344604446054460644607446084460944610446114461244613446144461544616446174461844619446204462144622446234462444625446264462744628446294463044631446324463344634446354463644637446384463944640446414464244643446444464544646446474464844649446504465144652446534465444655446564465744658446594466044661446624466344664446654466644667446684466944670446714467244673446744467544676446774467844679446804468144682446834468444685446864468744688446894469044691446924469344694446954469644697446984469944700447014470244703447044470544706447074470844709447104471144712447134471444715447164471744718447194472044721447224472344724447254472644727447284472944730447314473244733447344473544736447374473844739447404474144742447434474444745447464474744748447494475044751447524475344754447554475644757447584475944760447614476244763447644476544766447674476844769447704477144772447734477444775447764477744778447794478044781447824478344784447854478644787447884478944790447914479244793447944479544796447974479844799448004480144802448034480444805448064480744808448094481044811448124481344814448154481644817448184481944820448214482244823448244482544826448274482844829448304483144832448334483444835448364483744838448394484044841448424484344844448454484644847448484484944850448514485244853448544485544856448574485844859448604486144862448634486444865448664486744868448694487044871448724487344874448754487644877448784487944880448814488244883448844488544886448874488844889448904489144892448934489444895448964489744898448994490044901449024490344904449054490644907449084490944910449114491244913449144491544916449174491844919449204492144922449234492444925449264492744928449294493044931449324493344934449354493644937449384493944940449414494244943449444494544946449474494844949449504495144952449534495444955449564495744958449594496044961449624496344964449654496644967449684496944970449714497244973449744497544976449774497844979449804498144982449834498444985449864498744988449894499044991449924499344994449954499644997449984499945000450014500245003450044500545006450074500845009450104501145012450134501445015450164501745018450194502045021450224502345024450254502645027450284502945030450314503245033450344503545036450374503845039450404504145042450434504445045450464504745048450494505045051450524505345054450554505645057450584505945060450614506245063450644506545066450674506845069450704507145072450734507445075450764507745078450794508045081450824508345084450854508645087450884508945090450914509245093450944509545096450974509845099451004510145102451034510445105451064510745108451094511045111451124511345114451154511645117451184511945120451214512245123451244512545126451274512845129451304513145132451334513445135451364513745138451394514045141451424514345144451454514645147451484514945150451514515245153451544515545156451574515845159451604516145162451634516445165451664516745168451694517045171451724517345174451754517645177451784517945180451814518245183451844518545186451874518845189451904519145192451934519445195451964519745198451994520045201452024520345204452054520645207452084520945210452114521245213452144521545216452174521845219452204522145222452234522445225452264522745228452294523045231452324523345234452354523645237452384523945240452414524245243452444524545246452474524845249452504525145252452534525445255452564525745258452594526045261452624526345264452654526645267452684526945270452714527245273452744527545276452774527845279452804528145282452834528445285452864528745288452894529045291452924529345294452954529645297452984529945300453014530245303453044530545306453074530845309453104531145312453134531445315453164531745318453194532045321453224532345324453254532645327453284532945330453314533245333453344533545336453374533845339453404534145342453434534445345453464534745348453494535045351453524535345354453554535645357453584535945360453614536245363453644536545366453674536845369453704537145372453734537445375453764537745378453794538045381453824538345384453854538645387453884538945390453914539245393453944539545396453974539845399454004540145402454034540445405454064540745408454094541045411454124541345414454154541645417454184541945420454214542245423454244542545426454274542845429454304543145432454334543445435454364543745438454394544045441454424544345444454454544645447454484544945450454514545245453454544545545456454574545845459454604546145462454634546445465454664546745468454694547045471454724547345474454754547645477454784547945480454814548245483454844548545486454874548845489454904549145492454934549445495454964549745498454994550045501455024550345504455054550645507455084550945510455114551245513455144551545516455174551845519455204552145522455234552445525455264552745528455294553045531455324553345534455354553645537455384553945540455414554245543455444554545546455474554845549455504555145552455534555445555455564555745558455594556045561455624556345564455654556645567455684556945570455714557245573455744557545576455774557845579455804558145582455834558445585455864558745588455894559045591455924559345594455954559645597455984559945600456014560245603456044560545606456074560845609456104561145612456134561445615456164561745618456194562045621456224562345624456254562645627456284562945630456314563245633456344563545636456374563845639456404564145642456434564445645456464564745648456494565045651456524565345654456554565645657456584565945660456614566245663456644566545666456674566845669456704567145672456734567445675456764567745678456794568045681456824568345684456854568645687456884568945690456914569245693456944569545696456974569845699457004570145702457034570445705457064570745708457094571045711457124571345714457154571645717457184571945720457214572245723457244572545726457274572845729457304573145732457334573445735457364573745738457394574045741457424574345744457454574645747457484574945750457514575245753457544575545756457574575845759457604576145762457634576445765457664576745768457694577045771457724577345774457754577645777457784577945780457814578245783457844578545786457874578845789457904579145792457934579445795457964579745798457994580045801458024580345804458054580645807458084580945810458114581245813458144581545816458174581845819458204582145822458234582445825458264582745828458294583045831458324583345834458354583645837458384583945840458414584245843458444584545846458474584845849458504585145852458534585445855458564585745858458594586045861458624586345864458654586645867458684586945870458714587245873458744587545876458774587845879458804588145882458834588445885458864588745888458894589045891458924589345894458954589645897458984589945900459014590245903459044590545906459074590845909459104591145912459134591445915459164591745918459194592045921459224592345924459254592645927459284592945930459314593245933459344593545936459374593845939459404594145942459434594445945459464594745948459494595045951459524595345954459554595645957459584595945960459614596245963459644596545966459674596845969459704597145972459734597445975459764597745978459794598045981459824598345984459854598645987459884598945990459914599245993459944599545996459974599845999460004600146002460034600446005460064600746008460094601046011460124601346014460154601646017460184601946020460214602246023460244602546026460274602846029460304603146032460334603446035460364603746038460394604046041460424604346044460454604646047460484604946050460514605246053460544605546056460574605846059460604606146062460634606446065460664606746068460694607046071460724607346074460754607646077460784607946080460814608246083460844608546086460874608846089460904609146092460934609446095460964609746098460994610046101461024610346104461054610646107461084610946110461114611246113461144611546116461174611846119461204612146122461234612446125461264612746128461294613046131461324613346134461354613646137461384613946140461414614246143461444614546146461474614846149461504615146152461534615446155461564615746158461594616046161461624616346164461654616646167461684616946170461714617246173461744617546176461774617846179461804618146182461834618446185461864618746188461894619046191461924619346194461954619646197461984619946200462014620246203462044620546206462074620846209462104621146212462134621446215462164621746218462194622046221462224622346224462254622646227462284622946230462314623246233462344623546236462374623846239462404624146242462434624446245462464624746248462494625046251462524625346254462554625646257462584625946260462614626246263462644626546266462674626846269462704627146272462734627446275462764627746278462794628046281462824628346284462854628646287462884628946290462914629246293462944629546296462974629846299463004630146302463034630446305463064630746308463094631046311463124631346314463154631646317463184631946320463214632246323463244632546326463274632846329463304633146332463334633446335463364633746338463394634046341463424634346344463454634646347463484634946350463514635246353463544635546356463574635846359463604636146362463634636446365463664636746368463694637046371463724637346374463754637646377463784637946380463814638246383463844638546386463874638846389463904639146392463934639446395463964639746398463994640046401464024640346404464054640646407464084640946410464114641246413464144641546416464174641846419464204642146422464234642446425464264642746428464294643046431464324643346434464354643646437464384643946440464414644246443464444644546446464474644846449464504645146452464534645446455464564645746458464594646046461464624646346464464654646646467464684646946470464714647246473464744647546476464774647846479464804648146482464834648446485464864648746488464894649046491464924649346494464954649646497464984649946500465014650246503465044650546506465074650846509465104651146512465134651446515465164651746518465194652046521465224652346524465254652646527465284652946530465314653246533465344653546536465374653846539465404654146542465434654446545465464654746548465494655046551465524655346554465554655646557465584655946560465614656246563465644656546566465674656846569465704657146572465734657446575465764657746578465794658046581465824658346584465854658646587465884658946590465914659246593465944659546596465974659846599466004660146602466034660446605466064660746608466094661046611466124661346614466154661646617466184661946620466214662246623466244662546626466274662846629466304663146632466334663446635466364663746638466394664046641466424664346644466454664646647466484664946650466514665246653466544665546656466574665846659466604666146662466634666446665466664666746668466694667046671466724667346674466754667646677466784667946680466814668246683466844668546686466874668846689466904669146692466934669446695466964669746698466994670046701467024670346704467054670646707467084670946710467114671246713467144671546716467174671846719467204672146722467234672446725467264672746728467294673046731467324673346734467354673646737467384673946740467414674246743467444674546746467474674846749467504675146752467534675446755467564675746758467594676046761467624676346764467654676646767467684676946770467714677246773467744677546776467774677846779467804678146782467834678446785467864678746788467894679046791467924679346794467954679646797467984679946800468014680246803468044680546806468074680846809468104681146812468134681446815468164681746818468194682046821468224682346824468254682646827468284682946830468314683246833468344683546836468374683846839468404684146842468434684446845468464684746848468494685046851468524685346854468554685646857468584685946860468614686246863468644686546866468674686846869468704687146872468734687446875468764687746878468794688046881468824688346884468854688646887468884688946890468914689246893468944689546896468974689846899469004690146902469034690446905469064690746908469094691046911469124691346914469154691646917469184691946920469214692246923469244692546926469274692846929469304693146932469334693446935469364693746938469394694046941469424694346944469454694646947469484694946950469514695246953469544695546956469574695846959469604696146962469634696446965469664696746968469694697046971469724697346974469754697646977469784697946980469814698246983469844698546986469874698846989469904699146992469934699446995469964699746998469994700047001470024700347004470054700647007470084700947010470114701247013470144701547016470174701847019470204702147022470234702447025470264702747028470294703047031470324703347034470354703647037470384703947040470414704247043470444704547046470474704847049470504705147052470534705447055470564705747058470594706047061470624706347064470654706647067470684706947070470714707247073470744707547076470774707847079470804708147082470834708447085470864708747088470894709047091470924709347094470954709647097470984709947100471014710247103471044710547106471074710847109471104711147112471134711447115471164711747118471194712047121471224712347124471254712647127471284712947130471314713247133471344713547136471374713847139471404714147142471434714447145471464714747148471494715047151471524715347154471554715647157471584715947160471614716247163471644716547166471674716847169471704717147172471734717447175471764717747178471794718047181471824718347184471854718647187471884718947190471914719247193471944719547196471974719847199472004720147202472034720447205472064720747208472094721047211472124721347214472154721647217472184721947220472214722247223472244722547226472274722847229472304723147232472334723447235472364723747238472394724047241472424724347244472454724647247472484724947250472514725247253472544725547256472574725847259472604726147262472634726447265472664726747268472694727047271472724727347274472754727647277472784727947280472814728247283472844728547286472874728847289472904729147292472934729447295472964729747298472994730047301473024730347304473054730647307473084730947310473114731247313473144731547316473174731847319473204732147322473234732447325473264732747328473294733047331473324733347334473354733647337473384733947340473414734247343473444734547346473474734847349473504735147352473534735447355473564735747358473594736047361473624736347364473654736647367473684736947370473714737247373473744737547376473774737847379473804738147382473834738447385473864738747388473894739047391473924739347394473954739647397473984739947400474014740247403474044740547406474074740847409474104741147412474134741447415474164741747418474194742047421474224742347424474254742647427474284742947430474314743247433474344743547436474374743847439474404744147442474434744447445474464744747448474494745047451474524745347454474554745647457474584745947460474614746247463474644746547466474674746847469474704747147472474734747447475474764747747478474794748047481474824748347484474854748647487474884748947490474914749247493474944749547496474974749847499475004750147502475034750447505475064750747508475094751047511475124751347514475154751647517475184751947520475214752247523475244752547526475274752847529475304753147532475334753447535475364753747538475394754047541475424754347544475454754647547475484754947550475514755247553475544755547556475574755847559475604756147562475634756447565475664756747568475694757047571475724757347574475754757647577475784757947580475814758247583475844758547586475874758847589475904759147592475934759447595475964759747598475994760047601476024760347604476054760647607476084760947610476114761247613476144761547616476174761847619476204762147622476234762447625476264762747628476294763047631476324763347634476354763647637476384763947640476414764247643476444764547646476474764847649476504765147652476534765447655476564765747658476594766047661476624766347664476654766647667476684766947670476714767247673476744767547676476774767847679476804768147682476834768447685476864768747688476894769047691476924769347694476954769647697476984769947700477014770247703477044770547706477074770847709477104771147712477134771447715477164771747718477194772047721477224772347724477254772647727477284772947730477314773247733477344773547736477374773847739477404774147742477434774447745477464774747748477494775047751477524775347754477554775647757477584775947760477614776247763477644776547766477674776847769477704777147772477734777447775477764777747778477794778047781477824778347784477854778647787477884778947790477914779247793477944779547796477974779847799478004780147802478034780447805478064780747808478094781047811478124781347814478154781647817478184781947820478214782247823478244782547826478274782847829478304783147832478334783447835478364783747838478394784047841478424784347844478454784647847478484784947850478514785247853478544785547856478574785847859478604786147862478634786447865478664786747868478694787047871478724787347874478754787647877478784787947880478814788247883478844788547886478874788847889478904789147892478934789447895478964789747898478994790047901479024790347904479054790647907479084790947910479114791247913479144791547916479174791847919479204792147922479234792447925479264792747928479294793047931479324793347934479354793647937479384793947940479414794247943479444794547946479474794847949479504795147952479534795447955479564795747958479594796047961479624796347964479654796647967479684796947970479714797247973479744797547976479774797847979479804798147982479834798447985479864798747988479894799047991479924799347994479954799647997479984799948000480014800248003480044800548006480074800848009480104801148012480134801448015480164801748018480194802048021480224802348024480254802648027480284802948030480314803248033480344803548036480374803848039480404804148042480434804448045480464804748048480494805048051480524805348054480554805648057480584805948060480614806248063480644806548066480674806848069480704807148072480734807448075480764807748078480794808048081480824808348084480854808648087480884808948090480914809248093480944809548096480974809848099481004810148102481034810448105481064810748108481094811048111481124811348114481154811648117481184811948120481214812248123481244812548126481274812848129481304813148132481334813448135481364813748138481394814048141481424814348144481454814648147481484814948150481514815248153481544815548156481574815848159481604816148162481634816448165481664816748168481694817048171481724817348174481754817648177481784817948180481814818248183481844818548186481874818848189481904819148192481934819448195481964819748198481994820048201482024820348204482054820648207482084820948210482114821248213482144821548216482174821848219482204822148222482234822448225482264822748228482294823048231482324823348234482354823648237482384823948240482414824248243482444824548246482474824848249482504825148252482534825448255482564825748258482594826048261482624826348264482654826648267482684826948270482714827248273482744827548276482774827848279482804828148282482834828448285482864828748288482894829048291482924829348294482954829648297482984829948300483014830248303483044830548306483074830848309483104831148312483134831448315483164831748318483194832048321483224832348324483254832648327483284832948330483314833248333483344833548336483374833848339483404834148342483434834448345483464834748348483494835048351483524835348354483554835648357483584835948360483614836248363483644836548366483674836848369483704837148372483734837448375483764837748378483794838048381483824838348384483854838648387483884838948390483914839248393483944839548396483974839848399484004840148402484034840448405484064840748408484094841048411484124841348414484154841648417484184841948420484214842248423484244842548426484274842848429484304843148432484334843448435484364843748438484394844048441484424844348444484454844648447484484844948450484514845248453484544845548456484574845848459484604846148462484634846448465484664846748468484694847048471484724847348474484754847648477484784847948480484814848248483484844848548486484874848848489484904849148492484934849448495484964849748498484994850048501485024850348504485054850648507485084850948510485114851248513485144851548516485174851848519485204852148522485234852448525485264852748528485294853048531485324853348534485354853648537485384853948540485414854248543485444854548546485474854848549485504855148552485534855448555485564855748558485594856048561485624856348564485654856648567485684856948570485714857248573485744857548576485774857848579485804858148582485834858448585485864858748588485894859048591485924859348594485954859648597485984859948600486014860248603486044860548606486074860848609486104861148612486134861448615486164861748618486194862048621486224862348624486254862648627486284862948630486314863248633486344863548636486374863848639486404864148642486434864448645486464864748648486494865048651486524865348654486554865648657486584865948660486614866248663486644866548666486674866848669486704867148672486734867448675486764867748678486794868048681486824868348684486854868648687486884868948690486914869248693486944869548696486974869848699487004870148702487034870448705487064870748708487094871048711487124871348714487154871648717487184871948720487214872248723487244872548726487274872848729487304873148732487334873448735487364873748738487394874048741487424874348744487454874648747487484874948750487514875248753487544875548756487574875848759487604876148762487634876448765487664876748768487694877048771487724877348774487754877648777487784877948780487814878248783487844878548786487874878848789487904879148792487934879448795487964879748798487994880048801488024880348804488054880648807488084880948810488114881248813488144881548816488174881848819488204882148822488234882448825488264882748828488294883048831488324883348834488354883648837488384883948840488414884248843488444884548846488474884848849488504885148852488534885448855488564885748858488594886048861488624886348864488654886648867488684886948870488714887248873488744887548876488774887848879488804888148882488834888448885488864888748888488894889048891488924889348894488954889648897488984889948900489014890248903489044890548906489074890848909489104891148912489134891448915489164891748918489194892048921489224892348924489254892648927489284892948930489314893248933489344893548936489374893848939489404894148942489434894448945489464894748948489494895048951489524895348954489554895648957489584895948960489614896248963489644896548966489674896848969489704897148972489734897448975489764897748978489794898048981489824898348984489854898648987489884898948990489914899248993489944899548996489974899848999490004900149002490034900449005490064900749008490094901049011490124901349014490154901649017490184901949020490214902249023490244902549026490274902849029490304903149032490334903449035490364903749038490394904049041490424904349044490454904649047490484904949050490514905249053490544905549056490574905849059490604906149062490634906449065490664906749068490694907049071490724907349074490754907649077490784907949080490814908249083490844908549086490874908849089490904909149092490934909449095490964909749098490994910049101491024910349104491054910649107491084910949110491114911249113491144911549116491174911849119491204912149122491234912449125491264912749128491294913049131491324913349134491354913649137491384913949140491414914249143491444914549146491474914849149491504915149152491534915449155491564915749158491594916049161491624916349164491654916649167491684916949170491714917249173491744917549176491774917849179491804918149182491834918449185491864918749188491894919049191491924919349194491954919649197491984919949200492014920249203492044920549206492074920849209492104921149212492134921449215492164921749218492194922049221492224922349224492254922649227492284922949230492314923249233492344923549236492374923849239492404924149242492434924449245492464924749248492494925049251492524925349254492554925649257492584925949260492614926249263492644926549266492674926849269492704927149272492734927449275492764927749278492794928049281492824928349284492854928649287492884928949290492914929249293492944929549296492974929849299493004930149302493034930449305493064930749308493094931049311493124931349314493154931649317493184931949320493214932249323493244932549326493274932849329493304933149332493334933449335493364933749338493394934049341493424934349344493454934649347493484934949350493514935249353493544935549356493574935849359493604936149362493634936449365493664936749368493694937049371493724937349374493754937649377493784937949380493814938249383493844938549386493874938849389493904939149392493934939449395493964939749398493994940049401494024940349404494054940649407494084940949410494114941249413494144941549416494174941849419494204942149422494234942449425494264942749428494294943049431494324943349434494354943649437494384943949440494414944249443494444944549446494474944849449494504945149452494534945449455494564945749458494594946049461494624946349464494654946649467494684946949470494714947249473494744947549476494774947849479494804948149482494834948449485494864948749488494894949049491494924949349494494954949649497494984949949500495014950249503495044950549506495074950849509495104951149512495134951449515495164951749518495194952049521495224952349524495254952649527495284952949530495314953249533495344953549536495374953849539495404954149542495434954449545495464954749548495494955049551495524955349554495554955649557495584955949560495614956249563495644956549566495674956849569495704957149572495734957449575495764957749578495794958049581495824958349584495854958649587495884958949590495914959249593495944959549596495974959849599496004960149602496034960449605496064960749608496094961049611496124961349614496154961649617496184961949620496214962249623496244962549626496274962849629496304963149632496334963449635496364963749638496394964049641496424964349644496454964649647496484964949650496514965249653496544965549656496574965849659496604966149662496634966449665496664966749668496694967049671496724967349674496754967649677496784967949680496814968249683496844968549686496874968849689496904969149692496934969449695496964969749698496994970049701497024970349704497054970649707497084970949710497114971249713497144971549716497174971849719497204972149722497234972449725497264972749728497294973049731497324973349734497354973649737497384973949740497414974249743497444974549746497474974849749497504975149752497534975449755497564975749758497594976049761497624976349764497654976649767497684976949770497714977249773497744977549776497774977849779497804978149782497834978449785497864978749788497894979049791497924979349794497954979649797497984979949800498014980249803498044980549806498074980849809498104981149812498134981449815498164981749818498194982049821498224982349824498254982649827498284982949830498314983249833498344983549836498374983849839498404984149842498434984449845498464984749848498494985049851498524985349854498554985649857498584985949860498614986249863498644986549866498674986849869498704987149872498734987449875498764987749878498794988049881498824988349884498854988649887498884988949890498914989249893498944989549896498974989849899499004990149902499034990449905499064990749908499094991049911499124991349914499154991649917499184991949920499214992249923499244992549926499274992849929499304993149932499334993449935499364993749938499394994049941499424994349944499454994649947499484994949950499514995249953499544995549956499574995849959499604996149962499634996449965499664996749968499694997049971499724997349974499754997649977499784997949980499814998249983499844998549986499874998849989499904999149992499934999449995499964999749998499995000050001500025000350004500055000650007500085000950010500115001250013500145001550016500175001850019500205002150022500235002450025500265002750028500295003050031500325003350034500355003650037500385003950040500415004250043500445004550046500475004850049500505005150052500535005450055500565005750058500595006050061500625006350064500655006650067500685006950070500715007250073500745007550076500775007850079500805008150082500835008450085500865008750088500895009050091500925009350094500955009650097500985009950100501015010250103501045010550106501075010850109501105011150112501135011450115501165011750118501195012050121501225012350124501255012650127501285012950130501315013250133501345013550136501375013850139501405014150142501435014450145501465014750148501495015050151501525015350154501555015650157501585015950160501615016250163501645016550166501675016850169501705017150172501735017450175501765017750178501795018050181501825018350184501855018650187501885018950190501915019250193501945019550196501975019850199502005020150202502035020450205502065020750208502095021050211502125021350214502155021650217502185021950220502215022250223502245022550226502275022850229502305023150232502335023450235502365023750238502395024050241502425024350244502455024650247502485024950250502515025250253502545025550256502575025850259502605026150262502635026450265502665026750268502695027050271502725027350274502755027650277502785027950280502815028250283502845028550286502875028850289502905029150292502935029450295502965029750298502995030050301503025030350304503055030650307503085030950310503115031250313503145031550316503175031850319503205032150322503235032450325503265032750328503295033050331503325033350334503355033650337503385033950340503415034250343503445034550346503475034850349503505035150352503535035450355503565035750358503595036050361503625036350364503655036650367503685036950370503715037250373503745037550376503775037850379503805038150382503835038450385503865038750388503895039050391503925039350394503955039650397503985039950400504015040250403504045040550406504075040850409504105041150412504135041450415504165041750418504195042050421504225042350424504255042650427504285042950430504315043250433504345043550436504375043850439504405044150442504435044450445504465044750448504495045050451504525045350454504555045650457504585045950460504615046250463504645046550466504675046850469504705047150472504735047450475504765047750478504795048050481504825048350484504855048650487504885048950490504915049250493504945049550496504975049850499505005050150502505035050450505505065050750508505095051050511505125051350514505155051650517505185051950520505215052250523505245052550526505275052850529505305053150532505335053450535505365053750538505395054050541505425054350544505455054650547505485054950550505515055250553505545055550556505575055850559505605056150562505635056450565505665056750568505695057050571505725057350574505755057650577505785057950580505815058250583505845058550586505875058850589505905059150592505935059450595505965059750598505995060050601506025060350604506055060650607506085060950610506115061250613506145061550616506175061850619506205062150622506235062450625506265062750628506295063050631506325063350634506355063650637506385063950640506415064250643506445064550646506475064850649506505065150652506535065450655506565065750658506595066050661506625066350664506655066650667506685066950670506715067250673506745067550676506775067850679506805068150682506835068450685506865068750688506895069050691506925069350694506955069650697506985069950700507015070250703507045070550706507075070850709507105071150712507135071450715507165071750718507195072050721507225072350724507255072650727507285072950730507315073250733507345073550736507375073850739507405074150742507435074450745507465074750748507495075050751507525075350754507555075650757507585075950760507615076250763507645076550766507675076850769507705077150772507735077450775507765077750778507795078050781507825078350784507855078650787507885078950790507915079250793507945079550796507975079850799508005080150802508035080450805508065080750808508095081050811508125081350814508155081650817508185081950820508215082250823508245082550826508275082850829508305083150832508335083450835508365083750838508395084050841508425084350844508455084650847508485084950850508515085250853508545085550856508575085850859508605086150862508635086450865508665086750868508695087050871508725087350874508755087650877508785087950880508815088250883508845088550886508875088850889508905089150892508935089450895508965089750898508995090050901509025090350904509055090650907509085090950910509115091250913509145091550916509175091850919509205092150922509235092450925509265092750928509295093050931509325093350934509355093650937509385093950940509415094250943509445094550946509475094850949509505095150952509535095450955509565095750958509595096050961509625096350964509655096650967509685096950970509715097250973509745097550976509775097850979509805098150982509835098450985509865098750988509895099050991509925099350994509955099650997509985099951000510015100251003510045100551006510075100851009510105101151012510135101451015510165101751018510195102051021510225102351024510255102651027510285102951030510315103251033510345103551036510375103851039510405104151042510435104451045510465104751048510495105051051510525105351054510555105651057510585105951060510615106251063510645106551066510675106851069510705107151072510735107451075510765107751078510795108051081510825108351084510855108651087510885108951090510915109251093510945109551096510975109851099511005110151102511035110451105511065110751108511095111051111511125111351114511155111651117511185111951120511215112251123511245112551126511275112851129511305113151132511335113451135511365113751138511395114051141511425114351144511455114651147511485114951150511515115251153511545115551156511575115851159511605116151162511635116451165511665116751168511695117051171511725117351174511755117651177511785117951180511815118251183511845118551186511875118851189511905119151192511935119451195511965119751198511995120051201512025120351204512055120651207512085120951210512115121251213512145121551216512175121851219512205122151222512235122451225512265122751228512295123051231512325123351234512355123651237512385123951240512415124251243512445124551246512475124851249512505125151252512535125451255512565125751258512595126051261512625126351264512655126651267512685126951270512715127251273512745127551276512775127851279512805128151282512835128451285512865128751288512895129051291512925129351294512955129651297512985129951300513015130251303513045130551306513075130851309513105131151312513135131451315513165131751318513195132051321513225132351324513255132651327513285132951330513315133251333513345133551336513375133851339513405134151342513435134451345513465134751348513495135051351513525135351354513555135651357513585135951360513615136251363513645136551366513675136851369513705137151372513735137451375513765137751378513795138051381513825138351384513855138651387513885138951390513915139251393513945139551396513975139851399514005140151402514035140451405514065140751408514095141051411514125141351414514155141651417514185141951420514215142251423514245142551426514275142851429514305143151432514335143451435514365143751438514395144051441514425144351444514455144651447514485144951450514515145251453514545145551456514575145851459514605146151462514635146451465514665146751468514695147051471514725147351474514755147651477514785147951480514815148251483514845148551486514875148851489514905149151492514935149451495514965149751498514995150051501515025150351504515055150651507515085150951510515115151251513515145151551516515175151851519515205152151522515235152451525515265152751528515295153051531515325153351534515355153651537515385153951540515415154251543515445154551546515475154851549515505155151552515535155451555515565155751558515595156051561515625156351564515655156651567515685156951570515715157251573515745157551576515775157851579515805158151582515835158451585515865158751588515895159051591515925159351594515955159651597515985159951600516015160251603516045160551606516075160851609516105161151612516135161451615516165161751618516195162051621516225162351624516255162651627516285162951630516315163251633516345163551636516375163851639516405164151642516435164451645516465164751648516495165051651516525165351654516555165651657516585165951660516615166251663516645166551666516675166851669516705167151672516735167451675516765167751678516795168051681516825168351684516855168651687516885168951690516915169251693516945169551696516975169851699517005170151702517035170451705517065170751708517095171051711517125171351714517155171651717517185171951720517215172251723517245172551726517275172851729517305173151732517335173451735517365173751738517395174051741517425174351744517455174651747517485174951750517515175251753517545175551756517575175851759517605176151762517635176451765517665176751768517695177051771517725177351774517755177651777517785177951780517815178251783517845178551786517875178851789517905179151792517935179451795517965179751798517995180051801518025180351804518055180651807518085180951810518115181251813518145181551816518175181851819518205182151822518235182451825518265182751828518295183051831518325183351834518355183651837518385183951840518415184251843518445184551846518475184851849518505185151852518535185451855518565185751858518595186051861518625186351864518655186651867518685186951870518715187251873518745187551876518775187851879518805188151882518835188451885518865188751888518895189051891518925189351894518955189651897518985189951900519015190251903519045190551906519075190851909519105191151912519135191451915519165191751918519195192051921519225192351924519255192651927519285192951930519315193251933519345193551936519375193851939519405194151942519435194451945519465194751948519495195051951519525195351954519555195651957519585195951960519615196251963519645196551966519675196851969519705197151972519735197451975519765197751978519795198051981519825198351984519855198651987519885198951990519915199251993519945199551996519975199851999520005200152002520035200452005520065200752008520095201052011520125201352014520155201652017520185201952020520215202252023520245202552026520275202852029520305203152032520335203452035520365203752038520395204052041520425204352044520455204652047520485204952050520515205252053520545205552056520575205852059520605206152062520635206452065520665206752068520695207052071520725207352074520755207652077520785207952080520815208252083520845208552086520875208852089520905209152092520935209452095520965209752098520995210052101521025210352104521055210652107521085210952110521115211252113521145211552116521175211852119521205212152122521235212452125521265212752128521295213052131521325213352134521355213652137521385213952140521415214252143521445214552146521475214852149521505215152152521535215452155521565215752158521595216052161521625216352164521655216652167521685216952170521715217252173521745217552176521775217852179521805218152182521835218452185521865218752188521895219052191521925219352194521955219652197521985219952200522015220252203522045220552206522075220852209522105221152212522135221452215522165221752218522195222052221522225222352224522255222652227522285222952230522315223252233522345223552236522375223852239522405224152242522435224452245522465224752248522495225052251522525225352254522555225652257522585225952260522615226252263522645226552266522675226852269522705227152272522735227452275522765227752278522795228052281522825228352284522855228652287522885228952290522915229252293522945229552296522975229852299523005230152302523035230452305523065230752308523095231052311523125231352314523155231652317523185231952320523215232252323523245232552326523275232852329523305233152332523335233452335523365233752338523395234052341523425234352344523455234652347523485234952350523515235252353523545235552356523575235852359523605236152362523635236452365523665236752368523695237052371523725237352374523755237652377523785237952380523815238252383523845238552386523875238852389523905239152392523935239452395523965239752398523995240052401524025240352404524055240652407524085240952410524115241252413524145241552416524175241852419524205242152422524235242452425524265242752428524295243052431524325243352434524355243652437524385243952440524415244252443524445244552446524475244852449524505245152452524535245452455524565245752458524595246052461524625246352464524655246652467524685246952470524715247252473524745247552476524775247852479524805248152482524835248452485524865248752488524895249052491524925249352494524955249652497524985249952500525015250252503525045250552506525075250852509525105251152512525135251452515525165251752518525195252052521525225252352524525255252652527525285252952530525315253252533525345253552536525375253852539525405254152542525435254452545525465254752548525495255052551525525255352554525555255652557525585255952560525615256252563525645256552566525675256852569525705257152572525735257452575525765257752578525795258052581525825258352584525855258652587525885258952590525915259252593525945259552596525975259852599526005260152602526035260452605526065260752608526095261052611526125261352614526155261652617526185261952620526215262252623526245262552626526275262852629526305263152632526335263452635526365263752638526395264052641526425264352644526455264652647526485264952650526515265252653526545265552656526575265852659526605266152662526635266452665526665266752668526695267052671526725267352674526755267652677526785267952680526815268252683526845268552686526875268852689526905269152692526935269452695526965269752698526995270052701527025270352704527055270652707527085270952710527115271252713527145271552716527175271852719527205272152722527235272452725527265272752728527295273052731527325273352734527355273652737527385273952740527415274252743527445274552746527475274852749527505275152752527535275452755527565275752758527595276052761527625276352764527655276652767527685276952770527715277252773527745277552776527775277852779527805278152782527835278452785527865278752788527895279052791527925279352794527955279652797527985279952800528015280252803528045280552806528075280852809528105281152812528135281452815528165281752818528195282052821528225282352824528255282652827528285282952830528315283252833528345283552836528375283852839528405284152842528435284452845528465284752848528495285052851528525285352854528555285652857528585285952860528615286252863528645286552866528675286852869528705287152872528735287452875528765287752878528795288052881528825288352884528855288652887528885288952890528915289252893528945289552896528975289852899529005290152902529035290452905529065290752908529095291052911529125291352914529155291652917529185291952920529215292252923529245292552926529275292852929529305293152932529335293452935529365293752938529395294052941529425294352944529455294652947529485294952950529515295252953529545295552956529575295852959529605296152962529635296452965529665296752968529695297052971529725297352974529755297652977529785297952980529815298252983529845298552986529875298852989529905299152992529935299452995529965299752998529995300053001530025300353004530055300653007530085300953010530115301253013530145301553016530175301853019530205302153022530235302453025530265302753028530295303053031530325303353034530355303653037530385303953040530415304253043530445304553046530475304853049530505305153052530535305453055530565305753058530595306053061530625306353064530655306653067530685306953070530715307253073530745307553076530775307853079530805308153082530835308453085530865308753088530895309053091530925309353094530955309653097530985309953100531015310253103531045310553106531075310853109531105311153112531135311453115531165311753118531195312053121531225312353124531255312653127531285312953130531315313253133531345313553136531375313853139531405314153142531435314453145531465314753148531495315053151531525315353154531555315653157531585315953160531615316253163531645316553166531675316853169531705317153172531735317453175531765317753178531795318053181531825318353184531855318653187531885318953190531915319253193531945319553196531975319853199532005320153202532035320453205532065320753208532095321053211532125321353214532155321653217532185321953220532215322253223532245322553226532275322853229532305323153232532335323453235532365323753238532395324053241532425324353244532455324653247532485324953250532515325253253532545325553256532575325853259532605326153262532635326453265532665326753268532695327053271532725327353274532755327653277532785327953280532815328253283532845328553286532875328853289532905329153292532935329453295532965329753298532995330053301533025330353304533055330653307533085330953310533115331253313533145331553316533175331853319533205332153322533235332453325533265332753328533295333053331533325333353334533355333653337533385333953340533415334253343533445334553346533475334853349533505335153352533535335453355533565335753358533595336053361533625336353364533655336653367533685336953370533715337253373533745337553376533775337853379533805338153382533835338453385533865338753388533895339053391533925339353394533955339653397533985339953400534015340253403534045340553406534075340853409534105341153412534135341453415534165341753418534195342053421534225342353424534255342653427534285342953430534315343253433534345343553436534375343853439534405344153442534435344453445534465344753448534495345053451534525345353454534555345653457534585345953460534615346253463534645346553466534675346853469534705347153472534735347453475534765347753478534795348053481534825348353484534855348653487534885348953490534915349253493534945349553496534975349853499535005350153502535035350453505535065350753508535095351053511535125351353514535155351653517535185351953520535215352253523535245352553526535275352853529535305353153532535335353453535535365353753538535395354053541535425354353544535455354653547535485354953550535515355253553535545355553556535575355853559535605356153562535635356453565535665356753568535695357053571535725357353574535755357653577535785357953580535815358253583535845358553586535875358853589535905359153592535935359453595535965359753598535995360053601536025360353604536055360653607536085360953610536115361253613536145361553616536175361853619536205362153622536235362453625536265362753628536295363053631536325363353634536355363653637536385363953640536415364253643536445364553646536475364853649536505365153652536535365453655536565365753658536595366053661536625366353664536655366653667536685366953670536715367253673536745367553676536775367853679536805368153682536835368453685536865368753688536895369053691536925369353694536955369653697536985369953700537015370253703537045370553706537075370853709537105371153712537135371453715537165371753718537195372053721537225372353724537255372653727537285372953730537315373253733537345373553736537375373853739537405374153742537435374453745537465374753748537495375053751537525375353754537555375653757537585375953760537615376253763537645376553766537675376853769537705377153772537735377453775537765377753778537795378053781537825378353784537855378653787537885378953790537915379253793537945379553796537975379853799538005380153802538035380453805538065380753808538095381053811538125381353814538155381653817538185381953820538215382253823538245382553826538275382853829538305383153832538335383453835538365383753838538395384053841538425384353844538455384653847538485384953850538515385253853538545385553856538575385853859538605386153862538635386453865538665386753868538695387053871538725387353874538755387653877538785387953880538815388253883538845388553886538875388853889538905389153892538935389453895538965389753898538995390053901539025390353904539055390653907539085390953910539115391253913539145391553916539175391853919539205392153922539235392453925539265392753928539295393053931539325393353934539355393653937539385393953940539415394253943539445394553946539475394853949539505395153952539535395453955539565395753958539595396053961539625396353964539655396653967539685396953970539715397253973539745397553976539775397853979539805398153982539835398453985539865398753988539895399053991539925399353994539955399653997539985399954000540015400254003540045400554006540075400854009540105401154012540135401454015540165401754018540195402054021540225402354024540255402654027540285402954030540315403254033540345403554036540375403854039540405404154042540435404454045540465404754048540495405054051540525405354054540555405654057540585405954060540615406254063540645406554066540675406854069540705407154072540735407454075540765407754078540795408054081540825408354084540855408654087540885408954090540915409254093540945409554096540975409854099541005410154102541035410454105541065410754108541095411054111541125411354114541155411654117541185411954120541215412254123541245412554126541275412854129541305413154132541335413454135541365413754138541395414054141541425414354144541455414654147541485414954150541515415254153541545415554156541575415854159541605416154162541635416454165541665416754168541695417054171541725417354174541755417654177541785417954180541815418254183541845418554186541875418854189541905419154192541935419454195541965419754198541995420054201542025420354204542055420654207542085420954210542115421254213542145421554216542175421854219542205422154222542235422454225542265422754228542295423054231542325423354234542355423654237542385423954240542415424254243542445424554246542475424854249542505425154252542535425454255542565425754258542595426054261542625426354264542655426654267542685426954270542715427254273542745427554276542775427854279542805428154282542835428454285542865428754288542895429054291542925429354294542955429654297542985429954300543015430254303543045430554306543075430854309543105431154312543135431454315543165431754318543195432054321543225432354324543255432654327543285432954330543315433254333543345433554336543375433854339543405434154342543435434454345543465434754348543495435054351543525435354354543555435654357543585435954360543615436254363543645436554366543675436854369543705437154372543735437454375543765437754378543795438054381543825438354384543855438654387543885438954390543915439254393543945439554396543975439854399544005440154402544035440454405544065440754408544095441054411544125441354414544155441654417544185441954420544215442254423544245442554426544275442854429544305443154432544335443454435544365443754438544395444054441544425444354444544455444654447544485444954450544515445254453544545445554456544575445854459544605446154462544635446454465544665446754468544695447054471544725447354474544755447654477544785447954480544815448254483544845448554486544875448854489544905449154492544935449454495544965449754498544995450054501545025450354504545055450654507545085450954510545115451254513545145451554516545175451854519545205452154522545235452454525545265452754528545295453054531545325453354534545355453654537545385453954540545415454254543545445454554546545475454854549545505455154552545535455454555545565455754558545595456054561545625456354564545655456654567545685456954570545715457254573545745457554576545775457854579545805458154582545835458454585545865458754588545895459054591545925459354594545955459654597545985459954600546015460254603546045460554606546075460854609546105461154612546135461454615546165461754618546195462054621546225462354624546255462654627546285462954630546315463254633546345463554636546375463854639546405464154642546435464454645546465464754648546495465054651546525465354654546555465654657546585465954660546615466254663546645466554666546675466854669546705467154672546735467454675546765467754678546795468054681546825468354684546855468654687546885468954690546915469254693546945469554696546975469854699547005470154702547035470454705547065470754708547095471054711547125471354714547155471654717547185471954720547215472254723547245472554726547275472854729547305473154732547335473454735547365473754738547395474054741547425474354744547455474654747547485474954750547515475254753547545475554756547575475854759547605476154762547635476454765547665476754768547695477054771547725477354774547755477654777547785477954780547815478254783547845478554786547875478854789547905479154792547935479454795547965479754798547995480054801548025480354804548055480654807548085480954810548115481254813548145481554816548175481854819548205482154822548235482454825548265482754828548295483054831548325483354834548355483654837548385483954840548415484254843548445484554846548475484854849548505485154852548535485454855548565485754858548595486054861548625486354864548655486654867548685486954870548715487254873548745487554876548775487854879548805488154882548835488454885548865488754888548895489054891548925489354894548955489654897548985489954900549015490254903549045490554906549075490854909549105491154912549135491454915549165491754918549195492054921549225492354924549255492654927549285492954930549315493254933549345493554936549375493854939549405494154942549435494454945549465494754948549495495054951549525495354954549555495654957549585495954960549615496254963549645496554966549675496854969549705497154972549735497454975549765497754978549795498054981549825498354984549855498654987549885498954990549915499254993549945499554996549975499854999550005500155002550035500455005550065500755008550095501055011550125501355014550155501655017550185501955020550215502255023550245502555026550275502855029550305503155032550335503455035550365503755038550395504055041550425504355044550455504655047550485504955050550515505255053550545505555056550575505855059550605506155062550635506455065550665506755068550695507055071550725507355074550755507655077550785507955080550815508255083550845508555086550875508855089550905509155092550935509455095550965509755098550995510055101551025510355104551055510655107551085510955110551115511255113551145511555116551175511855119551205512155122551235512455125551265512755128551295513055131551325513355134551355513655137551385513955140551415514255143551445514555146551475514855149551505515155152551535515455155551565515755158551595516055161551625516355164551655516655167551685516955170551715517255173551745517555176551775517855179551805518155182551835518455185551865518755188551895519055191551925519355194551955519655197551985519955200552015520255203552045520555206552075520855209552105521155212552135521455215552165521755218552195522055221552225522355224552255522655227552285522955230552315523255233552345523555236552375523855239552405524155242552435524455245552465524755248552495525055251552525525355254552555525655257552585525955260552615526255263552645526555266552675526855269552705527155272552735527455275552765527755278552795528055281552825528355284552855528655287552885528955290552915529255293552945529555296552975529855299553005530155302553035530455305553065530755308553095531055311553125531355314553155531655317553185531955320553215532255323553245532555326553275532855329553305533155332553335533455335553365533755338553395534055341553425534355344553455534655347553485534955350553515535255353553545535555356553575535855359553605536155362553635536455365553665536755368553695537055371553725537355374553755537655377553785537955380553815538255383553845538555386553875538855389553905539155392553935539455395553965539755398553995540055401554025540355404554055540655407554085540955410554115541255413554145541555416554175541855419554205542155422554235542455425554265542755428554295543055431554325543355434554355543655437554385543955440554415544255443554445544555446554475544855449554505545155452554535545455455554565545755458554595546055461554625546355464554655546655467554685546955470554715547255473554745547555476554775547855479554805548155482554835548455485554865548755488554895549055491554925549355494554955549655497554985549955500555015550255503555045550555506555075550855509555105551155512555135551455515555165551755518555195552055521555225552355524555255552655527555285552955530555315553255533555345553555536555375553855539555405554155542555435554455545555465554755548555495555055551555525555355554555555555655557555585555955560555615556255563555645556555566555675556855569555705557155572555735557455575555765557755578555795558055581555825558355584555855558655587555885558955590555915559255593555945559555596555975559855599556005560155602556035560455605556065560755608556095561055611556125561355614556155561655617556185561955620556215562255623556245562555626556275562855629556305563155632556335563455635556365563755638556395564055641556425564355644556455564655647556485564955650556515565255653556545565555656556575565855659556605566155662556635566455665556665566755668556695567055671556725567355674556755567655677556785567955680556815568255683556845568555686556875568855689556905569155692556935569455695556965569755698556995570055701557025570355704557055570655707557085570955710557115571255713557145571555716557175571855719557205572155722557235572455725557265572755728557295573055731557325573355734557355573655737557385573955740557415574255743557445574555746557475574855749557505575155752557535575455755557565575755758557595576055761557625576355764557655576655767557685576955770557715577255773557745577555776557775577855779557805578155782557835578455785557865578755788557895579055791557925579355794557955579655797557985579955800558015580255803558045580555806558075580855809558105581155812558135581455815558165581755818558195582055821558225582355824558255582655827558285582955830558315583255833558345583555836558375583855839558405584155842558435584455845558465584755848558495585055851558525585355854558555585655857558585585955860558615586255863558645586555866558675586855869558705587155872558735587455875558765587755878558795588055881558825588355884558855588655887558885588955890558915589255893558945589555896558975589855899559005590155902559035590455905559065590755908559095591055911559125591355914559155591655917559185591955920559215592255923559245592555926559275592855929559305593155932559335593455935559365593755938559395594055941559425594355944559455594655947559485594955950559515595255953559545595555956559575595855959559605596155962559635596455965559665596755968559695597055971559725597355974559755597655977559785597955980559815598255983559845598555986559875598855989559905599155992559935599455995559965599755998559995600056001560025600356004560055600656007560085600956010560115601256013560145601556016560175601856019560205602156022560235602456025560265602756028560295603056031560325603356034560355603656037560385603956040560415604256043560445604556046560475604856049560505605156052560535605456055560565605756058560595606056061560625606356064560655606656067560685606956070560715607256073560745607556076560775607856079560805608156082560835608456085560865608756088560895609056091560925609356094560955609656097560985609956100561015610256103561045610556106561075610856109561105611156112561135611456115561165611756118561195612056121561225612356124561255612656127561285612956130561315613256133561345613556136561375613856139561405614156142561435614456145561465614756148561495615056151561525615356154561555615656157561585615956160561615616256163561645616556166561675616856169561705617156172561735617456175561765617756178561795618056181561825618356184561855618656187561885618956190561915619256193561945619556196561975619856199562005620156202562035620456205562065620756208562095621056211562125621356214562155621656217562185621956220562215622256223562245622556226562275622856229562305623156232562335623456235562365623756238562395624056241562425624356244562455624656247562485624956250562515625256253562545625556256562575625856259562605626156262562635626456265562665626756268562695627056271562725627356274562755627656277562785627956280562815628256283562845628556286562875628856289562905629156292562935629456295562965629756298562995630056301563025630356304563055630656307563085630956310563115631256313563145631556316563175631856319563205632156322563235632456325563265632756328563295633056331563325633356334563355633656337563385633956340563415634256343563445634556346563475634856349563505635156352563535635456355563565635756358563595636056361563625636356364563655636656367563685636956370563715637256373563745637556376563775637856379563805638156382563835638456385563865638756388563895639056391563925639356394563955639656397563985639956400564015640256403564045640556406564075640856409564105641156412564135641456415564165641756418564195642056421564225642356424564255642656427564285642956430564315643256433564345643556436564375643856439564405644156442564435644456445564465644756448564495645056451564525645356454564555645656457564585645956460564615646256463564645646556466564675646856469564705647156472564735647456475564765647756478564795648056481564825648356484564855648656487564885648956490564915649256493564945649556496564975649856499565005650156502565035650456505565065650756508565095651056511565125651356514565155651656517565185651956520565215652256523565245652556526565275652856529565305653156532565335653456535565365653756538565395654056541565425654356544565455654656547565485654956550565515655256553565545655556556565575655856559565605656156562565635656456565565665656756568565695657056571565725657356574565755657656577565785657956580565815658256583565845658556586565875658856589565905659156592565935659456595565965659756598565995660056601566025660356604566055660656607566085660956610566115661256613566145661556616566175661856619566205662156622566235662456625566265662756628566295663056631566325663356634566355663656637566385663956640566415664256643566445664556646566475664856649566505665156652566535665456655566565665756658566595666056661566625666356664566655666656667566685666956670566715667256673566745667556676566775667856679566805668156682566835668456685566865668756688566895669056691566925669356694566955669656697566985669956700567015670256703567045670556706567075670856709567105671156712567135671456715567165671756718567195672056721567225672356724567255672656727567285672956730567315673256733567345673556736567375673856739567405674156742567435674456745567465674756748567495675056751567525675356754567555675656757567585675956760567615676256763567645676556766567675676856769567705677156772567735677456775567765677756778567795678056781567825678356784567855678656787567885678956790567915679256793567945679556796567975679856799568005680156802568035680456805568065680756808568095681056811568125681356814568155681656817568185681956820568215682256823568245682556826568275682856829568305683156832568335683456835568365683756838568395684056841568425684356844568455684656847568485684956850568515685256853568545685556856568575685856859568605686156862568635686456865568665686756868568695687056871568725687356874568755687656877568785687956880568815688256883568845688556886568875688856889568905689156892568935689456895568965689756898568995690056901569025690356904569055690656907569085690956910569115691256913569145691556916569175691856919569205692156922569235692456925569265692756928569295693056931569325693356934569355693656937569385693956940569415694256943569445694556946569475694856949569505695156952569535695456955569565695756958569595696056961569625696356964569655696656967569685696956970569715697256973569745697556976569775697856979569805698156982569835698456985569865698756988569895699056991569925699356994569955699656997569985699957000570015700257003570045700557006570075700857009570105701157012570135701457015570165701757018570195702057021570225702357024570255702657027570285702957030570315703257033570345703557036570375703857039570405704157042570435704457045570465704757048570495705057051570525705357054570555705657057570585705957060570615706257063570645706557066570675706857069570705707157072570735707457075570765707757078570795708057081570825708357084570855708657087570885708957090570915709257093570945709557096570975709857099571005710157102571035710457105571065710757108571095711057111571125711357114571155711657117571185711957120571215712257123571245712557126571275712857129571305713157132571335713457135571365713757138571395714057141571425714357144571455714657147571485714957150571515715257153571545715557156571575715857159571605716157162571635716457165571665716757168571695717057171571725717357174571755717657177571785717957180571815718257183571845718557186571875718857189571905719157192571935719457195571965719757198571995720057201572025720357204572055720657207572085720957210572115721257213572145721557216572175721857219572205722157222572235722457225572265722757228572295723057231572325723357234572355723657237572385723957240572415724257243572445724557246572475724857249572505725157252572535725457255572565725757258572595726057261572625726357264572655726657267572685726957270572715727257273572745727557276572775727857279572805728157282572835728457285572865728757288572895729057291572925729357294572955729657297572985729957300573015730257303573045730557306573075730857309573105731157312573135731457315573165731757318573195732057321573225732357324573255732657327573285732957330573315733257333573345733557336573375733857339573405734157342573435734457345573465734757348573495735057351573525735357354573555735657357573585735957360573615736257363573645736557366573675736857369573705737157372573735737457375573765737757378573795738057381573825738357384573855738657387573885738957390573915739257393573945739557396573975739857399574005740157402574035740457405574065740757408574095741057411574125741357414574155741657417574185741957420574215742257423574245742557426574275742857429574305743157432574335743457435574365743757438574395744057441574425744357444574455744657447574485744957450574515745257453574545745557456574575745857459574605746157462574635746457465574665746757468574695747057471574725747357474574755747657477574785747957480574815748257483574845748557486574875748857489574905749157492574935749457495574965749757498574995750057501575025750357504575055750657507575085750957510575115751257513575145751557516575175751857519575205752157522575235752457525575265752757528575295753057531575325753357534575355753657537575385753957540575415754257543575445754557546575475754857549575505755157552575535755457555575565755757558575595756057561575625756357564575655756657567575685756957570575715757257573575745757557576575775757857579575805758157582575835758457585575865758757588575895759057591575925759357594575955759657597575985759957600576015760257603576045760557606576075760857609576105761157612576135761457615576165761757618576195762057621576225762357624576255762657627576285762957630576315763257633576345763557636576375763857639576405764157642576435764457645576465764757648576495765057651576525765357654576555765657657576585765957660576615766257663576645766557666576675766857669576705767157672576735767457675576765767757678576795768057681576825768357684576855768657687576885768957690576915769257693576945769557696576975769857699577005770157702577035770457705577065770757708577095771057711577125771357714577155771657717577185771957720577215772257723577245772557726577275772857729577305773157732577335773457735577365773757738577395774057741577425774357744577455774657747577485774957750577515775257753577545775557756577575775857759577605776157762577635776457765577665776757768577695777057771577725777357774577755777657777577785777957780577815778257783577845778557786577875778857789577905779157792577935779457795577965779757798577995780057801578025780357804578055780657807578085780957810578115781257813578145781557816578175781857819578205782157822578235782457825578265782757828578295783057831578325783357834578355783657837578385783957840578415784257843578445784557846578475784857849578505785157852578535785457855578565785757858578595786057861578625786357864578655786657867578685786957870578715787257873578745787557876578775787857879578805788157882578835788457885578865788757888578895789057891578925789357894578955789657897578985789957900579015790257903579045790557906579075790857909579105791157912579135791457915579165791757918579195792057921579225792357924579255792657927579285792957930579315793257933579345793557936579375793857939579405794157942579435794457945579465794757948579495795057951579525795357954579555795657957579585795957960579615796257963579645796557966579675796857969579705797157972579735797457975579765797757978579795798057981579825798357984579855798657987579885798957990579915799257993579945799557996579975799857999580005800158002580035800458005580065800758008580095801058011580125801358014580155801658017580185801958020580215802258023580245802558026580275802858029580305803158032580335803458035580365803758038580395804058041580425804358044580455804658047580485804958050580515805258053580545805558056580575805858059580605806158062580635806458065580665806758068580695807058071580725807358074580755807658077580785807958080580815808258083580845808558086580875808858089580905809158092580935809458095580965809758098580995810058101581025810358104581055810658107581085810958110581115811258113581145811558116581175811858119581205812158122581235812458125581265812758128581295813058131581325813358134581355813658137581385813958140581415814258143581445814558146581475814858149581505815158152581535815458155581565815758158581595816058161581625816358164581655816658167581685816958170581715817258173581745817558176581775817858179581805818158182581835818458185581865818758188581895819058191581925819358194581955819658197581985819958200582015820258203582045820558206582075820858209582105821158212582135821458215582165821758218582195822058221582225822358224582255822658227582285822958230582315823258233582345823558236582375823858239582405824158242582435824458245582465824758248582495825058251582525825358254582555825658257582585825958260582615826258263582645826558266582675826858269582705827158272582735827458275582765827758278582795828058281582825828358284582855828658287582885828958290582915829258293582945829558296582975829858299583005830158302583035830458305583065830758308583095831058311583125831358314583155831658317583185831958320583215832258323583245832558326583275832858329583305833158332583335833458335583365833758338583395834058341583425834358344583455834658347583485834958350583515835258353583545835558356583575835858359583605836158362583635836458365583665836758368583695837058371583725837358374583755837658377583785837958380583815838258383583845838558386583875838858389583905839158392583935839458395583965839758398583995840058401584025840358404584055840658407584085840958410584115841258413584145841558416584175841858419584205842158422584235842458425584265842758428584295843058431584325843358434584355843658437584385843958440584415844258443584445844558446584475844858449584505845158452584535845458455584565845758458584595846058461584625846358464584655846658467584685846958470584715847258473584745847558476584775847858479584805848158482584835848458485584865848758488584895849058491584925849358494584955849658497584985849958500585015850258503585045850558506585075850858509585105851158512585135851458515585165851758518585195852058521585225852358524585255852658527585285852958530585315853258533585345853558536585375853858539585405854158542585435854458545585465854758548585495855058551585525855358554585555855658557585585855958560585615856258563585645856558566585675856858569585705857158572585735857458575585765857758578585795858058581585825858358584585855858658587585885858958590585915859258593585945859558596585975859858599586005860158602586035860458605586065860758608586095861058611586125861358614586155861658617586185861958620586215862258623586245862558626586275862858629586305863158632586335863458635586365863758638586395864058641586425864358644586455864658647586485864958650586515865258653586545865558656586575865858659586605866158662586635866458665586665866758668586695867058671586725867358674586755867658677586785867958680586815868258683586845868558686586875868858689586905869158692586935869458695586965869758698586995870058701587025870358704587055870658707587085870958710587115871258713587145871558716587175871858719587205872158722587235872458725587265872758728587295873058731587325873358734587355873658737587385873958740587415874258743587445874558746587475874858749587505875158752587535875458755587565875758758587595876058761587625876358764587655876658767587685876958770587715877258773587745877558776587775877858779587805878158782587835878458785587865878758788587895879058791587925879358794587955879658797587985879958800588015880258803588045880558806588075880858809588105881158812588135881458815588165881758818588195882058821588225882358824588255882658827588285882958830588315883258833588345883558836588375883858839588405884158842588435884458845588465884758848588495885058851588525885358854588555885658857588585885958860588615886258863588645886558866588675886858869588705887158872588735887458875588765887758878588795888058881588825888358884588855888658887588885888958890588915889258893588945889558896588975889858899589005890158902589035890458905589065890758908589095891058911589125891358914589155891658917589185891958920589215892258923589245892558926589275892858929589305893158932589335893458935589365893758938589395894058941589425894358944589455894658947589485894958950589515895258953589545895558956589575895858959589605896158962589635896458965589665896758968589695897058971589725897358974589755897658977589785897958980589815898258983589845898558986589875898858989589905899158992589935899458995589965899758998589995900059001590025900359004590055900659007590085900959010590115901259013590145901559016590175901859019590205902159022590235902459025590265902759028590295903059031590325903359034590355903659037590385903959040590415904259043590445904559046590475904859049590505905159052590535905459055590565905759058590595906059061590625906359064590655906659067590685906959070590715907259073590745907559076590775907859079590805908159082590835908459085590865908759088590895909059091590925909359094590955909659097590985909959100591015910259103591045910559106591075910859109591105911159112591135911459115591165911759118591195912059121591225912359124591255912659127591285912959130591315913259133591345913559136591375913859139591405914159142591435914459145591465914759148591495915059151591525915359154591555915659157591585915959160591615916259163591645916559166591675916859169591705917159172591735917459175591765917759178591795918059181591825918359184591855918659187591885918959190591915919259193591945919559196591975919859199592005920159202592035920459205592065920759208592095921059211592125921359214592155921659217592185921959220592215922259223592245922559226592275922859229592305923159232592335923459235592365923759238592395924059241592425924359244592455924659247592485924959250592515925259253592545925559256592575925859259592605926159262592635926459265592665926759268592695927059271592725927359274592755927659277592785927959280592815928259283592845928559286592875928859289592905929159292592935929459295592965929759298592995930059301593025930359304593055930659307593085930959310593115931259313593145931559316593175931859319593205932159322593235932459325593265932759328593295933059331593325933359334593355933659337593385933959340593415934259343593445934559346593475934859349593505935159352593535935459355593565935759358593595936059361593625936359364593655936659367593685936959370593715937259373593745937559376593775937859379593805938159382593835938459385593865938759388593895939059391593925939359394593955939659397593985939959400594015940259403594045940559406594075940859409594105941159412594135941459415594165941759418594195942059421594225942359424594255942659427594285942959430594315943259433594345943559436594375943859439594405944159442594435944459445594465944759448594495945059451594525945359454594555945659457594585945959460594615946259463594645946559466594675946859469594705947159472594735947459475594765947759478594795948059481594825948359484594855948659487594885948959490594915949259493594945949559496594975949859499595005950159502595035950459505595065950759508595095951059511595125951359514595155951659517595185951959520595215952259523595245952559526595275952859529595305953159532595335953459535595365953759538595395954059541595425954359544595455954659547595485954959550595515955259553595545955559556595575955859559595605956159562595635956459565595665956759568595695957059571595725957359574595755957659577595785957959580595815958259583595845958559586595875958859589595905959159592595935959459595595965959759598595995960059601596025960359604596055960659607596085960959610596115961259613596145961559616596175961859619596205962159622596235962459625596265962759628596295963059631596325963359634596355963659637596385963959640596415964259643596445964559646596475964859649596505965159652596535965459655596565965759658596595966059661596625966359664596655966659667596685966959670596715967259673596745967559676596775967859679596805968159682596835968459685596865968759688596895969059691596925969359694596955969659697596985969959700597015970259703597045970559706597075970859709597105971159712597135971459715597165971759718597195972059721597225972359724597255972659727597285972959730597315973259733597345973559736597375973859739597405974159742597435974459745597465974759748597495975059751597525975359754597555975659757597585975959760597615976259763597645976559766597675976859769597705977159772597735977459775597765977759778597795978059781597825978359784597855978659787597885978959790597915979259793597945979559796597975979859799598005980159802598035980459805598065980759808598095981059811598125981359814598155981659817598185981959820598215982259823598245982559826598275982859829598305983159832598335983459835598365983759838598395984059841598425984359844598455984659847598485984959850598515985259853598545985559856598575985859859598605986159862598635986459865598665986759868598695987059871598725987359874598755987659877598785987959880598815988259883598845988559886598875988859889598905989159892598935989459895598965989759898598995990059901599025990359904599055990659907599085990959910599115991259913599145991559916599175991859919599205992159922599235992459925599265992759928599295993059931599325993359934599355993659937599385993959940599415994259943599445994559946599475994859949599505995159952599535995459955599565995759958599595996059961599625996359964599655996659967599685996959970599715997259973599745997559976599775997859979599805998159982599835998459985599865998759988599895999059991599925999359994599955999659997599985999960000600016000260003600046000560006600076000860009600106001160012600136001460015600166001760018600196002060021600226002360024600256002660027600286002960030600316003260033600346003560036600376003860039600406004160042600436004460045600466004760048600496005060051600526005360054600556005660057600586005960060600616006260063600646006560066600676006860069600706007160072600736007460075600766007760078600796008060081600826008360084600856008660087600886008960090600916009260093600946009560096600976009860099601006010160102601036010460105601066010760108601096011060111601126011360114601156011660117601186011960120601216012260123601246012560126601276012860129601306013160132601336013460135601366013760138601396014060141601426014360144601456014660147601486014960150601516015260153601546015560156601576015860159601606016160162601636016460165601666016760168601696017060171601726017360174601756017660177601786017960180601816018260183601846018560186601876018860189601906019160192601936019460195601966019760198601996020060201602026020360204602056020660207602086020960210602116021260213602146021560216602176021860219602206022160222602236022460225602266022760228602296023060231602326023360234602356023660237602386023960240602416024260243602446024560246602476024860249602506025160252602536025460255602566025760258602596026060261602626026360264602656026660267602686026960270602716027260273602746027560276602776027860279602806028160282602836028460285602866028760288602896029060291602926029360294602956029660297602986029960300603016030260303603046030560306603076030860309603106031160312603136031460315603166031760318603196032060321603226032360324603256032660327603286032960330603316033260333603346033560336603376033860339603406034160342603436034460345603466034760348603496035060351603526035360354603556035660357603586035960360603616036260363603646036560366603676036860369603706037160372603736037460375603766037760378603796038060381603826038360384603856038660387603886038960390603916039260393603946039560396603976039860399604006040160402604036040460405604066040760408604096041060411604126041360414604156041660417604186041960420604216042260423604246042560426604276042860429604306043160432604336043460435604366043760438604396044060441604426044360444604456044660447604486044960450604516045260453604546045560456604576045860459604606046160462604636046460465604666046760468604696047060471604726047360474604756047660477604786047960480604816048260483604846048560486604876048860489604906049160492604936049460495604966049760498604996050060501605026050360504605056050660507605086050960510605116051260513605146051560516605176051860519605206052160522605236052460525605266052760528605296053060531605326053360534605356053660537605386053960540605416054260543605446054560546605476054860549605506055160552605536055460555605566055760558605596056060561605626056360564605656056660567605686056960570605716057260573605746057560576605776057860579605806058160582605836058460585605866058760588605896059060591605926059360594605956059660597605986059960600606016060260603606046060560606606076060860609606106061160612606136061460615606166061760618606196062060621606226062360624606256062660627606286062960630606316063260633606346063560636606376063860639606406064160642606436064460645606466064760648606496065060651606526065360654606556065660657606586065960660606616066260663606646066560666606676066860669606706067160672606736067460675606766067760678606796068060681606826068360684606856068660687606886068960690606916069260693606946069560696606976069860699607006070160702607036070460705607066070760708607096071060711607126071360714607156071660717607186071960720607216072260723607246072560726607276072860729607306073160732607336073460735607366073760738607396074060741607426074360744607456074660747607486074960750607516075260753607546075560756607576075860759607606076160762607636076460765607666076760768607696077060771607726077360774607756077660777607786077960780607816078260783607846078560786607876078860789607906079160792607936079460795607966079760798607996080060801608026080360804608056080660807608086080960810608116081260813608146081560816608176081860819608206082160822608236082460825608266082760828608296083060831608326083360834608356083660837608386083960840608416084260843608446084560846608476084860849608506085160852608536085460855608566085760858608596086060861608626086360864608656086660867608686086960870608716087260873608746087560876608776087860879608806088160882608836088460885608866088760888608896089060891608926089360894608956089660897608986089960900609016090260903609046090560906609076090860909609106091160912609136091460915609166091760918609196092060921609226092360924609256092660927609286092960930609316093260933609346093560936609376093860939609406094160942609436094460945609466094760948609496095060951609526095360954609556095660957609586095960960609616096260963609646096560966609676096860969609706097160972609736097460975609766097760978609796098060981609826098360984609856098660987609886098960990609916099260993609946099560996609976099860999610006100161002610036100461005610066100761008610096101061011610126101361014610156101661017610186101961020610216102261023610246102561026610276102861029610306103161032610336103461035610366103761038610396104061041610426104361044610456104661047610486104961050610516105261053610546105561056610576105861059610606106161062610636106461065610666106761068610696107061071610726107361074610756107661077610786107961080610816108261083610846108561086610876108861089610906109161092610936109461095610966109761098610996110061101611026110361104611056110661107611086110961110611116111261113611146111561116611176111861119611206112161122611236112461125611266112761128611296113061131611326113361134611356113661137611386113961140611416114261143611446114561146611476114861149611506115161152611536115461155611566115761158611596116061161611626116361164611656116661167611686116961170611716117261173611746117561176611776117861179611806118161182611836118461185611866118761188611896119061191611926119361194611956119661197611986119961200612016120261203612046120561206612076120861209612106121161212612136121461215612166121761218612196122061221612226122361224612256122661227612286122961230612316123261233612346123561236612376123861239612406124161242612436124461245612466124761248612496125061251612526125361254612556125661257612586125961260612616126261263612646126561266612676126861269612706127161272612736127461275612766127761278612796128061281612826128361284612856128661287612886128961290612916129261293612946129561296612976129861299613006130161302613036130461305613066130761308613096131061311613126131361314613156131661317613186131961320613216132261323613246132561326613276132861329613306133161332613336133461335613366133761338613396134061341613426134361344613456134661347613486134961350613516135261353613546135561356613576135861359613606136161362613636136461365613666136761368613696137061371613726137361374613756137661377613786137961380613816138261383613846138561386613876138861389613906139161392613936139461395613966139761398613996140061401614026140361404614056140661407614086140961410614116141261413614146141561416614176141861419614206142161422614236142461425614266142761428614296143061431614326143361434614356143661437614386143961440614416144261443614446144561446614476144861449614506145161452614536145461455614566145761458614596146061461614626146361464614656146661467614686146961470614716147261473614746147561476614776147861479614806148161482614836148461485614866148761488614896149061491614926149361494614956149661497614986149961500615016150261503615046150561506615076150861509615106151161512615136151461515615166151761518615196152061521615226152361524615256152661527615286152961530615316153261533615346153561536615376153861539615406154161542615436154461545615466154761548615496155061551615526155361554615556155661557615586155961560615616156261563615646156561566615676156861569615706157161572615736157461575615766157761578615796158061581615826158361584615856158661587615886158961590615916159261593615946159561596615976159861599616006160161602616036160461605616066160761608616096161061611616126161361614616156161661617616186161961620616216162261623616246162561626616276162861629616306163161632616336163461635616366163761638616396164061641616426164361644616456164661647616486164961650616516165261653616546165561656616576165861659616606166161662616636166461665616666166761668616696167061671616726167361674616756167661677616786167961680616816168261683616846168561686616876168861689616906169161692616936169461695616966169761698616996170061701617026170361704617056170661707617086170961710617116171261713617146171561716617176171861719617206172161722617236172461725617266172761728617296173061731617326173361734617356173661737617386173961740617416174261743617446174561746617476174861749617506175161752617536175461755617566175761758617596176061761617626176361764617656176661767617686176961770617716177261773617746177561776617776177861779617806178161782617836178461785617866178761788617896179061791617926179361794617956179661797617986179961800618016180261803618046180561806618076180861809618106181161812618136181461815618166181761818618196182061821618226182361824618256182661827618286182961830618316183261833618346183561836618376183861839618406184161842618436184461845618466184761848618496185061851618526185361854618556185661857618586185961860618616186261863618646186561866618676186861869618706187161872618736187461875618766187761878618796188061881618826188361884618856188661887618886188961890618916189261893618946189561896618976189861899619006190161902619036190461905619066190761908619096191061911619126191361914619156191661917619186191961920619216192261923619246192561926619276192861929619306193161932619336193461935619366193761938619396194061941619426194361944619456194661947619486194961950619516195261953619546195561956619576195861959619606196161962619636196461965619666196761968619696197061971619726197361974619756197661977619786197961980619816198261983619846198561986619876198861989619906199161992619936199461995619966199761998619996200062001620026200362004620056200662007620086200962010620116201262013620146201562016620176201862019620206202162022620236202462025620266202762028620296203062031620326203362034620356203662037620386203962040620416204262043620446204562046620476204862049620506205162052620536205462055620566205762058620596206062061620626206362064620656206662067620686206962070620716207262073620746207562076620776207862079620806208162082620836208462085620866208762088620896209062091620926209362094620956209662097620986209962100621016210262103621046210562106621076210862109621106211162112621136211462115621166211762118621196212062121621226212362124621256212662127621286212962130621316213262133621346213562136621376213862139621406214162142621436214462145621466214762148621496215062151621526215362154621556215662157621586215962160621616216262163621646216562166621676216862169621706217162172621736217462175621766217762178621796218062181621826218362184621856218662187621886218962190621916219262193621946219562196621976219862199622006220162202622036220462205622066220762208622096221062211622126221362214622156221662217622186221962220622216222262223622246222562226622276222862229622306223162232622336223462235622366223762238622396224062241622426224362244622456224662247622486224962250622516225262253622546225562256622576225862259622606226162262622636226462265622666226762268622696227062271622726227362274622756227662277622786227962280622816228262283622846228562286622876228862289622906229162292622936229462295622966229762298622996230062301623026230362304623056230662307623086230962310623116231262313623146231562316623176231862319623206232162322623236232462325623266232762328623296233062331623326233362334623356233662337623386233962340623416234262343623446234562346623476234862349623506235162352623536235462355623566235762358623596236062361623626236362364623656236662367623686236962370623716237262373623746237562376623776237862379623806238162382623836238462385623866238762388623896239062391623926239362394623956239662397623986239962400624016240262403624046240562406624076240862409624106241162412624136241462415624166241762418624196242062421624226242362424624256242662427624286242962430624316243262433624346243562436624376243862439624406244162442624436244462445624466244762448624496245062451624526245362454624556245662457624586245962460624616246262463624646246562466624676246862469624706247162472624736247462475624766247762478624796248062481624826248362484624856248662487624886248962490624916249262493624946249562496624976249862499625006250162502625036250462505625066250762508625096251062511625126251362514625156251662517625186251962520625216252262523625246252562526625276252862529625306253162532625336253462535625366253762538625396254062541625426254362544625456254662547625486254962550625516255262553625546255562556625576255862559625606256162562625636256462565625666256762568625696257062571625726257362574625756257662577625786257962580625816258262583625846258562586625876258862589625906259162592625936259462595625966259762598625996260062601626026260362604626056260662607626086260962610626116261262613626146261562616626176261862619626206262162622626236262462625626266262762628626296263062631626326263362634626356263662637626386263962640626416264262643626446264562646626476264862649626506265162652626536265462655626566265762658626596266062661626626266362664626656266662667626686266962670626716267262673626746267562676626776267862679626806268162682626836268462685626866268762688626896269062691626926269362694626956269662697626986269962700627016270262703627046270562706627076270862709627106271162712627136271462715627166271762718627196272062721627226272362724627256272662727627286272962730627316273262733627346273562736627376273862739627406274162742627436274462745627466274762748627496275062751627526275362754627556275662757627586275962760627616276262763627646276562766627676276862769627706277162772627736277462775627766277762778627796278062781627826278362784627856278662787627886278962790627916279262793627946279562796627976279862799628006280162802628036280462805628066280762808628096281062811628126281362814628156281662817628186281962820628216282262823628246282562826628276282862829628306283162832628336283462835628366283762838628396284062841628426284362844628456284662847628486284962850628516285262853628546285562856628576285862859628606286162862628636286462865628666286762868628696287062871628726287362874628756287662877628786287962880628816288262883628846288562886628876288862889628906289162892628936289462895628966289762898628996290062901629026290362904629056290662907629086290962910629116291262913629146291562916629176291862919629206292162922629236292462925629266292762928629296293062931629326293362934629356293662937629386293962940629416294262943629446294562946629476294862949629506295162952629536295462955629566295762958629596296062961629626296362964629656296662967629686296962970629716297262973629746297562976629776297862979629806298162982629836298462985629866298762988629896299062991629926299362994629956299662997629986299963000630016300263003630046300563006630076300863009630106301163012630136301463015630166301763018630196302063021630226302363024630256302663027630286302963030630316303263033630346303563036630376303863039630406304163042630436304463045630466304763048630496305063051630526305363054630556305663057630586305963060630616306263063630646306563066630676306863069630706307163072630736307463075630766307763078630796308063081630826308363084630856308663087630886308963090630916309263093630946309563096630976309863099631006310163102631036310463105631066310763108631096311063111631126311363114631156311663117631186311963120631216312263123631246312563126631276312863129631306313163132631336313463135631366313763138631396314063141631426314363144631456314663147631486314963150631516315263153631546315563156631576315863159631606316163162631636316463165631666316763168631696317063171631726317363174631756317663177631786317963180631816318263183631846318563186631876318863189631906319163192631936319463195631966319763198631996320063201632026320363204632056320663207632086320963210632116321263213632146321563216632176321863219632206322163222632236322463225632266322763228632296323063231632326323363234632356323663237632386323963240632416324263243632446324563246632476324863249632506325163252632536325463255632566325763258632596326063261632626326363264632656326663267632686326963270632716327263273632746327563276632776327863279632806328163282632836328463285632866328763288632896329063291632926329363294632956329663297632986329963300633016330263303633046330563306633076330863309633106331163312633136331463315633166331763318633196332063321633226332363324633256332663327633286332963330633316333263333633346333563336633376333863339633406334163342633436334463345633466334763348633496335063351633526335363354633556335663357633586335963360633616336263363633646336563366633676336863369633706337163372633736337463375633766337763378633796338063381633826338363384633856338663387633886338963390633916339263393633946339563396633976339863399634006340163402634036340463405634066340763408634096341063411634126341363414634156341663417634186341963420634216342263423634246342563426634276342863429634306343163432634336343463435634366343763438634396344063441634426344363444634456344663447634486344963450634516345263453634546345563456634576345863459634606346163462634636346463465634666346763468634696347063471634726347363474634756347663477634786347963480634816348263483634846348563486634876348863489634906349163492634936349463495634966349763498634996350063501635026350363504635056350663507635086350963510635116351263513635146351563516635176351863519635206352163522635236352463525635266352763528635296353063531635326353363534635356353663537635386353963540635416354263543635446354563546635476354863549635506355163552635536355463555635566355763558635596356063561635626356363564635656356663567635686356963570635716357263573635746357563576635776357863579635806358163582635836358463585635866358763588635896359063591635926359363594635956359663597635986359963600636016360263603636046360563606636076360863609636106361163612636136361463615636166361763618636196362063621636226362363624636256362663627636286362963630636316363263633636346363563636636376363863639636406364163642636436364463645636466364763648636496365063651636526365363654636556365663657636586365963660636616366263663636646366563666636676366863669636706367163672636736367463675636766367763678636796368063681636826368363684636856368663687636886368963690636916369263693636946369563696636976369863699637006370163702637036370463705637066370763708637096371063711637126371363714637156371663717637186371963720637216372263723637246372563726637276372863729637306373163732637336373463735637366373763738637396374063741637426374363744637456374663747637486374963750637516375263753637546375563756637576375863759637606376163762637636376463765637666376763768637696377063771637726377363774637756377663777637786377963780637816378263783637846378563786637876378863789637906379163792637936379463795637966379763798637996380063801638026380363804638056380663807638086380963810638116381263813638146381563816638176381863819638206382163822638236382463825638266382763828638296383063831638326383363834638356383663837638386383963840638416384263843638446384563846638476384863849638506385163852638536385463855638566385763858638596386063861638626386363864638656386663867638686386963870638716387263873638746387563876638776387863879638806388163882638836388463885638866388763888638896389063891638926389363894638956389663897638986389963900639016390263903639046390563906639076390863909639106391163912639136391463915639166391763918639196392063921639226392363924639256392663927639286392963930639316393263933639346393563936639376393863939639406394163942639436394463945639466394763948639496395063951639526395363954639556395663957639586395963960639616396263963639646396563966639676396863969639706397163972639736397463975639766397763978639796398063981639826398363984639856398663987639886398963990639916399263993639946399563996639976399863999640006400164002640036400464005640066400764008640096401064011640126401364014640156401664017640186401964020640216402264023640246402564026640276402864029640306403164032640336403464035640366403764038640396404064041640426404364044640456404664047640486404964050640516405264053640546405564056640576405864059640606406164062640636406464065640666406764068640696407064071640726407364074640756407664077640786407964080640816408264083640846408564086640876408864089640906409164092640936409464095640966409764098640996410064101641026410364104641056410664107641086410964110641116411264113641146411564116641176411864119641206412164122641236412464125641266412764128641296413064131641326413364134641356413664137641386413964140641416414264143641446414564146641476414864149641506415164152641536415464155641566415764158641596416064161641626416364164641656416664167641686416964170641716417264173641746417564176641776417864179641806418164182641836418464185641866418764188641896419064191641926419364194641956419664197641986419964200642016420264203642046420564206642076420864209642106421164212642136421464215642166421764218642196422064221642226422364224642256422664227642286422964230642316423264233642346423564236642376423864239642406424164242642436424464245642466424764248642496425064251642526425364254642556425664257642586425964260642616426264263642646426564266642676426864269642706427164272642736427464275642766427764278642796428064281642826428364284642856428664287642886428964290642916429264293642946429564296642976429864299643006430164302643036430464305643066430764308643096431064311643126431364314643156431664317643186431964320643216432264323643246432564326643276432864329643306433164332643336433464335643366433764338643396434064341643426434364344643456434664347643486434964350643516435264353643546435564356643576435864359643606436164362643636436464365643666436764368643696437064371643726437364374643756437664377643786437964380643816438264383643846438564386643876438864389643906439164392643936439464395643966439764398643996440064401644026440364404644056440664407644086440964410644116441264413644146441564416644176441864419644206442164422644236442464425644266442764428644296443064431644326443364434644356443664437644386443964440644416444264443644446444564446644476444864449644506445164452644536445464455644566445764458644596446064461644626446364464644656446664467644686446964470644716447264473644746447564476644776447864479644806448164482644836448464485644866448764488644896449064491644926449364494644956449664497644986449964500645016450264503645046450564506645076450864509645106451164512645136451464515645166451764518645196452064521645226452364524645256452664527645286452964530645316453264533645346453564536645376453864539645406454164542645436454464545645466454764548645496455064551645526455364554645556455664557645586455964560645616456264563645646456564566645676456864569645706457164572645736457464575645766457764578645796458064581645826458364584645856458664587645886458964590645916459264593645946459564596645976459864599646006460164602646036460464605646066460764608646096461064611646126461364614646156461664617646186461964620646216462264623646246462564626646276462864629646306463164632646336463464635646366463764638646396464064641646426464364644646456464664647646486464964650646516465264653646546465564656646576465864659646606466164662646636466464665646666466764668646696467064671646726467364674646756467664677646786467964680646816468264683646846468564686646876468864689646906469164692646936469464695646966469764698646996470064701647026470364704647056470664707647086470964710647116471264713647146471564716647176471864719647206472164722647236472464725647266472764728647296473064731647326473364734647356473664737647386473964740647416474264743647446474564746647476474864749647506475164752647536475464755647566475764758647596476064761647626476364764647656476664767647686476964770647716477264773647746477564776647776477864779647806478164782647836478464785647866478764788647896479064791647926479364794647956479664797647986479964800648016480264803648046480564806648076480864809648106481164812648136481464815648166481764818648196482064821648226482364824648256482664827648286482964830648316483264833648346483564836648376483864839648406484164842648436484464845648466484764848648496485064851648526485364854648556485664857648586485964860648616486264863648646486564866648676486864869648706487164872648736487464875648766487764878648796488064881648826488364884648856488664887648886488964890648916489264893648946489564896648976489864899649006490164902649036490464905649066490764908649096491064911649126491364914649156491664917649186491964920649216492264923649246492564926649276492864929649306493164932649336493464935649366493764938649396494064941649426494364944649456494664947649486494964950649516495264953649546495564956649576495864959649606496164962649636496464965649666496764968649696497064971649726497364974649756497664977649786497964980649816498264983649846498564986649876498864989649906499164992649936499464995649966499764998649996500065001650026500365004650056500665007650086500965010650116501265013650146501565016650176501865019650206502165022650236502465025650266502765028650296503065031650326503365034650356503665037650386503965040650416504265043650446504565046650476504865049650506505165052650536505465055650566505765058650596506065061650626506365064650656506665067650686506965070650716507265073650746507565076650776507865079650806508165082650836508465085650866508765088650896509065091650926509365094650956509665097650986509965100651016510265103651046510565106651076510865109651106511165112651136511465115651166511765118651196512065121651226512365124651256512665127651286512965130651316513265133651346513565136651376513865139651406514165142651436514465145651466514765148651496515065151651526515365154651556515665157651586515965160651616516265163651646516565166651676516865169651706517165172651736517465175651766517765178651796518065181651826518365184651856518665187651886518965190651916519265193651946519565196651976519865199652006520165202652036520465205652066520765208652096521065211652126521365214652156521665217652186521965220652216522265223652246522565226652276522865229652306523165232652336523465235652366523765238652396524065241652426524365244652456524665247652486524965250652516525265253652546525565256652576525865259652606526165262652636526465265652666526765268652696527065271652726527365274652756527665277652786527965280652816528265283652846528565286652876528865289652906529165292652936529465295652966529765298652996530065301653026530365304653056530665307653086530965310653116531265313653146531565316653176531865319653206532165322653236532465325653266532765328653296533065331653326533365334653356533665337653386533965340653416534265343653446534565346653476534865349653506535165352653536535465355653566535765358653596536065361653626536365364653656536665367653686536965370653716537265373653746537565376653776537865379653806538165382653836538465385653866538765388653896539065391653926539365394653956539665397653986539965400654016540265403654046540565406654076540865409654106541165412654136541465415654166541765418654196542065421654226542365424654256542665427654286542965430654316543265433654346543565436654376543865439654406544165442654436544465445654466544765448654496545065451654526545365454654556545665457654586545965460654616546265463654646546565466654676546865469654706547165472654736547465475654766547765478654796548065481654826548365484654856548665487654886548965490654916549265493654946549565496654976549865499655006550165502655036550465505655066550765508655096551065511655126551365514655156551665517655186551965520655216552265523655246552565526655276552865529655306553165532655336553465535655366553765538655396554065541655426554365544655456554665547655486554965550655516555265553655546555565556655576555865559655606556165562655636556465565655666556765568655696557065571655726557365574655756557665577655786557965580655816558265583655846558565586655876558865589655906559165592655936559465595655966559765598655996560065601656026560365604656056560665607656086560965610656116561265613656146561565616656176561865619656206562165622656236562465625656266562765628656296563065631656326563365634656356563665637656386563965640656416564265643656446564565646656476564865649656506565165652656536565465655656566565765658656596566065661656626566365664656656566665667656686566965670656716567265673656746567565676656776567865679656806568165682656836568465685656866568765688656896569065691656926569365694656956569665697656986569965700657016570265703657046570565706657076570865709657106571165712657136571465715657166571765718657196572065721657226572365724657256572665727657286572965730657316573265733657346573565736657376573865739657406574165742657436574465745657466574765748657496575065751657526575365754657556575665757657586575965760657616576265763657646576565766657676576865769657706577165772657736577465775657766577765778657796578065781657826578365784657856578665787657886578965790657916579265793657946579565796657976579865799658006580165802658036580465805658066580765808658096581065811658126581365814658156581665817658186581965820658216582265823658246582565826658276582865829658306583165832658336583465835658366583765838658396584065841658426584365844658456584665847658486584965850658516585265853658546585565856658576585865859658606586165862658636586465865658666586765868658696587065871658726587365874658756587665877658786587965880658816588265883658846588565886658876588865889658906589165892658936589465895658966589765898658996590065901659026590365904659056590665907659086590965910659116591265913659146591565916659176591865919659206592165922659236592465925659266592765928659296593065931659326593365934659356593665937659386593965940659416594265943659446594565946659476594865949659506595165952659536595465955659566595765958659596596065961659626596365964659656596665967659686596965970659716597265973659746597565976659776597865979659806598165982659836598465985659866598765988659896599065991659926599365994659956599665997659986599966000660016600266003660046600566006660076600866009660106601166012660136601466015660166601766018660196602066021660226602366024660256602666027660286602966030660316603266033660346603566036660376603866039660406604166042660436604466045660466604766048660496605066051660526605366054660556605666057660586605966060660616606266063660646606566066660676606866069660706607166072660736607466075660766607766078660796608066081660826608366084660856608666087660886608966090660916609266093660946609566096660976609866099661006610166102661036610466105661066610766108661096611066111661126611366114661156611666117661186611966120661216612266123661246612566126661276612866129661306613166132661336613466135661366613766138661396614066141661426614366144661456614666147661486614966150661516615266153661546615566156661576615866159661606616166162661636616466165661666616766168661696617066171661726617366174661756617666177661786617966180661816618266183661846618566186661876618866189661906619166192661936619466195661966619766198661996620066201662026620366204662056620666207662086620966210662116621266213662146621566216662176621866219662206622166222662236622466225662266622766228662296623066231662326623366234662356623666237662386623966240662416624266243662446624566246662476624866249662506625166252662536625466255662566625766258662596626066261662626626366264662656626666267662686626966270662716627266273662746627566276662776627866279662806628166282662836628466285662866628766288662896629066291662926629366294662956629666297662986629966300663016630266303663046630566306663076630866309663106631166312663136631466315663166631766318663196632066321663226632366324663256632666327663286632966330663316633266333663346633566336663376633866339663406634166342663436634466345663466634766348663496635066351663526635366354663556635666357663586635966360663616636266363663646636566366663676636866369663706637166372663736637466375663766637766378663796638066381663826638366384663856638666387663886638966390663916639266393663946639566396663976639866399664006640166402664036640466405664066640766408664096641066411664126641366414664156641666417664186641966420664216642266423664246642566426664276642866429664306643166432664336643466435664366643766438664396644066441664426644366444664456644666447664486644966450664516645266453664546645566456664576645866459664606646166462664636646466465664666646766468664696647066471664726647366474664756647666477664786647966480664816648266483664846648566486664876648866489664906649166492664936649466495664966649766498664996650066501665026650366504665056650666507665086650966510665116651266513665146651566516665176651866519665206652166522665236652466525665266652766528665296653066531665326653366534665356653666537665386653966540665416654266543665446654566546665476654866549665506655166552665536655466555665566655766558665596656066561665626656366564665656656666567665686656966570665716657266573665746657566576665776657866579665806658166582665836658466585665866658766588665896659066591665926659366594665956659666597665986659966600666016660266603666046660566606666076660866609666106661166612666136661466615666166661766618666196662066621666226662366624666256662666627666286662966630666316663266633666346663566636666376663866639666406664166642666436664466645666466664766648666496665066651666526665366654666556665666657666586665966660666616666266663666646666566666666676666866669666706667166672666736667466675666766667766678666796668066681666826668366684666856668666687666886668966690666916669266693666946669566696666976669866699667006670166702667036670466705667066670766708667096671066711667126671366714667156671666717667186671966720667216672266723667246672566726667276672866729667306673166732667336673466735667366673766738667396674066741667426674366744667456674666747667486674966750667516675266753667546675566756667576675866759667606676166762667636676466765667666676766768667696677066771667726677366774667756677666777667786677966780667816678266783667846678566786667876678866789667906679166792667936679466795667966679766798667996680066801668026680366804668056680666807668086680966810668116681266813668146681566816668176681866819668206682166822668236682466825668266682766828668296683066831668326683366834668356683666837668386683966840668416684266843668446684566846668476684866849668506685166852668536685466855668566685766858668596686066861668626686366864668656686666867668686686966870668716687266873668746687566876668776687866879668806688166882668836688466885668866688766888668896689066891668926689366894668956689666897668986689966900669016690266903669046690566906669076690866909669106691166912669136691466915669166691766918669196692066921669226692366924669256692666927669286692966930669316693266933669346693566936669376693866939669406694166942669436694466945669466694766948669496695066951669526695366954669556695666957669586695966960669616696266963669646696566966669676696866969669706697166972669736697466975669766697766978669796698066981669826698366984669856698666987669886698966990669916699266993669946699566996669976699866999670006700167002670036700467005670066700767008670096701067011670126701367014670156701667017670186701967020670216702267023670246702567026670276702867029670306703167032670336703467035670366703767038670396704067041670426704367044670456704667047670486704967050670516705267053670546705567056670576705867059670606706167062670636706467065670666706767068670696707067071670726707367074670756707667077670786707967080670816708267083670846708567086670876708867089670906709167092670936709467095670966709767098670996710067101671026710367104671056710667107671086710967110671116711267113671146711567116671176711867119671206712167122671236712467125671266712767128671296713067131671326713367134671356713667137671386713967140671416714267143671446714567146671476714867149671506715167152671536715467155671566715767158671596716067161671626716367164671656716667167671686716967170671716717267173671746717567176671776717867179671806718167182671836718467185671866718767188671896719067191671926719367194671956719667197671986719967200672016720267203672046720567206672076720867209672106721167212672136721467215672166721767218672196722067221672226722367224672256722667227672286722967230672316723267233672346723567236672376723867239672406724167242672436724467245672466724767248672496725067251672526725367254672556725667257672586725967260672616726267263672646726567266672676726867269672706727167272672736727467275672766727767278672796728067281672826728367284672856728667287672886728967290672916729267293672946729567296672976729867299673006730167302673036730467305673066730767308673096731067311673126731367314673156731667317673186731967320673216732267323673246732567326673276732867329673306733167332673336733467335673366733767338673396734067341673426734367344673456734667347673486734967350673516735267353673546735567356673576735867359673606736167362673636736467365673666736767368673696737067371673726737367374673756737667377673786737967380673816738267383673846738567386673876738867389673906739167392673936739467395673966739767398673996740067401674026740367404674056740667407674086740967410674116741267413674146741567416674176741867419674206742167422674236742467425674266742767428674296743067431674326743367434674356743667437674386743967440674416744267443674446744567446674476744867449674506745167452674536745467455674566745767458674596746067461674626746367464674656746667467674686746967470674716747267473674746747567476674776747867479674806748167482674836748467485674866748767488674896749067491674926749367494674956749667497674986749967500675016750267503675046750567506675076750867509675106751167512675136751467515675166751767518675196752067521675226752367524675256752667527675286752967530675316753267533675346753567536675376753867539675406754167542675436754467545675466754767548675496755067551675526755367554675556755667557675586755967560675616756267563675646756567566675676756867569675706757167572675736757467575675766757767578675796758067581675826758367584675856758667587675886758967590675916759267593675946759567596675976759867599676006760167602676036760467605676066760767608676096761067611676126761367614676156761667617676186761967620676216762267623676246762567626676276762867629676306763167632676336763467635676366763767638676396764067641676426764367644676456764667647676486764967650676516765267653676546765567656676576765867659676606766167662676636766467665676666766767668676696767067671676726767367674676756767667677676786767967680676816768267683676846768567686676876768867689676906769167692676936769467695676966769767698676996770067701677026770367704677056770667707677086770967710677116771267713677146771567716677176771867719677206772167722677236772467725677266772767728677296773067731677326773367734677356773667737677386773967740677416774267743677446774567746677476774867749677506775167752677536775467755677566775767758677596776067761677626776367764677656776667767677686776967770677716777267773677746777567776677776777867779677806778167782677836778467785677866778767788677896779067791677926779367794677956779667797677986779967800678016780267803678046780567806678076780867809678106781167812678136781467815678166781767818678196782067821678226782367824678256782667827678286782967830678316783267833678346783567836678376783867839678406784167842678436784467845678466784767848678496785067851678526785367854678556785667857678586785967860678616786267863678646786567866678676786867869678706787167872678736787467875678766787767878678796788067881678826788367884678856788667887678886788967890678916789267893678946789567896678976789867899679006790167902679036790467905679066790767908679096791067911679126791367914679156791667917679186791967920679216792267923679246792567926679276792867929679306793167932679336793467935679366793767938679396794067941679426794367944679456794667947679486794967950679516795267953679546795567956679576795867959679606796167962679636796467965679666796767968679696797067971679726797367974679756797667977679786797967980679816798267983679846798567986679876798867989679906799167992679936799467995679966799767998679996800068001680026800368004680056800668007680086800968010680116801268013680146801568016680176801868019680206802168022680236802468025680266802768028680296803068031680326803368034680356803668037680386803968040680416804268043680446804568046680476804868049680506805168052680536805468055680566805768058680596806068061680626806368064680656806668067680686806968070680716807268073680746807568076680776807868079680806808168082680836808468085680866808768088680896809068091680926809368094680956809668097680986809968100681016810268103681046810568106681076810868109681106811168112681136811468115681166811768118681196812068121681226812368124681256812668127681286812968130681316813268133681346813568136681376813868139681406814168142681436814468145681466814768148681496815068151681526815368154681556815668157681586815968160681616816268163681646816568166681676816868169681706817168172681736817468175681766817768178681796818068181681826818368184681856818668187681886818968190681916819268193681946819568196681976819868199682006820168202682036820468205682066820768208682096821068211682126821368214682156821668217682186821968220682216822268223682246822568226682276822868229682306823168232682336823468235682366823768238682396824068241682426824368244682456824668247682486824968250682516825268253682546825568256682576825868259682606826168262682636826468265682666826768268682696827068271682726827368274682756827668277682786827968280682816828268283682846828568286682876828868289682906829168292682936829468295682966829768298682996830068301683026830368304683056830668307683086830968310683116831268313683146831568316683176831868319683206832168322683236832468325683266832768328683296833068331683326833368334683356833668337683386833968340683416834268343683446834568346683476834868349683506835168352683536835468355683566835768358683596836068361683626836368364683656836668367683686836968370683716837268373683746837568376683776837868379683806838168382683836838468385683866838768388683896839068391683926839368394683956839668397683986839968400684016840268403684046840568406684076840868409684106841168412684136841468415684166841768418684196842068421684226842368424684256842668427684286842968430684316843268433684346843568436684376843868439684406844168442684436844468445684466844768448684496845068451684526845368454684556845668457684586845968460684616846268463684646846568466684676846868469684706847168472684736847468475684766847768478684796848068481684826848368484684856848668487684886848968490684916849268493684946849568496684976849868499685006850168502685036850468505685066850768508685096851068511685126851368514685156851668517685186851968520685216852268523685246852568526685276852868529685306853168532685336853468535685366853768538685396854068541685426854368544685456854668547685486854968550685516855268553685546855568556685576855868559685606856168562685636856468565685666856768568685696857068571685726857368574685756857668577685786857968580685816858268583685846858568586685876858868589685906859168592685936859468595685966859768598685996860068601686026860368604686056860668607686086860968610686116861268613686146861568616686176861868619686206862168622686236862468625686266862768628686296863068631686326863368634686356863668637686386863968640686416864268643686446864568646686476864868649686506865168652686536865468655686566865768658686596866068661686626866368664686656866668667686686866968670686716867268673686746867568676686776867868679686806868168682686836868468685686866868768688686896869068691686926869368694686956869668697686986869968700687016870268703687046870568706687076870868709687106871168712687136871468715687166871768718687196872068721687226872368724687256872668727687286872968730687316873268733687346873568736687376873868739687406874168742687436874468745687466874768748687496875068751687526875368754687556875668757687586875968760687616876268763687646876568766687676876868769687706877168772687736877468775687766877768778687796878068781687826878368784687856878668787687886878968790687916879268793687946879568796687976879868799688006880168802688036880468805688066880768808688096881068811688126881368814688156881668817688186881968820688216882268823688246882568826688276882868829688306883168832688336883468835688366883768838688396884068841688426884368844688456884668847688486884968850688516885268853688546885568856688576885868859688606886168862688636886468865688666886768868688696887068871688726887368874688756887668877688786887968880688816888268883688846888568886688876888868889688906889168892688936889468895688966889768898688996890068901689026890368904689056890668907689086890968910689116891268913689146891568916689176891868919689206892168922689236892468925689266892768928689296893068931689326893368934689356893668937689386893968940689416894268943689446894568946689476894868949689506895168952689536895468955689566895768958689596896068961689626896368964689656896668967689686896968970689716897268973689746897568976689776897868979689806898168982689836898468985689866898768988689896899068991689926899368994689956899668997689986899969000690016900269003690046900569006690076900869009690106901169012690136901469015690166901769018690196902069021690226902369024690256902669027690286902969030690316903269033690346903569036690376903869039690406904169042690436904469045690466904769048690496905069051690526905369054690556905669057690586905969060690616906269063690646906569066690676906869069690706907169072690736907469075690766907769078690796908069081690826908369084690856908669087690886908969090690916909269093690946909569096690976909869099691006910169102691036910469105691066910769108691096911069111691126911369114691156911669117691186911969120691216912269123691246912569126691276912869129691306913169132691336913469135691366913769138691396914069141691426914369144691456914669147691486914969150691516915269153691546915569156691576915869159691606916169162691636916469165691666916769168691696917069171691726917369174691756917669177691786917969180691816918269183691846918569186691876918869189691906919169192691936919469195691966919769198691996920069201692026920369204692056920669207692086920969210692116921269213692146921569216692176921869219692206922169222692236922469225692266922769228692296923069231692326923369234692356923669237692386923969240692416924269243692446924569246692476924869249692506925169252692536925469255692566925769258692596926069261692626926369264692656926669267692686926969270692716927269273692746927569276692776927869279692806928169282692836928469285692866928769288692896929069291692926929369294692956929669297692986929969300693016930269303693046930569306693076930869309693106931169312693136931469315693166931769318693196932069321693226932369324693256932669327693286932969330693316933269333693346933569336693376933869339693406934169342693436934469345693466934769348693496935069351693526935369354693556935669357693586935969360693616936269363693646936569366693676936869369693706937169372693736937469375693766937769378693796938069381693826938369384693856938669387693886938969390693916939269393693946939569396693976939869399694006940169402694036940469405694066940769408694096941069411694126941369414694156941669417694186941969420694216942269423694246942569426694276942869429694306943169432694336943469435694366943769438694396944069441694426944369444694456944669447694486944969450694516945269453694546945569456694576945869459694606946169462694636946469465694666946769468694696947069471694726947369474694756947669477694786947969480694816948269483694846948569486694876948869489694906949169492694936949469495694966949769498694996950069501695026950369504695056950669507695086950969510695116951269513695146951569516695176951869519695206952169522695236952469525695266952769528695296953069531695326953369534695356953669537695386953969540695416954269543695446954569546695476954869549695506955169552695536955469555695566955769558695596956069561695626956369564695656956669567695686956969570695716957269573695746957569576695776957869579695806958169582695836958469585695866958769588695896959069591695926959369594695956959669597695986959969600696016960269603696046960569606696076960869609696106961169612696136961469615696166961769618696196962069621696226962369624696256962669627696286962969630696316963269633696346963569636696376963869639696406964169642696436964469645696466964769648696496965069651696526965369654696556965669657696586965969660696616966269663696646966569666696676966869669696706967169672696736967469675696766967769678696796968069681696826968369684696856968669687696886968969690696916969269693696946969569696696976969869699697006970169702697036970469705697066970769708697096971069711697126971369714697156971669717697186971969720697216972269723697246972569726697276972869729697306973169732697336973469735697366973769738697396974069741697426974369744697456974669747697486974969750697516975269753697546975569756697576975869759697606976169762697636976469765697666976769768697696977069771697726977369774697756977669777697786977969780697816978269783697846978569786697876978869789697906979169792697936979469795697966979769798697996980069801698026980369804698056980669807698086980969810698116981269813698146981569816698176981869819698206982169822698236982469825698266982769828698296983069831698326983369834698356983669837698386983969840698416984269843698446984569846698476984869849698506985169852698536985469855698566985769858698596986069861698626986369864698656986669867698686986969870698716987269873698746987569876698776987869879698806988169882698836988469885698866988769888698896989069891698926989369894698956989669897698986989969900699016990269903699046990569906699076990869909699106991169912699136991469915699166991769918699196992069921699226992369924699256992669927699286992969930699316993269933699346993569936699376993869939699406994169942699436994469945699466994769948699496995069951699526995369954699556995669957699586995969960699616996269963699646996569966699676996869969699706997169972699736997469975699766997769978699796998069981699826998369984699856998669987699886998969990699916999269993699946999569996699976999869999700007000170002700037000470005700067000770008700097001070011700127001370014700157001670017700187001970020700217002270023700247002570026700277002870029700307003170032700337003470035700367003770038700397004070041700427004370044700457004670047700487004970050700517005270053700547005570056700577005870059700607006170062700637006470065700667006770068700697007070071700727007370074700757007670077700787007970080700817008270083700847008570086700877008870089700907009170092700937009470095700967009770098700997010070101701027010370104701057010670107701087010970110701117011270113701147011570116701177011870119701207012170122701237012470125701267012770128701297013070131701327013370134701357013670137701387013970140701417014270143701447014570146701477014870149701507015170152701537015470155701567015770158701597016070161701627016370164701657016670167701687016970170701717017270173701747017570176701777017870179701807018170182701837018470185701867018770188701897019070191701927019370194701957019670197701987019970200702017020270203702047020570206702077020870209702107021170212702137021470215702167021770218702197022070221702227022370224702257022670227702287022970230702317023270233702347023570236702377023870239702407024170242702437024470245702467024770248702497025070251702527025370254702557025670257702587025970260702617026270263702647026570266702677026870269702707027170272702737027470275702767027770278702797028070281702827028370284702857028670287702887028970290702917029270293702947029570296702977029870299703007030170302703037030470305703067030770308703097031070311703127031370314703157031670317703187031970320703217032270323703247032570326703277032870329703307033170332703337033470335703367033770338703397034070341703427034370344703457034670347703487034970350703517035270353703547035570356703577035870359703607036170362703637036470365703667036770368703697037070371703727037370374703757037670377703787037970380703817038270383703847038570386703877038870389703907039170392703937039470395703967039770398703997040070401704027040370404704057040670407704087040970410704117041270413704147041570416704177041870419704207042170422704237042470425704267042770428704297043070431704327043370434704357043670437704387043970440704417044270443704447044570446704477044870449704507045170452704537045470455704567045770458704597046070461704627046370464704657046670467704687046970470704717047270473704747047570476704777047870479704807048170482704837048470485704867048770488704897049070491704927049370494704957049670497704987049970500705017050270503705047050570506705077050870509705107051170512705137051470515705167051770518705197052070521705227052370524705257052670527705287052970530705317053270533705347053570536705377053870539705407054170542705437054470545705467054770548705497055070551705527055370554705557055670557705587055970560705617056270563705647056570566705677056870569705707057170572705737057470575705767057770578705797058070581705827058370584705857058670587705887058970590705917059270593705947059570596705977059870599706007060170602706037060470605706067060770608706097061070611706127061370614706157061670617706187061970620706217062270623706247062570626706277062870629706307063170632706337063470635706367063770638706397064070641706427064370644706457064670647706487064970650706517065270653706547065570656706577065870659706607066170662706637066470665706667066770668706697067070671706727067370674706757067670677706787067970680706817068270683706847068570686706877068870689706907069170692706937069470695706967069770698706997070070701707027070370704707057070670707707087070970710707117071270713707147071570716707177071870719707207072170722707237072470725707267072770728707297073070731707327073370734707357073670737707387073970740707417074270743707447074570746707477074870749707507075170752707537075470755707567075770758707597076070761707627076370764707657076670767707687076970770707717077270773707747077570776707777077870779707807078170782707837078470785707867078770788707897079070791707927079370794707957079670797707987079970800708017080270803708047080570806708077080870809708107081170812708137081470815708167081770818708197082070821708227082370824708257082670827708287082970830708317083270833708347083570836708377083870839708407084170842708437084470845708467084770848708497085070851708527085370854708557085670857708587085970860708617086270863708647086570866708677086870869708707087170872708737087470875708767087770878708797088070881708827088370884708857088670887708887088970890708917089270893708947089570896708977089870899709007090170902709037090470905709067090770908709097091070911709127091370914709157091670917709187091970920709217092270923709247092570926709277092870929709307093170932709337093470935709367093770938709397094070941709427094370944709457094670947709487094970950709517095270953709547095570956709577095870959709607096170962709637096470965709667096770968709697097070971709727097370974709757097670977709787097970980709817098270983709847098570986709877098870989709907099170992709937099470995709967099770998709997100071001710027100371004710057100671007710087100971010710117101271013710147101571016710177101871019710207102171022710237102471025710267102771028710297103071031710327103371034710357103671037710387103971040710417104271043710447104571046710477104871049710507105171052710537105471055710567105771058710597106071061710627106371064710657106671067710687106971070710717107271073710747107571076710777107871079710807108171082710837108471085710867108771088710897109071091710927109371094710957109671097710987109971100711017110271103711047110571106711077110871109711107111171112711137111471115711167111771118711197112071121711227112371124711257112671127711287112971130711317113271133711347113571136711377113871139711407114171142711437114471145711467114771148711497115071151711527115371154711557115671157711587115971160711617116271163711647116571166711677116871169711707117171172711737117471175711767117771178711797118071181711827118371184711857118671187711887118971190711917119271193711947119571196711977119871199712007120171202712037120471205712067120771208712097121071211712127121371214712157121671217712187121971220712217122271223712247122571226712277122871229712307123171232712337123471235712367123771238712397124071241712427124371244712457124671247712487124971250712517125271253712547125571256712577125871259712607126171262712637126471265712667126771268712697127071271712727127371274712757127671277712787127971280712817128271283712847128571286712877128871289712907129171292712937129471295712967129771298712997130071301713027130371304713057130671307713087130971310713117131271313713147131571316713177131871319713207132171322713237132471325713267132771328713297133071331713327133371334713357133671337713387133971340713417134271343713447134571346713477134871349713507135171352713537135471355713567135771358713597136071361713627136371364713657136671367713687136971370713717137271373713747137571376713777137871379713807138171382713837138471385713867138771388713897139071391713927139371394713957139671397713987139971400714017140271403714047140571406714077140871409714107141171412714137141471415714167141771418714197142071421714227142371424714257142671427714287142971430714317143271433714347143571436714377143871439714407144171442714437144471445714467144771448714497145071451714527145371454714557145671457714587145971460714617146271463714647146571466714677146871469714707147171472714737147471475714767147771478714797148071481714827148371484714857148671487714887148971490714917149271493714947149571496714977149871499715007150171502715037150471505715067150771508715097151071511715127151371514715157151671517715187151971520715217152271523715247152571526715277152871529715307153171532715337153471535715367153771538715397154071541715427154371544715457154671547715487154971550715517155271553715547155571556715577155871559715607156171562715637156471565715667156771568715697157071571715727157371574715757157671577715787157971580715817158271583715847158571586715877158871589715907159171592715937159471595715967159771598715997160071601716027160371604716057160671607716087160971610716117161271613716147161571616716177161871619716207162171622716237162471625716267162771628716297163071631716327163371634716357163671637716387163971640716417164271643716447164571646716477164871649716507165171652716537165471655716567165771658716597166071661716627166371664716657166671667716687166971670716717167271673716747167571676716777167871679716807168171682716837168471685716867168771688716897169071691716927169371694716957169671697716987169971700717017170271703717047170571706717077170871709717107171171712717137171471715717167171771718717197172071721717227172371724717257172671727717287172971730717317173271733717347173571736717377173871739717407174171742717437174471745717467174771748717497175071751717527175371754717557175671757717587175971760717617176271763717647176571766717677176871769717707177171772717737177471775717767177771778717797178071781717827178371784717857178671787717887178971790717917179271793717947179571796717977179871799718007180171802718037180471805718067180771808718097181071811718127181371814718157181671817718187181971820718217182271823718247182571826718277182871829718307183171832718337183471835718367183771838718397184071841718427184371844718457184671847718487184971850718517185271853718547185571856718577185871859718607186171862718637186471865718667186771868718697187071871718727187371874718757187671877718787187971880718817188271883718847188571886718877188871889718907189171892718937189471895718967189771898718997190071901719027190371904719057190671907719087190971910719117191271913719147191571916719177191871919719207192171922719237192471925719267192771928719297193071931719327193371934719357193671937719387193971940719417194271943719447194571946719477194871949719507195171952719537195471955719567195771958719597196071961719627196371964719657196671967719687196971970719717197271973719747197571976719777197871979719807198171982719837198471985719867198771988719897199071991719927199371994719957199671997719987199972000720017200272003720047200572006720077200872009720107201172012720137201472015720167201772018720197202072021720227202372024720257202672027720287202972030720317203272033720347203572036720377203872039720407204172042720437204472045720467204772048720497205072051720527205372054720557205672057720587205972060720617206272063720647206572066720677206872069720707207172072720737207472075720767207772078720797208072081720827208372084720857208672087720887208972090720917209272093720947209572096720977209872099721007210172102721037210472105721067210772108721097211072111721127211372114721157211672117721187211972120721217212272123721247212572126721277212872129721307213172132721337213472135721367213772138721397214072141721427214372144721457214672147721487214972150721517215272153721547215572156721577215872159721607216172162721637216472165721667216772168721697217072171721727217372174721757217672177721787217972180721817218272183721847218572186721877218872189721907219172192721937219472195721967219772198721997220072201722027220372204722057220672207722087220972210722117221272213722147221572216722177221872219722207222172222722237222472225722267222772228722297223072231722327223372234722357223672237722387223972240722417224272243722447224572246722477224872249722507225172252722537225472255722567225772258722597226072261722627226372264722657226672267722687226972270722717227272273722747227572276722777227872279722807228172282722837228472285722867228772288722897229072291722927229372294722957229672297722987229972300723017230272303723047230572306723077230872309723107231172312723137231472315723167231772318723197232072321723227232372324723257232672327723287232972330723317233272333723347233572336723377233872339723407234172342723437234472345723467234772348723497235072351723527235372354723557235672357723587235972360723617236272363723647236572366723677236872369723707237172372723737237472375723767237772378723797238072381723827238372384723857238672387723887238972390723917239272393723947239572396723977239872399724007240172402724037240472405724067240772408724097241072411724127241372414724157241672417724187241972420724217242272423724247242572426724277242872429724307243172432724337243472435724367243772438724397244072441724427244372444724457244672447724487244972450724517245272453724547245572456724577245872459724607246172462724637246472465724667246772468724697247072471724727247372474724757247672477724787247972480724817248272483724847248572486724877248872489724907249172492724937249472495724967249772498724997250072501725027250372504725057250672507725087250972510725117251272513725147251572516725177251872519725207252172522725237252472525725267252772528725297253072531725327253372534725357253672537725387253972540725417254272543725447254572546725477254872549725507255172552725537255472555725567255772558725597256072561725627256372564725657256672567725687256972570725717257272573725747257572576725777257872579725807258172582725837258472585725867258772588725897259072591725927259372594725957259672597725987259972600726017260272603726047260572606726077260872609726107261172612726137261472615726167261772618726197262072621726227262372624726257262672627726287262972630726317263272633726347263572636726377263872639726407264172642726437264472645726467264772648726497265072651726527265372654726557265672657726587265972660726617266272663726647266572666726677266872669726707267172672726737267472675726767267772678726797268072681726827268372684726857268672687726887268972690726917269272693726947269572696726977269872699727007270172702727037270472705727067270772708727097271072711727127271372714727157271672717727187271972720727217272272723727247272572726727277272872729727307273172732727337273472735727367273772738727397274072741727427274372744727457274672747727487274972750727517275272753727547275572756727577275872759727607276172762727637276472765727667276772768727697277072771727727277372774727757277672777727787277972780727817278272783727847278572786727877278872789727907279172792727937279472795727967279772798727997280072801728027280372804728057280672807728087280972810728117281272813728147281572816728177281872819728207282172822728237282472825728267282772828728297283072831728327283372834728357283672837728387283972840728417284272843728447284572846728477284872849728507285172852728537285472855728567285772858728597286072861728627286372864728657286672867728687286972870728717287272873728747287572876728777287872879728807288172882728837288472885728867288772888728897289072891728927289372894728957289672897728987289972900729017290272903729047290572906729077290872909729107291172912729137291472915729167291772918729197292072921729227292372924729257292672927729287292972930729317293272933729347293572936729377293872939729407294172942729437294472945729467294772948729497295072951729527295372954729557295672957729587295972960729617296272963729647296572966729677296872969729707297172972729737297472975729767297772978729797298072981729827298372984729857298672987729887298972990729917299272993729947299572996729977299872999730007300173002730037300473005730067300773008730097301073011730127301373014730157301673017730187301973020730217302273023730247302573026730277302873029730307303173032730337303473035730367303773038730397304073041730427304373044730457304673047730487304973050730517305273053730547305573056730577305873059730607306173062730637306473065730667306773068730697307073071730727307373074730757307673077730787307973080730817308273083730847308573086730877308873089730907309173092730937309473095730967309773098730997310073101731027310373104731057310673107731087310973110731117311273113731147311573116731177311873119731207312173122731237312473125731267312773128731297313073131731327313373134731357313673137731387313973140731417314273143731447314573146731477314873149731507315173152731537315473155731567315773158731597316073161731627316373164731657316673167731687316973170731717317273173731747317573176731777317873179731807318173182731837318473185731867318773188731897319073191731927319373194731957319673197731987319973200732017320273203732047320573206732077320873209732107321173212732137321473215732167321773218732197322073221732227322373224732257322673227732287322973230732317323273233732347323573236732377323873239732407324173242732437324473245732467324773248732497325073251732527325373254732557325673257732587325973260732617326273263732647326573266732677326873269732707327173272732737327473275732767327773278732797328073281732827328373284732857328673287732887328973290732917329273293732947329573296732977329873299733007330173302733037330473305733067330773308733097331073311733127331373314733157331673317733187331973320733217332273323733247332573326733277332873329733307333173332733337333473335733367333773338733397334073341733427334373344733457334673347733487334973350733517335273353733547335573356733577335873359733607336173362733637336473365733667336773368733697337073371733727337373374733757337673377733787337973380733817338273383733847338573386733877338873389733907339173392733937339473395733967339773398733997340073401734027340373404734057340673407734087340973410734117341273413734147341573416734177341873419734207342173422734237342473425734267342773428734297343073431734327343373434734357343673437734387343973440734417344273443734447344573446734477344873449734507345173452734537345473455734567345773458734597346073461734627346373464734657346673467734687346973470734717347273473734747347573476734777347873479734807348173482734837348473485734867348773488734897349073491734927349373494734957349673497734987349973500735017350273503735047350573506735077350873509735107351173512735137351473515735167351773518735197352073521735227352373524735257352673527735287352973530735317353273533735347353573536735377353873539735407354173542735437354473545735467354773548735497355073551735527355373554735557355673557735587355973560735617356273563735647356573566735677356873569735707357173572735737357473575735767357773578735797358073581735827358373584735857358673587735887358973590735917359273593735947359573596735977359873599736007360173602736037360473605736067360773608736097361073611736127361373614736157361673617736187361973620736217362273623736247362573626736277362873629736307363173632736337363473635736367363773638736397364073641736427364373644736457364673647736487364973650736517365273653736547365573656736577365873659736607366173662736637366473665736667366773668736697367073671736727367373674736757367673677736787367973680736817368273683736847368573686736877368873689736907369173692736937369473695736967369773698736997370073701737027370373704737057370673707737087370973710737117371273713737147371573716737177371873719737207372173722737237372473725737267372773728737297373073731737327373373734737357373673737737387373973740737417374273743737447374573746737477374873749737507375173752737537375473755737567375773758737597376073761737627376373764737657376673767737687376973770737717377273773737747377573776737777377873779737807378173782737837378473785737867378773788737897379073791737927379373794737957379673797737987379973800738017380273803738047380573806738077380873809738107381173812738137381473815738167381773818738197382073821738227382373824738257382673827738287382973830738317383273833738347383573836738377383873839738407384173842738437384473845738467384773848738497385073851738527385373854738557385673857738587385973860738617386273863738647386573866738677386873869738707387173872738737387473875738767387773878738797388073881738827388373884738857388673887738887388973890738917389273893738947389573896738977389873899739007390173902739037390473905739067390773908739097391073911739127391373914739157391673917739187391973920739217392273923739247392573926739277392873929739307393173932739337393473935739367393773938739397394073941739427394373944739457394673947739487394973950739517395273953739547395573956739577395873959739607396173962739637396473965739667396773968739697397073971739727397373974739757397673977739787397973980739817398273983739847398573986739877398873989739907399173992739937399473995739967399773998739997400074001740027400374004740057400674007740087400974010740117401274013740147401574016740177401874019740207402174022740237402474025740267402774028740297403074031740327403374034740357403674037740387403974040740417404274043740447404574046740477404874049740507405174052740537405474055740567405774058740597406074061740627406374064740657406674067740687406974070740717407274073740747407574076740777407874079740807408174082740837408474085740867408774088740897409074091740927409374094740957409674097740987409974100741017410274103741047410574106741077410874109741107411174112741137411474115741167411774118741197412074121741227412374124741257412674127741287412974130741317413274133741347413574136741377413874139741407414174142741437414474145741467414774148741497415074151741527415374154741557415674157741587415974160741617416274163741647416574166741677416874169741707417174172741737417474175741767417774178741797418074181741827418374184741857418674187741887418974190741917419274193741947419574196741977419874199742007420174202742037420474205742067420774208742097421074211742127421374214742157421674217742187421974220742217422274223742247422574226742277422874229742307423174232742337423474235742367423774238742397424074241742427424374244742457424674247742487424974250742517425274253742547425574256742577425874259742607426174262742637426474265742667426774268742697427074271742727427374274742757427674277742787427974280742817428274283742847428574286742877428874289742907429174292742937429474295742967429774298742997430074301743027430374304743057430674307743087430974310743117431274313743147431574316743177431874319743207432174322743237432474325743267432774328743297433074331743327433374334743357433674337743387433974340743417434274343743447434574346743477434874349743507435174352743537435474355743567435774358743597436074361743627436374364743657436674367743687436974370743717437274373743747437574376743777437874379743807438174382743837438474385743867438774388743897439074391743927439374394743957439674397743987439974400744017440274403744047440574406744077440874409744107441174412744137441474415744167441774418744197442074421744227442374424744257442674427744287442974430744317443274433744347443574436744377443874439744407444174442744437444474445744467444774448744497445074451744527445374454744557445674457744587445974460744617446274463744647446574466744677446874469744707447174472744737447474475744767447774478744797448074481744827448374484744857448674487744887448974490744917449274493744947449574496744977449874499745007450174502745037450474505745067450774508745097451074511745127451374514745157451674517745187451974520745217452274523745247452574526745277452874529745307453174532745337453474535745367453774538745397454074541745427454374544745457454674547745487454974550745517455274553745547455574556745577455874559745607456174562745637456474565745667456774568745697457074571745727457374574745757457674577745787457974580745817458274583745847458574586745877458874589745907459174592745937459474595745967459774598745997460074601746027460374604746057460674607746087460974610746117461274613746147461574616746177461874619746207462174622746237462474625746267462774628746297463074631746327463374634746357463674637746387463974640746417464274643746447464574646746477464874649746507465174652746537465474655746567465774658746597466074661746627466374664746657466674667746687466974670746717467274673746747467574676746777467874679746807468174682746837468474685746867468774688746897469074691746927469374694746957469674697746987469974700747017470274703747047470574706747077470874709747107471174712747137471474715747167471774718747197472074721747227472374724747257472674727747287472974730747317473274733747347473574736747377473874739747407474174742747437474474745747467474774748747497475074751747527475374754747557475674757747587475974760747617476274763747647476574766747677476874769747707477174772747737477474775747767477774778747797478074781747827478374784747857478674787747887478974790747917479274793747947479574796747977479874799748007480174802748037480474805748067480774808748097481074811748127481374814748157481674817748187481974820748217482274823748247482574826748277482874829748307483174832748337483474835748367483774838748397484074841748427484374844748457484674847748487484974850748517485274853748547485574856748577485874859748607486174862748637486474865748667486774868748697487074871748727487374874748757487674877748787487974880748817488274883748847488574886748877488874889748907489174892748937489474895748967489774898748997490074901749027490374904749057490674907749087490974910749117491274913749147491574916749177491874919749207492174922749237492474925749267492774928749297493074931749327493374934749357493674937749387493974940749417494274943749447494574946749477494874949749507495174952749537495474955749567495774958749597496074961749627496374964749657496674967749687496974970749717497274973749747497574976749777497874979749807498174982749837498474985749867498774988749897499074991749927499374994749957499674997749987499975000750017500275003750047500575006750077500875009750107501175012750137501475015750167501775018750197502075021750227502375024750257502675027750287502975030750317503275033750347503575036750377503875039750407504175042750437504475045750467504775048750497505075051750527505375054750557505675057750587505975060750617506275063750647506575066750677506875069750707507175072750737507475075750767507775078750797508075081750827508375084750857508675087750887508975090750917509275093750947509575096750977509875099751007510175102751037510475105751067510775108751097511075111751127511375114751157511675117751187511975120751217512275123751247512575126751277512875129751307513175132751337513475135751367513775138751397514075141751427514375144751457514675147751487514975150751517515275153751547515575156751577515875159751607516175162751637516475165751667516775168751697517075171751727517375174751757517675177751787517975180751817518275183751847518575186751877518875189751907519175192751937519475195751967519775198751997520075201752027520375204752057520675207752087520975210752117521275213752147521575216752177521875219752207522175222752237522475225752267522775228752297523075231752327523375234752357523675237752387523975240752417524275243752447524575246752477524875249752507525175252752537525475255752567525775258752597526075261752627526375264752657526675267752687526975270752717527275273752747527575276752777527875279752807528175282752837528475285752867528775288752897529075291752927529375294752957529675297752987529975300753017530275303753047530575306753077530875309753107531175312753137531475315753167531775318753197532075321753227532375324753257532675327753287532975330753317533275333753347533575336753377533875339753407534175342753437534475345753467534775348753497535075351753527535375354753557535675357753587535975360753617536275363753647536575366753677536875369753707537175372753737537475375753767537775378753797538075381753827538375384753857538675387753887538975390753917539275393753947539575396753977539875399754007540175402754037540475405754067540775408754097541075411754127541375414754157541675417754187541975420754217542275423754247542575426754277542875429754307543175432754337543475435754367543775438754397544075441754427544375444754457544675447754487544975450754517545275453754547545575456754577545875459754607546175462754637546475465754667546775468754697547075471754727547375474754757547675477754787547975480754817548275483754847548575486754877548875489754907549175492754937549475495754967549775498754997550075501755027550375504755057550675507755087550975510755117551275513755147551575516755177551875519755207552175522755237552475525755267552775528755297553075531755327553375534755357553675537755387553975540755417554275543755447554575546755477554875549755507555175552755537555475555755567555775558755597556075561755627556375564755657556675567755687556975570755717557275573755747557575576755777557875579755807558175582755837558475585755867558775588755897559075591755927559375594755957559675597755987559975600756017560275603756047560575606756077560875609756107561175612756137561475615756167561775618756197562075621756227562375624756257562675627756287562975630756317563275633756347563575636756377563875639756407564175642756437564475645756467564775648756497565075651756527565375654756557565675657756587565975660756617566275663756647566575666756677566875669756707567175672756737567475675756767567775678756797568075681756827568375684756857568675687756887568975690756917569275693756947569575696756977569875699757007570175702757037570475705757067570775708757097571075711757127571375714757157571675717757187571975720757217572275723757247572575726757277572875729757307573175732757337573475735757367573775738757397574075741757427574375744757457574675747757487574975750757517575275753757547575575756757577575875759757607576175762757637576475765757667576775768757697577075771757727577375774757757577675777757787577975780757817578275783757847578575786757877578875789757907579175792757937579475795757967579775798757997580075801758027580375804758057580675807758087580975810758117581275813758147581575816758177581875819758207582175822758237582475825758267582775828758297583075831758327583375834758357583675837758387583975840758417584275843758447584575846758477584875849758507585175852758537585475855758567585775858758597586075861758627586375864758657586675867758687586975870758717587275873758747587575876758777587875879758807588175882758837588475885758867588775888758897589075891758927589375894758957589675897758987589975900759017590275903759047590575906759077590875909759107591175912759137591475915759167591775918759197592075921759227592375924759257592675927759287592975930759317593275933759347593575936759377593875939759407594175942759437594475945759467594775948759497595075951759527595375954759557595675957759587595975960759617596275963759647596575966759677596875969759707597175972759737597475975759767597775978759797598075981759827598375984759857598675987759887598975990759917599275993759947599575996759977599875999760007600176002760037600476005760067600776008760097601076011760127601376014760157601676017760187601976020760217602276023760247602576026760277602876029760307603176032760337603476035760367603776038760397604076041760427604376044760457604676047760487604976050760517605276053760547605576056760577605876059760607606176062760637606476065760667606776068760697607076071760727607376074760757607676077760787607976080760817608276083760847608576086760877608876089760907609176092760937609476095760967609776098760997610076101761027610376104761057610676107761087610976110761117611276113761147611576116761177611876119761207612176122761237612476125761267612776128761297613076131761327613376134761357613676137761387613976140761417614276143761447614576146761477614876149761507615176152761537615476155761567615776158761597616076161761627616376164761657616676167761687616976170761717617276173761747617576176761777617876179761807618176182761837618476185761867618776188761897619076191761927619376194761957619676197761987619976200762017620276203762047620576206762077620876209762107621176212762137621476215762167621776218762197622076221762227622376224762257622676227762287622976230762317623276233762347623576236762377623876239762407624176242762437624476245762467624776248762497625076251762527625376254762557625676257762587625976260762617626276263762647626576266762677626876269762707627176272762737627476275762767627776278762797628076281762827628376284762857628676287762887628976290762917629276293762947629576296762977629876299763007630176302763037630476305763067630776308763097631076311763127631376314763157631676317763187631976320763217632276323763247632576326763277632876329763307633176332763337633476335763367633776338763397634076341763427634376344763457634676347763487634976350763517635276353763547635576356763577635876359763607636176362763637636476365763667636776368763697637076371763727637376374763757637676377763787637976380763817638276383763847638576386763877638876389763907639176392763937639476395763967639776398763997640076401764027640376404764057640676407764087640976410764117641276413764147641576416764177641876419764207642176422764237642476425764267642776428764297643076431764327643376434764357643676437764387643976440764417644276443764447644576446764477644876449764507645176452764537645476455764567645776458764597646076461764627646376464764657646676467764687646976470764717647276473764747647576476764777647876479764807648176482764837648476485764867648776488764897649076491764927649376494764957649676497764987649976500765017650276503765047650576506765077650876509765107651176512765137651476515765167651776518765197652076521765227652376524765257652676527765287652976530765317653276533765347653576536765377653876539765407654176542765437654476545765467654776548765497655076551765527655376554765557655676557765587655976560765617656276563765647656576566765677656876569765707657176572765737657476575765767657776578765797658076581765827658376584765857658676587765887658976590765917659276593765947659576596765977659876599766007660176602766037660476605766067660776608766097661076611766127661376614766157661676617766187661976620766217662276623766247662576626766277662876629766307663176632766337663476635766367663776638766397664076641766427664376644766457664676647766487664976650766517665276653766547665576656766577665876659766607666176662766637666476665766667666776668766697667076671766727667376674766757667676677766787667976680766817668276683766847668576686766877668876689766907669176692766937669476695766967669776698766997670076701767027670376704767057670676707767087670976710767117671276713767147671576716767177671876719767207672176722767237672476725767267672776728767297673076731767327673376734767357673676737767387673976740767417674276743767447674576746767477674876749767507675176752767537675476755767567675776758767597676076761767627676376764767657676676767767687676976770767717677276773767747677576776767777677876779767807678176782767837678476785767867678776788767897679076791767927679376794767957679676797767987679976800768017680276803768047680576806768077680876809768107681176812768137681476815768167681776818768197682076821768227682376824768257682676827768287682976830768317683276833768347683576836768377683876839768407684176842768437684476845768467684776848768497685076851768527685376854768557685676857768587685976860768617686276863768647686576866768677686876869768707687176872768737687476875768767687776878768797688076881768827688376884768857688676887768887688976890768917689276893768947689576896768977689876899769007690176902769037690476905769067690776908769097691076911769127691376914769157691676917769187691976920769217692276923769247692576926769277692876929769307693176932769337693476935769367693776938769397694076941769427694376944769457694676947769487694976950769517695276953769547695576956769577695876959769607696176962769637696476965769667696776968769697697076971769727697376974769757697676977769787697976980769817698276983769847698576986769877698876989769907699176992769937699476995769967699776998769997700077001770027700377004770057700677007770087700977010770117701277013770147701577016770177701877019770207702177022770237702477025770267702777028770297703077031770327703377034770357703677037770387703977040770417704277043770447704577046770477704877049770507705177052770537705477055770567705777058770597706077061770627706377064770657706677067770687706977070770717707277073770747707577076770777707877079770807708177082770837708477085770867708777088770897709077091770927709377094770957709677097770987709977100771017710277103771047710577106771077710877109771107711177112771137711477115771167711777118771197712077121771227712377124771257712677127771287712977130771317713277133771347713577136771377713877139771407714177142771437714477145771467714777148771497715077151771527715377154771557715677157771587715977160771617716277163771647716577166771677716877169771707717177172771737717477175771767717777178771797718077181771827718377184771857718677187771887718977190771917719277193771947719577196771977719877199772007720177202772037720477205772067720777208772097721077211772127721377214772157721677217772187721977220772217722277223772247722577226772277722877229772307723177232772337723477235772367723777238772397724077241772427724377244772457724677247772487724977250772517725277253772547725577256772577725877259772607726177262772637726477265772667726777268772697727077271772727727377274772757727677277772787727977280772817728277283772847728577286772877728877289772907729177292772937729477295772967729777298772997730077301773027730377304773057730677307773087730977310773117731277313773147731577316773177731877319773207732177322773237732477325773267732777328773297733077331773327733377334773357733677337773387733977340773417734277343773447734577346773477734877349773507735177352773537735477355773567735777358773597736077361773627736377364773657736677367773687736977370773717737277373773747737577376773777737877379773807738177382773837738477385773867738777388773897739077391773927739377394773957739677397773987739977400774017740277403774047740577406774077740877409774107741177412774137741477415774167741777418774197742077421774227742377424774257742677427774287742977430774317743277433774347743577436774377743877439774407744177442774437744477445774467744777448774497745077451774527745377454774557745677457774587745977460774617746277463774647746577466774677746877469774707747177472774737747477475774767747777478774797748077481774827748377484774857748677487774887748977490774917749277493774947749577496774977749877499775007750177502775037750477505775067750777508775097751077511775127751377514775157751677517775187751977520775217752277523775247752577526775277752877529775307753177532775337753477535775367753777538775397754077541775427754377544775457754677547775487754977550775517755277553775547755577556775577755877559775607756177562775637756477565775667756777568775697757077571775727757377574775757757677577775787757977580775817758277583775847758577586775877758877589775907759177592775937759477595775967759777598775997760077601776027760377604776057760677607776087760977610776117761277613776147761577616776177761877619776207762177622776237762477625776267762777628776297763077631776327763377634776357763677637776387763977640776417764277643776447764577646776477764877649776507765177652776537765477655776567765777658776597766077661776627766377664776657766677667776687766977670776717767277673776747767577676776777767877679776807768177682776837768477685776867768777688776897769077691776927769377694776957769677697776987769977700777017770277703777047770577706777077770877709777107771177712777137771477715777167771777718777197772077721777227772377724777257772677727777287772977730777317773277733777347773577736777377773877739777407774177742777437774477745777467774777748777497775077751777527775377754777557775677757777587775977760777617776277763777647776577766777677776877769777707777177772777737777477775777767777777778777797778077781777827778377784777857778677787777887778977790777917779277793777947779577796777977779877799778007780177802778037780477805778067780777808778097781077811778127781377814778157781677817778187781977820778217782277823778247782577826778277782877829778307783177832778337783477835778367783777838778397784077841778427784377844778457784677847778487784977850778517785277853778547785577856778577785877859778607786177862778637786477865778667786777868778697787077871778727787377874778757787677877778787787977880778817788277883778847788577886778877788877889778907789177892778937789477895778967789777898778997790077901779027790377904779057790677907779087790977910779117791277913779147791577916779177791877919779207792177922779237792477925779267792777928779297793077931779327793377934779357793677937779387793977940779417794277943779447794577946779477794877949779507795177952779537795477955779567795777958779597796077961779627796377964779657796677967779687796977970779717797277973779747797577976779777797877979779807798177982779837798477985779867798777988779897799077991779927799377994779957799677997779987799978000780017800278003780047800578006780077800878009780107801178012780137801478015780167801778018780197802078021780227802378024780257802678027780287802978030780317803278033780347803578036780377803878039780407804178042780437804478045780467804778048780497805078051780527805378054780557805678057780587805978060780617806278063780647806578066780677806878069780707807178072780737807478075780767807778078780797808078081780827808378084780857808678087780887808978090780917809278093780947809578096780977809878099781007810178102781037810478105781067810778108781097811078111781127811378114781157811678117781187811978120781217812278123781247812578126781277812878129781307813178132781337813478135781367813778138781397814078141781427814378144781457814678147781487814978150781517815278153781547815578156781577815878159781607816178162781637816478165781667816778168781697817078171781727817378174781757817678177781787817978180781817818278183781847818578186781877818878189781907819178192781937819478195781967819778198781997820078201782027820378204782057820678207782087820978210782117821278213782147821578216782177821878219782207822178222782237822478225782267822778228782297823078231782327823378234782357823678237782387823978240782417824278243782447824578246782477824878249782507825178252782537825478255782567825778258782597826078261782627826378264782657826678267782687826978270782717827278273782747827578276782777827878279782807828178282782837828478285782867828778288782897829078291782927829378294782957829678297782987829978300783017830278303783047830578306783077830878309783107831178312783137831478315783167831778318783197832078321783227832378324783257832678327783287832978330783317833278333783347833578336783377833878339783407834178342783437834478345783467834778348783497835078351783527835378354783557835678357783587835978360783617836278363783647836578366783677836878369783707837178372783737837478375783767837778378783797838078381783827838378384783857838678387783887838978390783917839278393783947839578396783977839878399784007840178402784037840478405784067840778408784097841078411784127841378414784157841678417784187841978420784217842278423784247842578426784277842878429784307843178432784337843478435784367843778438784397844078441784427844378444784457844678447784487844978450784517845278453784547845578456784577845878459784607846178462784637846478465784667846778468784697847078471784727847378474784757847678477784787847978480784817848278483784847848578486784877848878489784907849178492784937849478495784967849778498784997850078501785027850378504785057850678507785087850978510785117851278513785147851578516785177851878519785207852178522785237852478525785267852778528785297853078531785327853378534785357853678537785387853978540785417854278543785447854578546785477854878549785507855178552785537855478555785567855778558785597856078561785627856378564785657856678567785687856978570785717857278573785747857578576785777857878579785807858178582785837858478585785867858778588785897859078591785927859378594785957859678597785987859978600786017860278603786047860578606786077860878609786107861178612786137861478615786167861778618786197862078621786227862378624786257862678627786287862978630786317863278633786347863578636786377863878639786407864178642786437864478645786467864778648786497865078651786527865378654786557865678657786587865978660786617866278663786647866578666786677866878669786707867178672786737867478675786767867778678786797868078681786827868378684786857868678687786887868978690786917869278693786947869578696786977869878699787007870178702787037870478705787067870778708787097871078711787127871378714787157871678717787187871978720787217872278723787247872578726787277872878729787307873178732787337873478735787367873778738787397874078741787427874378744787457874678747787487874978750787517875278753787547875578756787577875878759787607876178762787637876478765787667876778768787697877078771787727877378774787757877678777787787877978780787817878278783787847878578786787877878878789787907879178792787937879478795787967879778798787997880078801788027880378804788057880678807788087880978810788117881278813788147881578816788177881878819788207882178822788237882478825788267882778828788297883078831788327883378834788357883678837788387883978840788417884278843788447884578846788477884878849788507885178852788537885478855788567885778858788597886078861788627886378864788657886678867788687886978870788717887278873788747887578876788777887878879788807888178882788837888478885788867888778888788897889078891788927889378894788957889678897788987889978900789017890278903789047890578906789077890878909789107891178912789137891478915789167891778918789197892078921789227892378924789257892678927789287892978930789317893278933789347893578936789377893878939789407894178942789437894478945789467894778948789497895078951789527895378954789557895678957789587895978960789617896278963789647896578966789677896878969789707897178972789737897478975789767897778978789797898078981789827898378984789857898678987789887898978990789917899278993789947899578996789977899878999790007900179002790037900479005790067900779008790097901079011790127901379014790157901679017790187901979020790217902279023790247902579026790277902879029790307903179032790337903479035790367903779038790397904079041790427904379044790457904679047790487904979050790517905279053790547905579056790577905879059790607906179062790637906479065790667906779068790697907079071790727907379074790757907679077790787907979080790817908279083790847908579086790877908879089790907909179092790937909479095790967909779098790997910079101791027910379104791057910679107791087910979110791117911279113791147911579116791177911879119791207912179122791237912479125791267912779128791297913079131791327913379134791357913679137791387913979140791417914279143791447914579146791477914879149791507915179152791537915479155791567915779158791597916079161791627916379164791657916679167791687916979170791717917279173791747917579176791777917879179791807918179182791837918479185791867918779188791897919079191791927919379194791957919679197791987919979200792017920279203792047920579206792077920879209792107921179212792137921479215792167921779218792197922079221792227922379224792257922679227792287922979230792317923279233792347923579236792377923879239792407924179242792437924479245792467924779248792497925079251792527925379254792557925679257792587925979260792617926279263792647926579266792677926879269792707927179272792737927479275792767927779278792797928079281792827928379284792857928679287792887928979290792917929279293792947929579296792977929879299793007930179302793037930479305793067930779308793097931079311793127931379314793157931679317793187931979320793217932279323793247932579326793277932879329793307933179332793337933479335793367933779338793397934079341793427934379344793457934679347793487934979350793517935279353793547935579356793577935879359793607936179362793637936479365793667936779368793697937079371793727937379374793757937679377793787937979380793817938279383793847938579386793877938879389793907939179392793937939479395793967939779398793997940079401794027940379404794057940679407794087940979410794117941279413794147941579416794177941879419794207942179422794237942479425794267942779428794297943079431794327943379434794357943679437794387943979440794417944279443794447944579446794477944879449794507945179452794537945479455794567945779458794597946079461794627946379464794657946679467794687946979470794717947279473794747947579476794777947879479794807948179482794837948479485794867948779488794897949079491794927949379494794957949679497794987949979500795017950279503795047950579506795077950879509795107951179512795137951479515795167951779518795197952079521795227952379524795257952679527795287952979530795317953279533795347953579536795377953879539795407954179542795437954479545795467954779548795497955079551795527955379554795557955679557795587955979560795617956279563795647956579566795677956879569795707957179572795737957479575795767957779578795797958079581795827958379584795857958679587795887958979590795917959279593795947959579596795977959879599796007960179602796037960479605796067960779608796097961079611796127961379614796157961679617796187961979620796217962279623796247962579626796277962879629796307963179632796337963479635796367963779638796397964079641796427964379644796457964679647796487964979650796517965279653796547965579656796577965879659796607966179662796637966479665796667966779668796697967079671796727967379674796757967679677796787967979680796817968279683796847968579686796877968879689796907969179692796937969479695796967969779698796997970079701797027970379704797057970679707797087970979710797117971279713797147971579716797177971879719797207972179722797237972479725797267972779728797297973079731797327973379734797357973679737797387973979740797417974279743797447974579746797477974879749797507975179752797537975479755797567975779758797597976079761797627976379764797657976679767797687976979770797717977279773797747977579776797777977879779797807978179782797837978479785797867978779788797897979079791797927979379794797957979679797797987979979800798017980279803798047980579806798077980879809798107981179812798137981479815798167981779818798197982079821798227982379824798257982679827798287982979830798317983279833798347983579836798377983879839798407984179842798437984479845798467984779848798497985079851798527985379854798557985679857798587985979860798617986279863798647986579866798677986879869798707987179872798737987479875798767987779878798797988079881798827988379884798857988679887798887988979890798917989279893798947989579896798977989879899799007990179902799037990479905799067990779908799097991079911799127991379914799157991679917799187991979920799217992279923799247992579926799277992879929799307993179932799337993479935799367993779938799397994079941799427994379944799457994679947799487994979950799517995279953799547995579956799577995879959799607996179962799637996479965799667996779968799697997079971799727997379974799757997679977799787997979980799817998279983799847998579986799877998879989799907999179992799937999479995799967999779998799998000080001800028000380004800058000680007800088000980010800118001280013800148001580016800178001880019800208002180022800238002480025800268002780028800298003080031800328003380034800358003680037800388003980040800418004280043800448004580046800478004880049800508005180052800538005480055800568005780058800598006080061800628006380064800658006680067800688006980070800718007280073800748007580076800778007880079800808008180082800838008480085800868008780088800898009080091800928009380094800958009680097800988009980100801018010280103801048010580106801078010880109801108011180112801138011480115801168011780118801198012080121801228012380124801258012680127801288012980130801318013280133801348013580136801378013880139801408014180142801438014480145801468014780148801498015080151801528015380154801558015680157801588015980160801618016280163801648016580166801678016880169801708017180172801738017480175801768017780178801798018080181801828018380184801858018680187801888018980190801918019280193801948019580196801978019880199802008020180202802038020480205802068020780208802098021080211802128021380214802158021680217802188021980220802218022280223802248022580226802278022880229802308023180232802338023480235802368023780238802398024080241802428024380244802458024680247802488024980250802518025280253802548025580256802578025880259802608026180262802638026480265802668026780268802698027080271802728027380274802758027680277802788027980280802818028280283802848028580286802878028880289802908029180292802938029480295802968029780298802998030080301803028030380304803058030680307803088030980310803118031280313803148031580316803178031880319803208032180322803238032480325803268032780328803298033080331803328033380334803358033680337803388033980340803418034280343803448034580346803478034880349803508035180352803538035480355803568035780358803598036080361803628036380364803658036680367803688036980370803718037280373803748037580376803778037880379803808038180382803838038480385803868038780388803898039080391803928039380394803958039680397803988039980400804018040280403804048040580406804078040880409804108041180412804138041480415804168041780418804198042080421804228042380424804258042680427804288042980430804318043280433804348043580436804378043880439804408044180442804438044480445804468044780448804498045080451804528045380454804558045680457804588045980460804618046280463804648046580466804678046880469804708047180472804738047480475804768047780478804798048080481804828048380484804858048680487804888048980490804918049280493804948049580496804978049880499805008050180502805038050480505805068050780508805098051080511805128051380514805158051680517805188051980520805218052280523805248052580526805278052880529805308053180532805338053480535805368053780538805398054080541805428054380544805458054680547805488054980550805518055280553805548055580556805578055880559805608056180562805638056480565805668056780568805698057080571805728057380574805758057680577805788057980580805818058280583805848058580586805878058880589805908059180592805938059480595805968059780598805998060080601806028060380604806058060680607806088060980610806118061280613806148061580616806178061880619806208062180622806238062480625806268062780628806298063080631806328063380634806358063680637806388063980640806418064280643806448064580646806478064880649806508065180652806538065480655806568065780658806598066080661806628066380664806658066680667806688066980670806718067280673806748067580676806778067880679806808068180682806838068480685806868068780688806898069080691806928069380694806958069680697806988069980700807018070280703807048070580706807078070880709807108071180712807138071480715807168071780718807198072080721807228072380724807258072680727807288072980730807318073280733807348073580736807378073880739807408074180742807438074480745807468074780748807498075080751807528075380754807558075680757807588075980760807618076280763807648076580766807678076880769807708077180772807738077480775807768077780778807798078080781807828078380784807858078680787807888078980790807918079280793807948079580796807978079880799808008080180802808038080480805808068080780808808098081080811808128081380814808158081680817808188081980820808218082280823808248082580826808278082880829808308083180832808338083480835808368083780838808398084080841808428084380844808458084680847808488084980850808518085280853808548085580856808578085880859808608086180862808638086480865808668086780868808698087080871808728087380874808758087680877808788087980880808818088280883808848088580886808878088880889808908089180892808938089480895808968089780898808998090080901809028090380904809058090680907809088090980910809118091280913809148091580916809178091880919809208092180922809238092480925809268092780928809298093080931809328093380934809358093680937809388093980940809418094280943809448094580946809478094880949809508095180952809538095480955809568095780958809598096080961809628096380964809658096680967809688096980970809718097280973809748097580976809778097880979809808098180982809838098480985809868098780988809898099080991809928099380994809958099680997809988099981000810018100281003810048100581006810078100881009810108101181012810138101481015810168101781018810198102081021810228102381024810258102681027810288102981030810318103281033810348103581036810378103881039810408104181042810438104481045810468104781048810498105081051810528105381054810558105681057810588105981060810618106281063810648106581066810678106881069810708107181072810738107481075810768107781078810798108081081810828108381084810858108681087810888108981090810918109281093810948109581096810978109881099811008110181102811038110481105811068110781108811098111081111811128111381114811158111681117811188111981120811218112281123811248112581126811278112881129811308113181132811338113481135811368113781138811398114081141811428114381144811458114681147811488114981150811518115281153811548115581156811578115881159811608116181162811638116481165811668116781168811698117081171811728117381174811758117681177811788117981180811818118281183811848118581186811878118881189811908119181192811938119481195811968119781198811998120081201812028120381204812058120681207812088120981210812118121281213812148121581216812178121881219812208122181222812238122481225812268122781228812298123081231812328123381234812358123681237812388123981240812418124281243812448124581246812478124881249812508125181252812538125481255812568125781258812598126081261812628126381264812658126681267812688126981270812718127281273812748127581276812778127881279812808128181282812838128481285812868128781288812898129081291812928129381294812958129681297812988129981300813018130281303813048130581306813078130881309813108131181312813138131481315813168131781318813198132081321813228132381324813258132681327813288132981330813318133281333813348133581336813378133881339813408134181342813438134481345813468134781348813498135081351813528135381354813558135681357813588135981360813618136281363813648136581366813678136881369813708137181372813738137481375813768137781378813798138081381813828138381384813858138681387813888138981390813918139281393813948139581396813978139881399814008140181402814038140481405814068140781408814098141081411814128141381414814158141681417814188141981420814218142281423814248142581426814278142881429814308143181432814338143481435814368143781438814398144081441814428144381444814458144681447814488144981450814518145281453814548145581456814578145881459814608146181462814638146481465814668146781468814698147081471814728147381474814758147681477814788147981480814818148281483814848148581486814878148881489814908149181492814938149481495814968149781498814998150081501815028150381504815058150681507815088150981510815118151281513815148151581516815178151881519815208152181522815238152481525815268152781528815298153081531815328153381534815358153681537815388153981540815418154281543815448154581546815478154881549815508155181552815538155481555815568155781558815598156081561815628156381564815658156681567815688156981570815718157281573815748157581576815778157881579815808158181582815838158481585815868158781588815898159081591815928159381594815958159681597815988159981600816018160281603816048160581606816078160881609816108161181612816138161481615816168161781618816198162081621816228162381624816258162681627816288162981630816318163281633816348163581636816378163881639816408164181642816438164481645816468164781648816498165081651816528165381654816558165681657816588165981660816618166281663816648166581666816678166881669816708167181672816738167481675816768167781678816798168081681816828168381684816858168681687816888168981690816918169281693816948169581696816978169881699817008170181702817038170481705817068170781708817098171081711817128171381714817158171681717817188171981720817218172281723817248172581726817278172881729817308173181732817338173481735817368173781738817398174081741817428174381744817458174681747817488174981750817518175281753817548175581756817578175881759817608176181762817638176481765817668176781768817698177081771817728177381774817758177681777817788177981780817818178281783817848178581786817878178881789817908179181792817938179481795817968179781798817998180081801818028180381804818058180681807818088180981810818118181281813818148181581816818178181881819818208182181822818238182481825818268182781828818298183081831818328183381834818358183681837818388183981840818418184281843818448184581846818478184881849818508185181852818538185481855818568185781858818598186081861818628186381864818658186681867818688186981870818718187281873818748187581876818778187881879818808188181882818838188481885818868188781888818898189081891818928189381894818958189681897818988189981900819018190281903819048190581906819078190881909819108191181912819138191481915819168191781918819198192081921819228192381924819258192681927819288192981930819318193281933819348193581936819378193881939819408194181942819438194481945819468194781948819498195081951819528195381954819558195681957819588195981960819618196281963819648196581966819678196881969819708197181972819738197481975819768197781978819798198081981819828198381984819858198681987819888198981990819918199281993819948199581996819978199881999820008200182002820038200482005820068200782008820098201082011820128201382014820158201682017820188201982020820218202282023820248202582026820278202882029820308203182032820338203482035820368203782038820398204082041820428204382044820458204682047820488204982050820518205282053820548205582056820578205882059820608206182062820638206482065820668206782068820698207082071820728207382074820758207682077820788207982080820818208282083820848208582086820878208882089820908209182092820938209482095820968209782098820998210082101821028210382104821058210682107821088210982110821118211282113821148211582116821178211882119821208212182122821238212482125821268212782128821298213082131821328213382134821358213682137821388213982140821418214282143821448214582146821478214882149821508215182152821538215482155821568215782158821598216082161821628216382164821658216682167821688216982170821718217282173821748217582176821778217882179821808218182182821838218482185821868218782188821898219082191821928219382194821958219682197821988219982200822018220282203822048220582206822078220882209822108221182212822138221482215822168221782218822198222082221822228222382224822258222682227822288222982230822318223282233822348223582236822378223882239822408224182242822438224482245822468224782248822498225082251822528225382254822558225682257822588225982260822618226282263822648226582266822678226882269822708227182272822738227482275822768227782278822798228082281822828228382284822858228682287822888228982290822918229282293822948229582296822978229882299823008230182302823038230482305823068230782308823098231082311823128231382314823158231682317823188231982320823218232282323823248232582326823278232882329823308233182332823338233482335823368233782338823398234082341823428234382344823458234682347823488234982350823518235282353823548235582356823578235882359823608236182362823638236482365823668236782368823698237082371823728237382374823758237682377823788237982380823818238282383823848238582386823878238882389823908239182392823938239482395823968239782398823998240082401824028240382404824058240682407824088240982410824118241282413824148241582416824178241882419824208242182422824238242482425824268242782428824298243082431824328243382434824358243682437824388243982440824418244282443824448244582446824478244882449824508245182452824538245482455824568245782458824598246082461824628246382464824658246682467824688246982470824718247282473824748247582476824778247882479824808248182482824838248482485824868248782488824898249082491824928249382494824958249682497824988249982500825018250282503825048250582506825078250882509825108251182512825138251482515825168251782518825198252082521825228252382524825258252682527825288252982530825318253282533825348253582536825378253882539825408254182542825438254482545825468254782548825498255082551825528255382554825558255682557825588255982560825618256282563825648256582566825678256882569825708257182572825738257482575825768257782578825798258082581825828258382584825858258682587825888258982590825918259282593825948259582596825978259882599826008260182602826038260482605826068260782608826098261082611826128261382614826158261682617826188261982620826218262282623826248262582626826278262882629826308263182632826338263482635826368263782638826398264082641826428264382644826458264682647826488264982650826518265282653826548265582656826578265882659826608266182662826638266482665826668266782668826698267082671826728267382674826758267682677826788267982680826818268282683826848268582686826878268882689826908269182692826938269482695826968269782698826998270082701827028270382704827058270682707827088270982710827118271282713827148271582716827178271882719827208272182722827238272482725827268272782728827298273082731827328273382734827358273682737827388273982740827418274282743827448274582746827478274882749827508275182752827538275482755827568275782758827598276082761827628276382764827658276682767827688276982770827718277282773827748277582776827778277882779827808278182782827838278482785827868278782788827898279082791827928279382794827958279682797827988279982800828018280282803828048280582806828078280882809828108281182812828138281482815828168281782818828198282082821828228282382824828258282682827828288282982830828318283282833828348283582836828378283882839828408284182842828438284482845828468284782848828498285082851828528285382854828558285682857828588285982860828618286282863828648286582866828678286882869828708287182872828738287482875828768287782878828798288082881828828288382884828858288682887828888288982890828918289282893828948289582896828978289882899829008290182902829038290482905829068290782908829098291082911829128291382914829158291682917829188291982920829218292282923829248292582926829278292882929829308293182932829338293482935829368293782938829398294082941829428294382944829458294682947829488294982950829518295282953829548295582956829578295882959829608296182962829638296482965829668296782968829698297082971829728297382974829758297682977829788297982980829818298282983829848298582986829878298882989829908299182992829938299482995829968299782998829998300083001830028300383004830058300683007830088300983010830118301283013830148301583016830178301883019830208302183022830238302483025830268302783028830298303083031830328303383034830358303683037830388303983040830418304283043830448304583046830478304883049830508305183052830538305483055830568305783058830598306083061830628306383064830658306683067830688306983070830718307283073830748307583076830778307883079830808308183082830838308483085830868308783088830898309083091830928309383094830958309683097830988309983100831018310283103831048310583106831078310883109831108311183112831138311483115831168311783118831198312083121831228312383124831258312683127831288312983130831318313283133831348313583136831378313883139831408314183142831438314483145831468314783148831498315083151831528315383154831558315683157831588315983160831618316283163831648316583166831678316883169831708317183172831738317483175831768317783178831798318083181831828318383184831858318683187831888318983190831918319283193831948319583196831978319883199832008320183202832038320483205832068320783208832098321083211832128321383214832158321683217832188321983220832218322283223832248322583226832278322883229832308323183232832338323483235832368323783238832398324083241832428324383244832458324683247832488324983250832518325283253832548325583256832578325883259832608326183262832638326483265832668326783268832698327083271832728327383274832758327683277832788327983280832818328283283832848328583286832878328883289832908329183292832938329483295832968329783298832998330083301833028330383304833058330683307833088330983310833118331283313833148331583316833178331883319833208332183322833238332483325833268332783328833298333083331833328333383334833358333683337833388333983340833418334283343833448334583346833478334883349833508335183352833538335483355833568335783358833598336083361833628336383364833658336683367833688336983370833718337283373833748337583376833778337883379833808338183382833838338483385833868338783388833898339083391833928339383394833958339683397833988339983400834018340283403834048340583406834078340883409834108341183412834138341483415834168341783418834198342083421834228342383424834258342683427834288342983430834318343283433834348343583436834378343883439834408344183442834438344483445834468344783448834498345083451834528345383454834558345683457834588345983460834618346283463834648346583466834678346883469834708347183472834738347483475834768347783478834798348083481834828348383484834858348683487834888348983490834918349283493834948349583496834978349883499835008350183502835038350483505835068350783508835098351083511835128351383514835158351683517835188351983520835218352283523835248352583526835278352883529835308353183532835338353483535835368353783538835398354083541835428354383544835458354683547835488354983550835518355283553835548355583556835578355883559835608356183562835638356483565835668356783568835698357083571835728357383574835758357683577835788357983580835818358283583835848358583586835878358883589835908359183592835938359483595835968359783598835998360083601836028360383604836058360683607836088360983610836118361283613836148361583616836178361883619836208362183622836238362483625836268362783628836298363083631836328363383634836358363683637836388363983640836418364283643836448364583646836478364883649836508365183652836538365483655836568365783658836598366083661836628366383664836658366683667836688366983670836718367283673836748367583676836778367883679836808368183682836838368483685836868368783688836898369083691836928369383694836958369683697836988369983700837018370283703837048370583706837078370883709837108371183712837138371483715837168371783718837198372083721837228372383724837258372683727837288372983730837318373283733837348373583736837378373883739837408374183742837438374483745837468374783748837498375083751837528375383754837558375683757837588375983760837618376283763837648376583766837678376883769837708377183772837738377483775837768377783778837798378083781837828378383784837858378683787837888378983790837918379283793837948379583796837978379883799838008380183802838038380483805838068380783808838098381083811838128381383814838158381683817838188381983820838218382283823838248382583826838278382883829838308383183832838338383483835838368383783838838398384083841838428384383844838458384683847838488384983850838518385283853838548385583856838578385883859838608386183862838638386483865838668386783868838698387083871838728387383874838758387683877838788387983880838818388283883838848388583886838878388883889838908389183892838938389483895838968389783898838998390083901839028390383904839058390683907839088390983910839118391283913839148391583916839178391883919839208392183922839238392483925839268392783928839298393083931839328393383934839358393683937839388393983940839418394283943839448394583946839478394883949839508395183952839538395483955839568395783958839598396083961839628396383964839658396683967839688396983970839718397283973839748397583976839778397883979839808398183982839838398483985839868398783988839898399083991839928399383994839958399683997839988399984000840018400284003840048400584006840078400884009840108401184012840138401484015840168401784018840198402084021840228402384024840258402684027840288402984030840318403284033840348403584036840378403884039840408404184042840438404484045840468404784048840498405084051840528405384054840558405684057840588405984060840618406284063840648406584066840678406884069840708407184072840738407484075840768407784078840798408084081840828408384084840858408684087840888408984090840918409284093840948409584096840978409884099841008410184102841038410484105841068410784108841098411084111841128411384114841158411684117841188411984120841218412284123841248412584126841278412884129841308413184132841338413484135841368413784138841398414084141841428414384144841458414684147841488414984150841518415284153841548415584156841578415884159841608416184162841638416484165841668416784168841698417084171841728417384174841758417684177841788417984180841818418284183841848418584186841878418884189841908419184192841938419484195841968419784198841998420084201842028420384204842058420684207842088420984210842118421284213842148421584216842178421884219842208422184222842238422484225842268422784228842298423084231842328423384234842358423684237842388423984240842418424284243842448424584246842478424884249842508425184252842538425484255842568425784258842598426084261842628426384264842658426684267842688426984270842718427284273842748427584276842778427884279842808428184282842838428484285842868428784288842898429084291842928429384294842958429684297842988429984300843018430284303843048430584306843078430884309843108431184312843138431484315843168431784318843198432084321843228432384324843258432684327843288432984330843318433284333843348433584336843378433884339843408434184342843438434484345843468434784348843498435084351843528435384354843558435684357843588435984360843618436284363843648436584366843678436884369843708437184372843738437484375843768437784378843798438084381843828438384384843858438684387843888438984390843918439284393843948439584396843978439884399844008440184402844038440484405844068440784408844098441084411844128441384414844158441684417844188441984420844218442284423844248442584426844278442884429844308443184432844338443484435844368443784438844398444084441844428444384444844458444684447844488444984450844518445284453844548445584456844578445884459844608446184462844638446484465844668446784468844698447084471844728447384474844758447684477844788447984480844818448284483844848448584486844878448884489844908449184492844938449484495844968449784498844998450084501845028450384504845058450684507845088450984510845118451284513845148451584516845178451884519845208452184522845238452484525845268452784528845298453084531845328453384534845358453684537845388453984540845418454284543845448454584546845478454884549845508455184552845538455484555845568455784558845598456084561845628456384564845658456684567845688456984570845718457284573845748457584576845778457884579845808458184582845838458484585845868458784588845898459084591845928459384594845958459684597845988459984600846018460284603846048460584606846078460884609846108461184612846138461484615846168461784618846198462084621846228462384624846258462684627846288462984630846318463284633846348463584636846378463884639846408464184642846438464484645846468464784648846498465084651846528465384654846558465684657846588465984660846618466284663846648466584666846678466884669846708467184672846738467484675846768467784678846798468084681846828468384684846858468684687846888468984690846918469284693846948469584696846978469884699847008470184702847038470484705847068470784708847098471084711847128471384714847158471684717847188471984720847218472284723847248472584726847278472884729847308473184732847338473484735847368473784738847398474084741847428474384744847458474684747847488474984750847518475284753847548475584756847578475884759847608476184762847638476484765847668476784768847698477084771847728477384774847758477684777847788477984780847818478284783847848478584786847878478884789847908479184792847938479484795847968479784798847998480084801848028480384804848058480684807848088480984810848118481284813848148481584816848178481884819848208482184822848238482484825848268482784828848298483084831848328483384834848358483684837848388483984840848418484284843848448484584846848478484884849848508485184852848538485484855848568485784858848598486084861848628486384864848658486684867848688486984870848718487284873848748487584876848778487884879848808488184882848838488484885848868488784888848898489084891848928489384894848958489684897848988489984900849018490284903849048490584906849078490884909849108491184912849138491484915849168491784918849198492084921849228492384924849258492684927849288492984930849318493284933849348493584936849378493884939849408494184942849438494484945849468494784948849498495084951849528495384954849558495684957849588495984960849618496284963849648496584966849678496884969849708497184972849738497484975849768497784978849798498084981849828498384984849858498684987849888498984990849918499284993849948499584996849978499884999850008500185002850038500485005850068500785008850098501085011850128501385014850158501685017850188501985020850218502285023850248502585026850278502885029850308503185032850338503485035850368503785038850398504085041850428504385044850458504685047850488504985050850518505285053850548505585056850578505885059850608506185062850638506485065850668506785068850698507085071850728507385074850758507685077850788507985080850818508285083850848508585086850878508885089850908509185092850938509485095850968509785098850998510085101851028510385104851058510685107851088510985110851118511285113851148511585116851178511885119851208512185122851238512485125851268512785128851298513085131851328513385134851358513685137851388513985140851418514285143851448514585146851478514885149851508515185152851538515485155851568515785158851598516085161851628516385164851658516685167851688516985170851718517285173851748517585176851778517885179851808518185182851838518485185851868518785188851898519085191851928519385194851958519685197851988519985200852018520285203852048520585206852078520885209852108521185212852138521485215852168521785218852198522085221852228522385224852258522685227852288522985230852318523285233852348523585236852378523885239852408524185242852438524485245852468524785248852498525085251852528525385254852558525685257852588525985260852618526285263852648526585266852678526885269852708527185272852738527485275852768527785278852798528085281852828528385284852858528685287852888528985290852918529285293852948529585296852978529885299853008530185302853038530485305853068530785308853098531085311853128531385314853158531685317853188531985320853218532285323853248532585326853278532885329853308533185332853338533485335853368533785338853398534085341853428534385344853458534685347853488534985350853518535285353853548535585356853578535885359853608536185362853638536485365853668536785368853698537085371853728537385374853758537685377853788537985380853818538285383853848538585386853878538885389853908539185392853938539485395853968539785398853998540085401854028540385404854058540685407854088540985410854118541285413854148541585416854178541885419854208542185422854238542485425854268542785428854298543085431854328543385434854358543685437854388543985440854418544285443854448544585446854478544885449854508545185452854538545485455854568545785458854598546085461854628546385464854658546685467854688546985470854718547285473854748547585476854778547885479854808548185482854838548485485854868548785488854898549085491854928549385494854958549685497854988549985500855018550285503855048550585506855078550885509855108551185512855138551485515855168551785518855198552085521855228552385524855258552685527855288552985530855318553285533855348553585536855378553885539855408554185542855438554485545855468554785548855498555085551855528555385554855558555685557855588555985560855618556285563855648556585566855678556885569855708557185572855738557485575855768557785578855798558085581855828558385584855858558685587855888558985590855918559285593855948559585596855978559885599856008560185602856038560485605856068560785608856098561085611856128561385614856158561685617856188561985620856218562285623856248562585626856278562885629856308563185632856338563485635856368563785638856398564085641856428564385644856458564685647856488564985650856518565285653856548565585656856578565885659856608566185662856638566485665856668566785668856698567085671856728567385674856758567685677856788567985680856818568285683856848568585686856878568885689856908569185692856938569485695856968569785698856998570085701857028570385704857058570685707857088570985710857118571285713857148571585716857178571885719857208572185722857238572485725857268572785728857298573085731857328573385734857358573685737857388573985740857418574285743857448574585746857478574885749857508575185752857538575485755857568575785758857598576085761857628576385764857658576685767857688576985770857718577285773857748577585776857778577885779857808578185782857838578485785857868578785788857898579085791857928579385794857958579685797857988579985800858018580285803858048580585806858078580885809858108581185812858138581485815858168581785818858198582085821858228582385824858258582685827858288582985830858318583285833858348583585836858378583885839858408584185842858438584485845858468584785848858498585085851858528585385854858558585685857858588585985860858618586285863858648586585866858678586885869858708587185872858738587485875858768587785878858798588085881858828588385884858858588685887858888588985890858918589285893858948589585896858978589885899859008590185902859038590485905859068590785908859098591085911859128591385914859158591685917859188591985920859218592285923859248592585926859278592885929859308593185932859338593485935859368593785938859398594085941859428594385944859458594685947859488594985950859518595285953859548595585956859578595885959859608596185962859638596485965859668596785968859698597085971859728597385974859758597685977859788597985980859818598285983859848598585986859878598885989859908599185992859938599485995859968599785998859998600086001860028600386004860058600686007860088600986010860118601286013860148601586016860178601886019860208602186022860238602486025860268602786028860298603086031860328603386034860358603686037860388603986040860418604286043860448604586046860478604886049860508605186052860538605486055860568605786058860598606086061860628606386064860658606686067860688606986070860718607286073860748607586076860778607886079860808608186082860838608486085860868608786088860898609086091860928609386094860958609686097860988609986100861018610286103861048610586106861078610886109861108611186112861138611486115861168611786118861198612086121861228612386124861258612686127861288612986130861318613286133861348613586136861378613886139861408614186142861438614486145861468614786148861498615086151861528615386154861558615686157861588615986160861618616286163861648616586166861678616886169861708617186172861738617486175861768617786178861798618086181861828618386184861858618686187861888618986190861918619286193861948619586196861978619886199862008620186202862038620486205862068620786208862098621086211862128621386214862158621686217862188621986220862218622286223862248622586226862278622886229862308623186232862338623486235862368623786238862398624086241862428624386244862458624686247862488624986250862518625286253862548625586256862578625886259862608626186262862638626486265862668626786268862698627086271862728627386274862758627686277862788627986280862818628286283862848628586286862878628886289862908629186292862938629486295862968629786298862998630086301863028630386304863058630686307863088630986310863118631286313863148631586316863178631886319863208632186322863238632486325863268632786328863298633086331863328633386334863358633686337863388633986340863418634286343863448634586346863478634886349863508635186352863538635486355863568635786358863598636086361863628636386364863658636686367863688636986370863718637286373863748637586376863778637886379863808638186382863838638486385863868638786388863898639086391863928639386394863958639686397863988639986400864018640286403864048640586406864078640886409864108641186412864138641486415864168641786418864198642086421864228642386424864258642686427864288642986430864318643286433864348643586436864378643886439864408644186442864438644486445864468644786448864498645086451864528645386454864558645686457864588645986460864618646286463864648646586466864678646886469864708647186472864738647486475864768647786478864798648086481864828648386484864858648686487864888648986490864918649286493864948649586496864978649886499865008650186502865038650486505865068650786508865098651086511865128651386514865158651686517865188651986520865218652286523865248652586526865278652886529865308653186532865338653486535865368653786538865398654086541865428654386544865458654686547865488654986550865518655286553865548655586556865578655886559865608656186562865638656486565865668656786568865698657086571865728657386574865758657686577865788657986580865818658286583865848658586586865878658886589865908659186592865938659486595865968659786598865998660086601866028660386604866058660686607866088660986610866118661286613866148661586616866178661886619866208662186622866238662486625866268662786628866298663086631866328663386634866358663686637866388663986640866418664286643866448664586646866478664886649866508665186652866538665486655866568665786658866598666086661866628666386664866658666686667866688666986670866718667286673866748667586676866778667886679866808668186682866838668486685866868668786688866898669086691866928669386694866958669686697866988669986700867018670286703867048670586706867078670886709867108671186712867138671486715867168671786718867198672086721867228672386724867258672686727867288672986730867318673286733867348673586736867378673886739867408674186742867438674486745867468674786748867498675086751867528675386754867558675686757867588675986760867618676286763867648676586766867678676886769867708677186772867738677486775867768677786778867798678086781867828678386784867858678686787867888678986790867918679286793867948679586796867978679886799868008680186802868038680486805868068680786808868098681086811868128681386814868158681686817868188681986820868218682286823868248682586826868278682886829868308683186832868338683486835868368683786838868398684086841868428684386844868458684686847868488684986850868518685286853868548685586856868578685886859868608686186862868638686486865868668686786868868698687086871868728687386874868758687686877868788687986880868818688286883868848688586886868878688886889868908689186892868938689486895868968689786898868998690086901869028690386904869058690686907869088690986910869118691286913869148691586916869178691886919869208692186922869238692486925869268692786928869298693086931869328693386934869358693686937869388693986940869418694286943869448694586946869478694886949869508695186952869538695486955869568695786958869598696086961869628696386964869658696686967869688696986970869718697286973869748697586976869778697886979869808698186982869838698486985869868698786988869898699086991869928699386994869958699686997869988699987000870018700287003870048700587006870078700887009870108701187012870138701487015870168701787018870198702087021870228702387024870258702687027870288702987030870318703287033870348703587036870378703887039870408704187042870438704487045870468704787048870498705087051870528705387054870558705687057870588705987060870618706287063870648706587066870678706887069870708707187072870738707487075870768707787078870798708087081870828708387084870858708687087870888708987090870918709287093870948709587096870978709887099871008710187102871038710487105871068710787108871098711087111871128711387114871158711687117871188711987120871218712287123871248712587126871278712887129871308713187132871338713487135871368713787138871398714087141871428714387144871458714687147871488714987150871518715287153871548715587156871578715887159871608716187162871638716487165871668716787168871698717087171871728717387174871758717687177871788717987180871818718287183871848718587186871878718887189871908719187192871938719487195871968719787198871998720087201872028720387204872058720687207872088720987210872118721287213872148721587216872178721887219872208722187222872238722487225872268722787228872298723087231872328723387234872358723687237872388723987240872418724287243872448724587246872478724887249872508725187252872538725487255872568725787258872598726087261872628726387264872658726687267872688726987270872718727287273872748727587276872778727887279872808728187282872838728487285872868728787288872898729087291872928729387294872958729687297872988729987300873018730287303873048730587306873078730887309873108731187312873138731487315873168731787318873198732087321873228732387324873258732687327873288732987330873318733287333873348733587336873378733887339873408734187342873438734487345873468734787348873498735087351873528735387354873558735687357873588735987360873618736287363873648736587366873678736887369873708737187372873738737487375873768737787378873798738087381873828738387384873858738687387873888738987390873918739287393873948739587396873978739887399874008740187402874038740487405874068740787408874098741087411874128741387414874158741687417874188741987420874218742287423874248742587426874278742887429874308743187432874338743487435874368743787438874398744087441874428744387444874458744687447874488744987450874518745287453874548745587456874578745887459874608746187462874638746487465874668746787468874698747087471874728747387474874758747687477874788747987480874818748287483874848748587486874878748887489874908749187492874938749487495874968749787498874998750087501875028750387504875058750687507875088750987510875118751287513875148751587516875178751887519875208752187522875238752487525875268752787528875298753087531875328753387534875358753687537875388753987540875418754287543875448754587546875478754887549875508755187552875538755487555875568755787558875598756087561875628756387564875658756687567875688756987570875718757287573875748757587576875778757887579875808758187582875838758487585875868758787588875898759087591875928759387594875958759687597875988759987600876018760287603876048760587606876078760887609876108761187612876138761487615876168761787618876198762087621876228762387624876258762687627876288762987630876318763287633876348763587636876378763887639876408764187642876438764487645876468764787648876498765087651876528765387654876558765687657876588765987660876618766287663876648766587666876678766887669876708767187672876738767487675876768767787678876798768087681876828768387684876858768687687876888768987690876918769287693876948769587696876978769887699877008770187702877038770487705877068770787708877098771087711877128771387714877158771687717877188771987720877218772287723877248772587726877278772887729877308773187732877338773487735877368773787738877398774087741877428774387744877458774687747877488774987750877518775287753877548775587756877578775887759877608776187762877638776487765877668776787768877698777087771877728777387774877758777687777877788777987780877818778287783877848778587786877878778887789877908779187792877938779487795877968779787798877998780087801878028780387804878058780687807878088780987810878118781287813878148781587816878178781887819878208782187822878238782487825878268782787828878298783087831878328783387834878358783687837878388783987840878418784287843878448784587846878478784887849878508785187852878538785487855878568785787858878598786087861878628786387864878658786687867878688786987870878718787287873878748787587876878778787887879878808788187882878838788487885878868788787888878898789087891878928789387894878958789687897878988789987900879018790287903879048790587906879078790887909879108791187912879138791487915879168791787918879198792087921879228792387924879258792687927879288792987930879318793287933879348793587936879378793887939879408794187942879438794487945879468794787948879498795087951879528795387954879558795687957879588795987960879618796287963879648796587966879678796887969879708797187972879738797487975879768797787978879798798087981879828798387984879858798687987879888798987990879918799287993879948799587996879978799887999880008800188002880038800488005880068800788008880098801088011880128801388014880158801688017880188801988020880218802288023880248802588026880278802888029880308803188032880338803488035880368803788038880398804088041880428804388044880458804688047880488804988050880518805288053880548805588056880578805888059880608806188062880638806488065880668806788068880698807088071880728807388074880758807688077880788807988080880818808288083880848808588086880878808888089880908809188092880938809488095880968809788098880998810088101881028810388104881058810688107881088810988110881118811288113881148811588116881178811888119881208812188122881238812488125881268812788128881298813088131881328813388134881358813688137881388813988140881418814288143881448814588146881478814888149881508815188152881538815488155881568815788158881598816088161881628816388164881658816688167881688816988170881718817288173881748817588176881778817888179881808818188182881838818488185881868818788188881898819088191881928819388194881958819688197881988819988200882018820288203882048820588206882078820888209882108821188212882138821488215882168821788218882198822088221882228822388224882258822688227882288822988230882318823288233882348823588236882378823888239882408824188242882438824488245882468824788248882498825088251882528825388254882558825688257882588825988260882618826288263882648826588266882678826888269882708827188272882738827488275882768827788278882798828088281882828828388284882858828688287882888828988290882918829288293882948829588296882978829888299883008830188302883038830488305883068830788308883098831088311883128831388314883158831688317883188831988320883218832288323883248832588326883278832888329883308833188332883338833488335883368833788338883398834088341883428834388344883458834688347883488834988350883518835288353883548835588356883578835888359883608836188362883638836488365883668836788368883698837088371883728837388374883758837688377883788837988380883818838288383883848838588386883878838888389883908839188392883938839488395883968839788398883998840088401884028840388404884058840688407884088840988410884118841288413884148841588416884178841888419884208842188422884238842488425884268842788428884298843088431884328843388434884358843688437884388843988440884418844288443884448844588446884478844888449884508845188452884538845488455884568845788458884598846088461884628846388464884658846688467884688846988470884718847288473884748847588476884778847888479884808848188482884838848488485884868848788488884898849088491884928849388494884958849688497884988849988500885018850288503885048850588506885078850888509885108851188512885138851488515885168851788518885198852088521885228852388524885258852688527885288852988530885318853288533885348853588536885378853888539885408854188542885438854488545885468854788548885498855088551885528855388554885558855688557885588855988560885618856288563885648856588566885678856888569885708857188572885738857488575885768857788578885798858088581885828858388584885858858688587885888858988590885918859288593885948859588596885978859888599886008860188602886038860488605886068860788608886098861088611886128861388614886158861688617886188861988620886218862288623886248862588626886278862888629886308863188632886338863488635886368863788638886398864088641886428864388644886458864688647886488864988650886518865288653886548865588656886578865888659886608866188662886638866488665886668866788668886698867088671886728867388674886758867688677886788867988680886818868288683886848868588686886878868888689886908869188692886938869488695886968869788698886998870088701887028870388704887058870688707887088870988710887118871288713887148871588716887178871888719887208872188722887238872488725887268872788728887298873088731887328873388734887358873688737887388873988740887418874288743887448874588746887478874888749887508875188752887538875488755887568875788758887598876088761887628876388764887658876688767887688876988770887718877288773887748877588776887778877888779887808878188782887838878488785887868878788788887898879088791887928879388794887958879688797887988879988800888018880288803888048880588806888078880888809888108881188812888138881488815888168881788818888198882088821888228882388824888258882688827888288882988830888318883288833888348883588836888378883888839888408884188842888438884488845888468884788848888498885088851888528885388854888558885688857888588885988860888618886288863888648886588866888678886888869888708887188872888738887488875888768887788878888798888088881888828888388884888858888688887888888888988890888918889288893888948889588896888978889888899889008890188902889038890488905889068890788908889098891088911889128891388914889158891688917889188891988920889218892288923889248892588926889278892888929889308893188932889338893488935889368893788938889398894088941889428894388944889458894688947889488894988950889518895288953889548895588956889578895888959889608896188962889638896488965889668896788968889698897088971889728897388974889758897688977889788897988980889818898288983889848898588986889878898888989889908899188992889938899488995889968899788998889998900089001890028900389004890058900689007890088900989010890118901289013890148901589016890178901889019890208902189022890238902489025890268902789028890298903089031890328903389034890358903689037890388903989040890418904289043890448904589046890478904889049890508905189052890538905489055890568905789058890598906089061890628906389064890658906689067890688906989070890718907289073890748907589076890778907889079890808908189082890838908489085890868908789088890898909089091890928909389094890958909689097890988909989100891018910289103891048910589106891078910889109891108911189112891138911489115891168911789118891198912089121891228912389124891258912689127891288912989130891318913289133891348913589136891378913889139891408914189142891438914489145891468914789148891498915089151891528915389154891558915689157891588915989160891618916289163891648916589166891678916889169891708917189172891738917489175891768917789178891798918089181891828918389184891858918689187891888918989190891918919289193891948919589196891978919889199892008920189202892038920489205892068920789208892098921089211892128921389214892158921689217892188921989220892218922289223892248922589226892278922889229892308923189232892338923489235892368923789238892398924089241892428924389244892458924689247892488924989250892518925289253892548925589256892578925889259892608926189262892638926489265892668926789268892698927089271892728927389274892758927689277892788927989280892818928289283892848928589286892878928889289892908929189292892938929489295892968929789298892998930089301893028930389304893058930689307893088930989310893118931289313893148931589316893178931889319893208932189322893238932489325893268932789328893298933089331893328933389334893358933689337893388933989340893418934289343893448934589346893478934889349893508935189352893538935489355893568935789358893598936089361893628936389364893658936689367893688936989370893718937289373893748937589376893778937889379893808938189382893838938489385893868938789388893898939089391893928939389394893958939689397893988939989400894018940289403894048940589406894078940889409894108941189412894138941489415894168941789418894198942089421894228942389424894258942689427894288942989430894318943289433894348943589436894378943889439894408944189442894438944489445894468944789448894498945089451894528945389454894558945689457894588945989460894618946289463894648946589466894678946889469894708947189472894738947489475894768947789478894798948089481894828948389484894858948689487894888948989490894918949289493894948949589496894978949889499895008950189502895038950489505895068950789508895098951089511895128951389514895158951689517895188951989520895218952289523895248952589526895278952889529895308953189532895338953489535895368953789538895398954089541895428954389544895458954689547895488954989550895518955289553895548955589556895578955889559895608956189562895638956489565895668956789568895698957089571895728957389574895758957689577895788957989580895818958289583895848958589586895878958889589895908959189592895938959489595895968959789598895998960089601896028960389604896058960689607896088960989610896118961289613896148961589616896178961889619896208962189622896238962489625896268962789628896298963089631896328963389634896358963689637896388963989640896418964289643896448964589646896478964889649896508965189652896538965489655896568965789658896598966089661896628966389664896658966689667896688966989670896718967289673896748967589676896778967889679896808968189682896838968489685896868968789688896898969089691896928969389694896958969689697896988969989700897018970289703897048970589706897078970889709897108971189712897138971489715897168971789718897198972089721897228972389724897258972689727897288972989730897318973289733897348973589736897378973889739897408974189742897438974489745897468974789748897498975089751897528975389754897558975689757897588975989760897618976289763897648976589766897678976889769897708977189772897738977489775897768977789778897798978089781897828978389784897858978689787897888978989790897918979289793897948979589796897978979889799898008980189802898038980489805898068980789808898098981089811898128981389814898158981689817898188981989820898218982289823898248982589826898278982889829898308983189832898338983489835898368983789838898398984089841898428984389844898458984689847898488984989850898518985289853898548985589856898578985889859898608986189862898638986489865898668986789868898698987089871898728987389874898758987689877898788987989880898818988289883898848988589886898878988889889898908989189892898938989489895898968989789898898998990089901899028990389904899058990689907899088990989910899118991289913899148991589916899178991889919899208992189922899238992489925899268992789928899298993089931899328993389934899358993689937899388993989940899418994289943899448994589946899478994889949899508995189952899538995489955899568995789958899598996089961899628996389964899658996689967899688996989970899718997289973899748997589976899778997889979899808998189982899838998489985899868998789988899898999089991899928999389994899958999689997899988999990000900019000290003900049000590006900079000890009900109001190012900139001490015900169001790018900199002090021900229002390024900259002690027900289002990030900319003290033900349003590036900379003890039900409004190042900439004490045900469004790048900499005090051900529005390054900559005690057900589005990060900619006290063900649006590066900679006890069900709007190072900739007490075900769007790078900799008090081900829008390084900859008690087900889008990090900919009290093900949009590096900979009890099901009010190102901039010490105901069010790108901099011090111901129011390114901159011690117901189011990120901219012290123901249012590126901279012890129901309013190132901339013490135901369013790138901399014090141901429014390144901459014690147901489014990150901519015290153901549015590156901579015890159901609016190162901639016490165901669016790168901699017090171901729017390174901759017690177901789017990180901819018290183901849018590186901879018890189901909019190192901939019490195901969019790198901999020090201902029020390204902059020690207902089020990210902119021290213902149021590216902179021890219902209022190222902239022490225902269022790228902299023090231902329023390234902359023690237902389023990240902419024290243902449024590246902479024890249902509025190252902539025490255902569025790258902599026090261902629026390264902659026690267902689026990270902719027290273902749027590276902779027890279902809028190282902839028490285902869028790288902899029090291902929029390294902959029690297902989029990300903019030290303903049030590306903079030890309903109031190312903139031490315903169031790318903199032090321903229032390324903259032690327903289032990330903319033290333903349033590336903379033890339903409034190342903439034490345903469034790348903499035090351903529035390354903559035690357903589035990360903619036290363903649036590366903679036890369903709037190372903739037490375903769037790378903799038090381903829038390384903859038690387903889038990390903919039290393903949039590396903979039890399904009040190402904039040490405904069040790408904099041090411904129041390414904159041690417904189041990420904219042290423904249042590426904279042890429904309043190432904339043490435904369043790438904399044090441904429044390444904459044690447904489044990450904519045290453904549045590456904579045890459904609046190462904639046490465904669046790468904699047090471904729047390474904759047690477904789047990480904819048290483904849048590486904879048890489904909049190492904939049490495904969049790498904999050090501905029050390504905059050690507905089050990510905119051290513905149051590516905179051890519905209052190522905239052490525905269052790528905299053090531905329053390534905359053690537905389053990540905419054290543905449054590546905479054890549905509055190552905539055490555905569055790558905599056090561905629056390564905659056690567905689056990570905719057290573905749057590576905779057890579905809058190582905839058490585905869058790588905899059090591905929059390594905959059690597905989059990600906019060290603906049060590606906079060890609906109061190612906139061490615906169061790618906199062090621906229062390624906259062690627906289062990630906319063290633906349063590636906379063890639906409064190642906439064490645906469064790648906499065090651906529065390654906559065690657906589065990660906619066290663906649066590666906679066890669906709067190672906739067490675906769067790678906799068090681906829068390684906859068690687906889068990690906919069290693906949069590696906979069890699907009070190702907039070490705907069070790708907099071090711907129071390714907159071690717907189071990720907219072290723907249072590726907279072890729907309073190732907339073490735907369073790738907399074090741907429074390744907459074690747907489074990750907519075290753907549075590756907579075890759907609076190762907639076490765907669076790768907699077090771907729077390774907759077690777907789077990780907819078290783907849078590786907879078890789907909079190792907939079490795907969079790798907999080090801908029080390804908059080690807908089080990810908119081290813908149081590816908179081890819908209082190822908239082490825908269082790828908299083090831908329083390834908359083690837908389083990840908419084290843908449084590846908479084890849908509085190852908539085490855908569085790858908599086090861908629086390864908659086690867908689086990870908719087290873908749087590876908779087890879908809088190882908839088490885908869088790888908899089090891908929089390894908959089690897908989089990900909019090290903909049090590906909079090890909909109091190912909139091490915909169091790918909199092090921909229092390924909259092690927909289092990930909319093290933909349093590936909379093890939909409094190942909439094490945909469094790948909499095090951909529095390954909559095690957909589095990960909619096290963909649096590966909679096890969909709097190972909739097490975909769097790978909799098090981909829098390984909859098690987909889098990990909919099290993909949099590996909979099890999910009100191002910039100491005910069100791008910099101091011910129101391014910159101691017910189101991020910219102291023910249102591026910279102891029910309103191032910339103491035910369103791038910399104091041910429104391044910459104691047910489104991050910519105291053910549105591056910579105891059910609106191062910639106491065910669106791068910699107091071910729107391074910759107691077910789107991080910819108291083910849108591086910879108891089910909109191092910939109491095910969109791098910999110091101911029110391104911059110691107911089110991110911119111291113911149111591116911179111891119911209112191122911239112491125911269112791128911299113091131911329113391134911359113691137911389113991140911419114291143911449114591146911479114891149911509115191152911539115491155911569115791158911599116091161911629116391164911659116691167911689116991170911719117291173911749117591176911779117891179911809118191182911839118491185911869118791188911899119091191911929119391194911959119691197911989119991200912019120291203912049120591206912079120891209912109121191212912139121491215912169121791218912199122091221912229122391224912259122691227912289122991230912319123291233912349123591236912379123891239912409124191242912439124491245912469124791248912499125091251912529125391254912559125691257912589125991260912619126291263912649126591266912679126891269912709127191272912739127491275912769127791278912799128091281912829128391284912859128691287912889128991290912919129291293912949129591296912979129891299913009130191302913039130491305913069130791308913099131091311913129131391314913159131691317913189131991320913219132291323913249132591326913279132891329913309133191332913339133491335913369133791338913399134091341913429134391344913459134691347913489134991350913519135291353913549135591356913579135891359913609136191362913639136491365913669136791368913699137091371913729137391374913759137691377913789137991380913819138291383913849138591386913879138891389913909139191392913939139491395913969139791398913999140091401914029140391404914059140691407914089140991410914119141291413914149141591416914179141891419914209142191422914239142491425914269142791428914299143091431914329143391434914359143691437914389143991440914419144291443914449144591446914479144891449914509145191452914539145491455914569145791458914599146091461914629146391464914659146691467914689146991470914719147291473914749147591476914779147891479914809148191482914839148491485914869148791488914899149091491914929149391494914959149691497914989149991500915019150291503915049150591506915079150891509915109151191512915139151491515915169151791518915199152091521915229152391524915259152691527915289152991530915319153291533915349153591536915379153891539915409154191542915439154491545915469154791548915499155091551915529155391554915559155691557915589155991560915619156291563915649156591566915679156891569915709157191572915739157491575915769157791578915799158091581915829158391584915859158691587915889158991590915919159291593915949159591596915979159891599916009160191602916039160491605916069160791608916099161091611916129161391614916159161691617916189161991620916219162291623916249162591626916279162891629916309163191632916339163491635916369163791638916399164091641916429164391644916459164691647916489164991650916519165291653916549165591656916579165891659916609166191662916639166491665916669166791668916699167091671916729167391674916759167691677916789167991680916819168291683916849168591686916879168891689916909169191692916939169491695916969169791698916999170091701917029170391704917059170691707917089170991710917119171291713917149171591716917179171891719917209172191722917239172491725917269172791728917299173091731917329173391734917359173691737917389173991740917419174291743917449174591746917479174891749917509175191752917539175491755917569175791758917599176091761917629176391764917659176691767917689176991770917719177291773917749177591776917779177891779917809178191782917839178491785917869178791788917899179091791917929179391794917959179691797917989179991800918019180291803918049180591806918079180891809918109181191812918139181491815918169181791818918199182091821918229182391824918259182691827918289182991830918319183291833918349183591836918379183891839918409184191842918439184491845918469184791848918499185091851918529185391854918559185691857918589185991860918619186291863918649186591866918679186891869918709187191872918739187491875918769187791878918799188091881918829188391884918859188691887918889188991890918919189291893918949189591896918979189891899919009190191902919039190491905919069190791908919099191091911919129191391914919159191691917919189191991920919219192291923919249192591926919279192891929919309193191932919339193491935919369193791938919399194091941919429194391944919459194691947919489194991950919519195291953919549195591956919579195891959919609196191962919639196491965919669196791968919699197091971919729197391974919759197691977919789197991980919819198291983919849198591986919879198891989919909199191992919939199491995919969199791998919999200092001920029200392004920059200692007920089200992010920119201292013920149201592016920179201892019920209202192022920239202492025920269202792028920299203092031920329203392034920359203692037920389203992040920419204292043920449204592046920479204892049920509205192052920539205492055920569205792058920599206092061920629206392064920659206692067920689206992070920719207292073920749207592076920779207892079920809208192082920839208492085920869208792088920899209092091920929209392094920959209692097920989209992100921019210292103921049210592106921079210892109921109211192112921139211492115921169211792118921199212092121921229212392124921259212692127921289212992130921319213292133921349213592136921379213892139921409214192142921439214492145921469214792148921499215092151921529215392154921559215692157921589215992160921619216292163921649216592166921679216892169921709217192172921739217492175921769217792178921799218092181921829218392184921859218692187921889218992190921919219292193921949219592196921979219892199922009220192202922039220492205922069220792208922099221092211922129221392214922159221692217922189221992220922219222292223922249222592226922279222892229922309223192232922339223492235922369223792238922399224092241922429224392244922459224692247922489224992250922519225292253922549225592256922579225892259922609226192262922639226492265922669226792268922699227092271922729227392274922759227692277922789227992280922819228292283922849228592286922879228892289922909229192292922939229492295922969229792298922999230092301923029230392304923059230692307923089230992310923119231292313923149231592316923179231892319923209232192322923239232492325923269232792328923299233092331923329233392334923359233692337923389233992340923419234292343923449234592346923479234892349923509235192352923539235492355923569235792358923599236092361923629236392364923659236692367923689236992370923719237292373923749237592376923779237892379923809238192382923839238492385923869238792388923899239092391923929239392394923959239692397923989239992400924019240292403924049240592406924079240892409924109241192412924139241492415924169241792418924199242092421924229242392424924259242692427924289242992430924319243292433924349243592436924379243892439924409244192442924439244492445924469244792448924499245092451924529245392454924559245692457924589245992460924619246292463924649246592466924679246892469924709247192472924739247492475924769247792478924799248092481924829248392484924859248692487924889248992490924919249292493924949249592496924979249892499925009250192502925039250492505925069250792508925099251092511925129251392514925159251692517925189251992520925219252292523925249252592526925279252892529925309253192532925339253492535925369253792538925399254092541925429254392544925459254692547925489254992550925519255292553925549255592556925579255892559925609256192562925639256492565925669256792568925699257092571925729257392574925759257692577925789257992580925819258292583925849258592586925879258892589925909259192592925939259492595925969259792598925999260092601926029260392604926059260692607926089260992610926119261292613926149261592616926179261892619926209262192622926239262492625926269262792628926299263092631926329263392634926359263692637926389263992640926419264292643926449264592646926479264892649926509265192652926539265492655926569265792658926599266092661926629266392664926659266692667926689266992670926719267292673926749267592676926779267892679926809268192682926839268492685926869268792688926899269092691926929269392694926959269692697926989269992700927019270292703927049270592706927079270892709927109271192712927139271492715927169271792718927199272092721927229272392724927259272692727927289272992730927319273292733927349273592736927379273892739927409274192742927439274492745927469274792748927499275092751927529275392754927559275692757927589275992760927619276292763927649276592766927679276892769927709277192772927739277492775927769277792778927799278092781927829278392784927859278692787927889278992790927919279292793927949279592796927979279892799928009280192802928039280492805928069280792808928099281092811928129281392814928159281692817928189281992820928219282292823928249282592826928279282892829928309283192832928339283492835928369283792838928399284092841928429284392844928459284692847928489284992850928519285292853928549285592856928579285892859928609286192862928639286492865928669286792868928699287092871928729287392874928759287692877928789287992880928819288292883928849288592886928879288892889928909289192892928939289492895928969289792898928999290092901929029290392904929059290692907929089290992910929119291292913929149291592916929179291892919929209292192922929239292492925929269292792928929299293092931929329293392934929359293692937929389293992940929419294292943929449294592946929479294892949929509295192952929539295492955929569295792958929599296092961929629296392964929659296692967929689296992970929719297292973929749297592976929779297892979929809298192982929839298492985929869298792988929899299092991929929299392994929959299692997929989299993000930019300293003930049300593006930079300893009930109301193012930139301493015930169301793018930199302093021930229302393024930259302693027930289302993030930319303293033930349303593036930379303893039930409304193042930439304493045930469304793048930499305093051930529305393054930559305693057930589305993060930619306293063930649306593066930679306893069930709307193072930739307493075930769307793078930799308093081930829308393084930859308693087930889308993090930919309293093930949309593096930979309893099931009310193102931039310493105931069310793108931099311093111931129311393114931159311693117931189311993120931219312293123931249312593126931279312893129931309313193132931339313493135931369313793138931399314093141931429314393144931459314693147931489314993150931519315293153931549315593156931579315893159931609316193162931639316493165931669316793168931699317093171931729317393174931759317693177931789317993180931819318293183931849318593186931879318893189931909319193192931939319493195931969319793198931999320093201932029320393204932059320693207932089320993210932119321293213932149321593216932179321893219932209322193222932239322493225932269322793228932299323093231932329323393234932359323693237932389323993240932419324293243932449324593246932479324893249932509325193252932539325493255932569325793258932599326093261932629326393264932659326693267932689326993270932719327293273932749327593276932779327893279932809328193282932839328493285932869328793288932899329093291932929329393294932959329693297932989329993300933019330293303933049330593306933079330893309933109331193312933139331493315933169331793318933199332093321933229332393324933259332693327933289332993330933319333293333933349333593336933379333893339933409334193342933439334493345933469334793348933499335093351933529335393354933559335693357933589335993360933619336293363933649336593366933679336893369933709337193372933739337493375933769337793378933799338093381933829338393384933859338693387933889338993390933919339293393933949339593396933979339893399934009340193402934039340493405934069340793408934099341093411934129341393414934159341693417934189341993420934219342293423934249342593426934279342893429934309343193432934339343493435934369343793438934399344093441934429344393444934459344693447934489344993450934519345293453934549345593456934579345893459934609346193462934639346493465934669346793468934699347093471934729347393474934759347693477934789347993480934819348293483934849348593486934879348893489934909349193492934939349493495934969349793498934999350093501935029350393504935059350693507935089350993510935119351293513935149351593516935179351893519935209352193522935239352493525935269352793528935299353093531935329353393534935359353693537935389353993540935419354293543935449354593546935479354893549935509355193552935539355493555935569355793558935599356093561935629356393564935659356693567935689356993570935719357293573935749357593576935779357893579935809358193582935839358493585935869358793588935899359093591935929359393594935959359693597935989359993600936019360293603936049360593606936079360893609936109361193612936139361493615936169361793618936199362093621936229362393624936259362693627936289362993630936319363293633936349363593636936379363893639936409364193642936439364493645936469364793648936499365093651936529365393654936559365693657936589365993660936619366293663936649366593666936679366893669936709367193672936739367493675936769367793678936799368093681936829368393684936859368693687936889368993690936919369293693936949369593696936979369893699937009370193702937039370493705937069370793708937099371093711937129371393714937159371693717937189371993720937219372293723937249372593726937279372893729937309373193732937339373493735937369373793738937399374093741937429374393744937459374693747937489374993750937519375293753937549375593756937579375893759937609376193762937639376493765937669376793768937699377093771937729377393774937759377693777937789377993780937819378293783937849378593786937879378893789937909379193792937939379493795937969379793798937999380093801938029380393804938059380693807938089380993810938119381293813938149381593816938179381893819938209382193822938239382493825938269382793828938299383093831938329383393834938359383693837938389383993840938419384293843938449384593846938479384893849938509385193852938539385493855938569385793858938599386093861938629386393864938659386693867938689386993870938719387293873938749387593876938779387893879938809388193882938839388493885938869388793888938899389093891938929389393894938959389693897938989389993900939019390293903939049390593906939079390893909939109391193912939139391493915939169391793918939199392093921939229392393924939259392693927939289392993930939319393293933939349393593936939379393893939939409394193942939439394493945939469394793948939499395093951939529395393954939559395693957939589395993960939619396293963939649396593966939679396893969939709397193972939739397493975939769397793978939799398093981939829398393984939859398693987939889398993990939919399293993939949399593996939979399893999940009400194002940039400494005940069400794008940099401094011940129401394014940159401694017940189401994020940219402294023940249402594026940279402894029940309403194032940339403494035940369403794038940399404094041940429404394044940459404694047940489404994050940519405294053940549405594056940579405894059940609406194062940639406494065940669406794068940699407094071940729407394074940759407694077940789407994080940819408294083940849408594086940879408894089940909409194092940939409494095940969409794098940999410094101941029410394104941059410694107941089410994110941119411294113941149411594116941179411894119941209412194122941239412494125941269412794128941299413094131941329413394134941359413694137941389413994140941419414294143941449414594146941479414894149941509415194152941539415494155941569415794158941599416094161941629416394164941659416694167941689416994170941719417294173941749417594176941779417894179941809418194182941839418494185941869418794188941899419094191941929419394194941959419694197941989419994200942019420294203942049420594206942079420894209942109421194212942139421494215942169421794218942199422094221942229422394224942259422694227942289422994230942319423294233942349423594236942379423894239942409424194242942439424494245942469424794248942499425094251942529425394254942559425694257942589425994260942619426294263942649426594266942679426894269942709427194272942739427494275942769427794278942799428094281942829428394284942859428694287942889428994290942919429294293942949429594296942979429894299943009430194302943039430494305943069430794308943099431094311943129431394314943159431694317943189431994320943219432294323943249432594326943279432894329943309433194332943339433494335943369433794338943399434094341943429434394344943459434694347943489434994350943519435294353943549435594356943579435894359943609436194362943639436494365943669436794368943699437094371943729437394374943759437694377943789437994380943819438294383943849438594386943879438894389943909439194392943939439494395943969439794398943999440094401944029440394404944059440694407944089440994410944119441294413944149441594416944179441894419944209442194422944239442494425944269442794428944299443094431944329443394434944359443694437944389443994440944419444294443944449444594446944479444894449944509445194452944539445494455944569445794458944599446094461944629446394464944659446694467944689446994470944719447294473944749447594476944779447894479944809448194482944839448494485944869448794488944899449094491944929449394494944959449694497944989449994500945019450294503945049450594506945079450894509945109451194512945139451494515945169451794518945199452094521945229452394524945259452694527945289452994530945319453294533945349453594536945379453894539945409454194542945439454494545945469454794548945499455094551945529455394554945559455694557945589455994560945619456294563945649456594566945679456894569945709457194572945739457494575945769457794578945799458094581945829458394584945859458694587945889458994590945919459294593945949459594596945979459894599946009460194602946039460494605946069460794608946099461094611946129461394614946159461694617946189461994620946219462294623946249462594626946279462894629946309463194632946339463494635946369463794638946399464094641946429464394644946459464694647946489464994650946519465294653946549465594656946579465894659946609466194662946639466494665946669466794668946699467094671946729467394674946759467694677946789467994680946819468294683946849468594686946879468894689946909469194692946939469494695946969469794698946999470094701947029470394704947059470694707947089470994710947119471294713947149471594716947179471894719947209472194722947239472494725947269472794728947299473094731947329473394734947359473694737947389473994740947419474294743947449474594746947479474894749947509475194752947539475494755947569475794758947599476094761947629476394764947659476694767947689476994770947719477294773947749477594776947779477894779947809478194782947839478494785947869478794788947899479094791947929479394794947959479694797947989479994800948019480294803948049480594806948079480894809948109481194812948139481494815948169481794818948199482094821948229482394824948259482694827948289482994830948319483294833948349483594836948379483894839948409484194842948439484494845948469484794848948499485094851948529485394854948559485694857948589485994860948619486294863948649486594866948679486894869948709487194872948739487494875948769487794878948799488094881948829488394884948859488694887948889488994890948919489294893948949489594896948979489894899949009490194902949039490494905949069490794908949099491094911949129491394914949159491694917949189491994920949219492294923949249492594926949279492894929949309493194932949339493494935949369493794938949399494094941949429494394944949459494694947949489494994950949519495294953949549495594956949579495894959949609496194962949639496494965949669496794968949699497094971949729497394974949759497694977949789497994980949819498294983949849498594986949879498894989949909499194992949939499494995949969499794998949999500095001950029500395004950059500695007950089500995010950119501295013950149501595016950179501895019950209502195022950239502495025950269502795028950299503095031950329503395034950359503695037950389503995040950419504295043950449504595046950479504895049950509505195052950539505495055950569505795058950599506095061950629506395064950659506695067950689506995070950719507295073950749507595076950779507895079950809508195082950839508495085950869508795088950899509095091950929509395094950959509695097950989509995100951019510295103951049510595106951079510895109951109511195112951139511495115951169511795118951199512095121951229512395124951259512695127951289512995130951319513295133951349513595136951379513895139951409514195142951439514495145951469514795148951499515095151951529515395154951559515695157951589515995160951619516295163951649516595166951679516895169951709517195172951739517495175951769517795178951799518095181951829518395184951859518695187951889518995190951919519295193951949519595196951979519895199952009520195202952039520495205952069520795208952099521095211952129521395214952159521695217952189521995220952219522295223952249522595226952279522895229952309523195232952339523495235952369523795238952399524095241952429524395244952459524695247952489524995250952519525295253952549525595256952579525895259952609526195262952639526495265952669526795268952699527095271952729527395274952759527695277952789527995280952819528295283952849528595286952879528895289952909529195292952939529495295952969529795298952999530095301953029530395304953059530695307953089530995310953119531295313953149531595316953179531895319953209532195322953239532495325953269532795328953299533095331953329533395334953359533695337953389533995340953419534295343953449534595346953479534895349953509535195352953539535495355953569535795358953599536095361953629536395364953659536695367953689536995370953719537295373953749537595376953779537895379953809538195382953839538495385953869538795388953899539095391953929539395394953959539695397953989539995400954019540295403954049540595406954079540895409954109541195412954139541495415954169541795418954199542095421954229542395424954259542695427954289542995430954319543295433954349543595436954379543895439954409544195442954439544495445954469544795448954499545095451954529545395454954559545695457954589545995460954619546295463954649546595466954679546895469954709547195472954739547495475954769547795478954799548095481954829548395484954859548695487954889548995490954919549295493954949549595496954979549895499955009550195502955039550495505955069550795508955099551095511955129551395514955159551695517955189551995520955219552295523955249552595526955279552895529955309553195532955339553495535955369553795538955399554095541955429554395544955459554695547955489554995550955519555295553955549555595556955579555895559955609556195562955639556495565955669556795568955699557095571955729557395574955759557695577955789557995580955819558295583955849558595586955879558895589955909559195592955939559495595955969559795598955999560095601956029560395604956059560695607956089560995610956119561295613956149561595616956179561895619956209562195622956239562495625956269562795628956299563095631956329563395634956359563695637956389563995640956419564295643956449564595646956479564895649956509565195652956539565495655956569565795658956599566095661956629566395664956659566695667956689566995670956719567295673956749567595676956779567895679956809568195682956839568495685956869568795688956899569095691956929569395694956959569695697956989569995700957019570295703957049570595706957079570895709957109571195712957139571495715957169571795718957199572095721957229572395724957259572695727957289572995730957319573295733957349573595736957379573895739957409574195742957439574495745957469574795748957499575095751957529575395754957559575695757957589575995760957619576295763957649576595766957679576895769957709577195772957739577495775957769577795778957799578095781957829578395784957859578695787957889578995790957919579295793957949579595796957979579895799958009580195802958039580495805958069580795808958099581095811958129581395814958159581695817958189581995820958219582295823958249582595826958279582895829958309583195832958339583495835958369583795838958399584095841958429584395844958459584695847958489584995850958519585295853958549585595856958579585895859958609586195862958639586495865958669586795868958699587095871958729587395874958759587695877958789587995880958819588295883958849588595886958879588895889958909589195892958939589495895958969589795898958999590095901959029590395904959059590695907959089590995910959119591295913959149591595916959179591895919959209592195922959239592495925959269592795928959299593095931959329593395934959359593695937959389593995940959419594295943959449594595946959479594895949959509595195952959539595495955959569595795958959599596095961959629596395964959659596695967959689596995970959719597295973959749597595976959779597895979959809598195982959839598495985959869598795988959899599095991959929599395994959959599695997959989599996000960019600296003960049600596006960079600896009960109601196012960139601496015960169601796018960199602096021960229602396024960259602696027960289602996030960319603296033960349603596036960379603896039960409604196042960439604496045960469604796048960499605096051960529605396054960559605696057960589605996060960619606296063960649606596066960679606896069960709607196072960739607496075960769607796078960799608096081960829608396084960859608696087960889608996090960919609296093960949609596096960979609896099961009610196102961039610496105961069610796108961099611096111961129611396114961159611696117961189611996120961219612296123961249612596126961279612896129961309613196132961339613496135961369613796138961399614096141961429614396144961459614696147961489614996150961519615296153961549615596156961579615896159961609616196162961639616496165961669616796168961699617096171961729617396174961759617696177961789617996180961819618296183961849618596186961879618896189961909619196192961939619496195961969619796198961999620096201962029620396204962059620696207962089620996210962119621296213962149621596216962179621896219962209622196222962239622496225962269622796228962299623096231962329623396234962359623696237962389623996240962419624296243962449624596246962479624896249962509625196252962539625496255962569625796258962599626096261962629626396264962659626696267962689626996270962719627296273962749627596276962779627896279962809628196282962839628496285962869628796288962899629096291962929629396294962959629696297962989629996300963019630296303963049630596306963079630896309963109631196312963139631496315963169631796318963199632096321963229632396324963259632696327963289632996330963319633296333963349633596336963379633896339963409634196342963439634496345963469634796348963499635096351963529635396354963559635696357963589635996360963619636296363963649636596366963679636896369963709637196372963739637496375963769637796378963799638096381963829638396384963859638696387963889638996390963919639296393963949639596396963979639896399964009640196402964039640496405964069640796408964099641096411964129641396414964159641696417964189641996420964219642296423964249642596426964279642896429964309643196432964339643496435964369643796438964399644096441964429644396444964459644696447964489644996450964519645296453964549645596456964579645896459964609646196462964639646496465964669646796468964699647096471964729647396474964759647696477964789647996480964819648296483964849648596486964879648896489964909649196492964939649496495964969649796498964999650096501965029650396504965059650696507965089650996510965119651296513965149651596516965179651896519965209652196522965239652496525965269652796528965299653096531965329653396534965359653696537965389653996540965419654296543965449654596546965479654896549965509655196552965539655496555965569655796558965599656096561965629656396564965659656696567965689656996570965719657296573965749657596576965779657896579965809658196582965839658496585965869658796588965899659096591965929659396594965959659696597965989659996600966019660296603966049660596606966079660896609966109661196612966139661496615966169661796618966199662096621966229662396624966259662696627966289662996630966319663296633966349663596636966379663896639966409664196642966439664496645966469664796648966499665096651966529665396654966559665696657966589665996660966619666296663966649666596666966679666896669966709667196672966739667496675966769667796678966799668096681966829668396684966859668696687966889668996690966919669296693966949669596696966979669896699967009670196702967039670496705967069670796708967099671096711967129671396714967159671696717967189671996720967219672296723967249672596726967279672896729967309673196732967339673496735967369673796738967399674096741967429674396744967459674696747967489674996750967519675296753967549675596756967579675896759967609676196762967639676496765967669676796768967699677096771967729677396774967759677696777967789677996780967819678296783967849678596786967879678896789967909679196792967939679496795967969679796798967999680096801968029680396804968059680696807968089680996810968119681296813968149681596816968179681896819968209682196822968239682496825968269682796828968299683096831968329683396834968359683696837968389683996840968419684296843968449684596846968479684896849968509685196852968539685496855968569685796858968599686096861968629686396864968659686696867968689686996870968719687296873968749687596876968779687896879968809688196882968839688496885968869688796888968899689096891968929689396894968959689696897968989689996900969019690296903969049690596906969079690896909969109691196912969139691496915969169691796918969199692096921969229692396924969259692696927969289692996930969319693296933969349693596936969379693896939969409694196942969439694496945969469694796948969499695096951969529695396954969559695696957969589695996960969619696296963969649696596966969679696896969969709697196972969739697496975969769697796978969799698096981969829698396984969859698696987969889698996990969919699296993969949699596996969979699896999970009700197002970039700497005970069700797008970099701097011970129701397014970159701697017970189701997020970219702297023970249702597026970279702897029970309703197032970339703497035970369703797038970399704097041970429704397044970459704697047970489704997050970519705297053970549705597056970579705897059970609706197062970639706497065970669706797068970699707097071970729707397074970759707697077970789707997080970819708297083970849708597086970879708897089970909709197092970939709497095970969709797098970999710097101971029710397104971059710697107971089710997110971119711297113971149711597116971179711897119971209712197122971239712497125971269712797128971299713097131971329713397134971359713697137971389713997140971419714297143971449714597146971479714897149971509715197152971539715497155971569715797158971599716097161971629716397164971659716697167971689716997170971719717297173971749717597176971779717897179971809718197182971839718497185971869718797188971899719097191971929719397194971959719697197971989719997200972019720297203972049720597206972079720897209972109721197212972139721497215972169721797218972199722097221972229722397224972259722697227972289722997230972319723297233972349723597236972379723897239972409724197242972439724497245972469724797248972499725097251972529725397254972559725697257972589725997260972619726297263972649726597266972679726897269972709727197272972739727497275972769727797278972799728097281972829728397284972859728697287972889728997290972919729297293972949729597296972979729897299973009730197302973039730497305973069730797308973099731097311973129731397314973159731697317973189731997320973219732297323973249732597326973279732897329973309733197332973339733497335973369733797338973399734097341973429734397344973459734697347973489734997350973519735297353973549735597356973579735897359973609736197362973639736497365973669736797368973699737097371973729737397374973759737697377973789737997380973819738297383973849738597386973879738897389973909739197392973939739497395973969739797398973999740097401974029740397404974059740697407974089740997410974119741297413974149741597416974179741897419974209742197422974239742497425974269742797428974299743097431974329743397434974359743697437974389743997440974419744297443974449744597446974479744897449974509745197452974539745497455974569745797458974599746097461974629746397464974659746697467974689746997470974719747297473974749747597476974779747897479974809748197482974839748497485974869748797488974899749097491974929749397494974959749697497974989749997500975019750297503975049750597506975079750897509975109751197512975139751497515975169751797518975199752097521975229752397524975259752697527975289752997530975319753297533975349753597536975379753897539975409754197542975439754497545975469754797548975499755097551975529755397554975559755697557975589755997560975619756297563975649756597566975679756897569975709757197572975739757497575975769757797578975799758097581975829758397584975859758697587975889758997590975919759297593975949759597596975979759897599976009760197602976039760497605976069760797608976099761097611976129761397614976159761697617976189761997620976219762297623976249762597626976279762897629976309763197632976339763497635976369763797638976399764097641976429764397644976459764697647976489764997650976519765297653976549765597656976579765897659976609766197662976639766497665976669766797668976699767097671976729767397674976759767697677976789767997680976819768297683976849768597686976879768897689976909769197692976939769497695976969769797698976999770097701977029770397704977059770697707977089770997710977119771297713977149771597716977179771897719977209772197722977239772497725977269772797728977299773097731977329773397734977359773697737977389773997740977419774297743977449774597746977479774897749977509775197752977539775497755977569775797758977599776097761977629776397764977659776697767977689776997770977719777297773977749777597776977779777897779977809778197782977839778497785977869778797788977899779097791977929779397794977959779697797977989779997800978019780297803978049780597806978079780897809978109781197812978139781497815978169781797818978199782097821978229782397824978259782697827978289782997830978319783297833978349783597836978379783897839978409784197842978439784497845978469784797848978499785097851978529785397854978559785697857978589785997860978619786297863978649786597866978679786897869978709787197872978739787497875978769787797878978799788097881978829788397884978859788697887978889788997890978919789297893978949789597896978979789897899979009790197902979039790497905979069790797908979099791097911979129791397914979159791697917979189791997920979219792297923979249792597926979279792897929979309793197932979339793497935979369793797938979399794097941979429794397944979459794697947979489794997950979519795297953979549795597956979579795897959979609796197962979639796497965979669796797968979699797097971979729797397974979759797697977979789797997980979819798297983979849798597986979879798897989979909799197992979939799497995979969799797998979999800098001980029800398004980059800698007980089800998010980119801298013980149801598016980179801898019980209802198022980239802498025980269802798028980299803098031980329803398034980359803698037980389803998040980419804298043980449804598046980479804898049980509805198052980539805498055980569805798058980599806098061980629806398064980659806698067980689806998070980719807298073980749807598076980779807898079980809808198082980839808498085980869808798088980899809098091980929809398094980959809698097980989809998100981019810298103981049810598106981079810898109981109811198112981139811498115981169811798118981199812098121981229812398124981259812698127981289812998130981319813298133981349813598136981379813898139981409814198142981439814498145981469814798148981499815098151981529815398154981559815698157981589815998160981619816298163981649816598166981679816898169981709817198172981739817498175981769817798178981799818098181981829818398184981859818698187981889818998190981919819298193981949819598196981979819898199982009820198202982039820498205982069820798208982099821098211982129821398214982159821698217982189821998220982219822298223982249822598226982279822898229982309823198232982339823498235982369823798238982399824098241982429824398244982459824698247982489824998250982519825298253982549825598256982579825898259982609826198262982639826498265982669826798268982699827098271982729827398274982759827698277982789827998280982819828298283982849828598286982879828898289982909829198292982939829498295982969829798298982999830098301983029830398304983059830698307983089830998310983119831298313983149831598316983179831898319983209832198322983239832498325983269832798328983299833098331983329833398334983359833698337983389833998340983419834298343983449834598346983479834898349983509835198352983539835498355983569835798358983599836098361983629836398364983659836698367983689836998370983719837298373983749837598376983779837898379983809838198382983839838498385983869838798388983899839098391983929839398394983959839698397983989839998400984019840298403984049840598406984079840898409984109841198412984139841498415984169841798418984199842098421984229842398424984259842698427984289842998430984319843298433984349843598436984379843898439984409844198442984439844498445984469844798448984499845098451984529845398454984559845698457984589845998460984619846298463984649846598466984679846898469984709847198472984739847498475984769847798478984799848098481984829848398484984859848698487984889848998490984919849298493984949849598496984979849898499985009850198502985039850498505985069850798508985099851098511985129851398514985159851698517985189851998520985219852298523985249852598526985279852898529985309853198532985339853498535985369853798538985399854098541985429854398544985459854698547985489854998550985519855298553985549855598556985579855898559985609856198562985639856498565985669856798568985699857098571985729857398574985759857698577985789857998580985819858298583985849858598586985879858898589985909859198592985939859498595985969859798598985999860098601986029860398604986059860698607986089860998610986119861298613986149861598616986179861898619986209862198622986239862498625986269862798628986299863098631986329863398634986359863698637986389863998640986419864298643986449864598646986479864898649986509865198652986539865498655986569865798658986599866098661986629866398664986659866698667986689866998670986719867298673986749867598676986779867898679986809868198682986839868498685986869868798688986899869098691986929869398694986959869698697986989869998700987019870298703987049870598706987079870898709987109871198712987139871498715987169871798718987199872098721987229872398724987259872698727987289872998730987319873298733987349873598736987379873898739987409874198742987439874498745987469874798748987499875098751987529875398754987559875698757987589875998760987619876298763987649876598766987679876898769987709877198772987739877498775987769877798778987799878098781987829878398784987859878698787987889878998790987919879298793987949879598796987979879898799988009880198802988039880498805988069880798808988099881098811988129881398814988159881698817988189881998820988219882298823988249882598826988279882898829988309883198832988339883498835988369883798838988399884098841988429884398844988459884698847988489884998850988519885298853988549885598856988579885898859988609886198862988639886498865988669886798868988699887098871988729887398874988759887698877988789887998880988819888298883988849888598886988879888898889988909889198892988939889498895988969889798898988999890098901989029890398904989059890698907989089890998910989119891298913989149891598916989179891898919989209892198922989239892498925989269892798928989299893098931989329893398934989359893698937989389893998940989419894298943989449894598946989479894898949989509895198952989539895498955989569895798958989599896098961989629896398964989659896698967989689896998970989719897298973989749897598976989779897898979989809898198982989839898498985989869898798988989899899098991989929899398994989959899698997989989899999000990019900299003990049900599006990079900899009990109901199012990139901499015990169901799018990199902099021990229902399024990259902699027990289902999030990319903299033990349903599036990379903899039990409904199042990439904499045990469904799048990499905099051990529905399054990559905699057990589905999060990619906299063990649906599066990679906899069990709907199072990739907499075990769907799078990799908099081990829908399084990859908699087990889908999090990919909299093990949909599096990979909899099991009910199102991039910499105991069910799108991099911099111991129911399114991159911699117991189911999120991219912299123991249912599126991279912899129991309913199132991339913499135991369913799138991399914099141991429914399144991459914699147991489914999150991519915299153991549915599156991579915899159991609916199162991639916499165991669916799168991699917099171991729917399174991759917699177991789917999180991819918299183991849918599186991879918899189991909919199192991939919499195991969919799198991999920099201992029920399204992059920699207992089920999210992119921299213992149921599216992179921899219992209922199222992239922499225992269922799228992299923099231992329923399234992359923699237992389923999240992419924299243992449924599246992479924899249992509925199252992539925499255992569925799258992599926099261992629926399264992659926699267992689926999270992719927299273992749927599276992779927899279992809928199282992839928499285992869928799288992899929099291992929929399294992959929699297992989929999300993019930299303993049930599306993079930899309993109931199312993139931499315993169931799318993199932099321993229932399324993259932699327993289932999330993319933299333993349933599336993379933899339993409934199342993439934499345993469934799348993499935099351993529935399354993559935699357993589935999360993619936299363993649936599366993679936899369993709937199372993739937499375993769937799378993799938099381993829938399384993859938699387993889938999390993919939299393993949939599396993979939899399994009940199402994039940499405994069940799408994099941099411994129941399414994159941699417994189941999420994219942299423994249942599426994279942899429994309943199432994339943499435994369943799438994399944099441994429944399444994459944699447994489944999450994519945299453994549945599456994579945899459994609946199462994639946499465994669946799468994699947099471994729947399474994759947699477994789947999480994819948299483994849948599486994879948899489994909949199492994939949499495994969949799498994999950099501995029950399504995059950699507995089950999510995119951299513995149951599516995179951899519995209952199522995239952499525995269952799528995299953099531995329953399534995359953699537995389953999540995419954299543995449954599546995479954899549995509955199552995539955499555995569955799558995599956099561995629956399564995659956699567995689956999570995719957299573995749957599576995779957899579995809958199582995839958499585995869958799588995899959099591995929959399594995959959699597995989959999600996019960299603996049960599606996079960899609996109961199612996139961499615996169961799618996199962099621996229962399624996259962699627996289962999630996319963299633996349963599636996379963899639996409964199642996439964499645996469964799648996499965099651996529965399654996559965699657996589965999660996619966299663996649966599666996679966899669996709967199672996739967499675996769967799678996799968099681996829968399684996859968699687996889968999690996919969299693996949969599696996979969899699997009970199702997039970499705997069970799708997099971099711997129971399714997159971699717997189971999720997219972299723997249972599726997279972899729997309973199732997339973499735997369973799738997399974099741997429974399744997459974699747997489974999750997519975299753997549975599756997579975899759997609976199762997639976499765997669976799768997699977099771997729977399774997759977699777997789977999780997819978299783997849978599786997879978899789997909979199792997939979499795997969979799798997999980099801998029980399804998059980699807998089980999810998119981299813998149981599816998179981899819998209982199822998239982499825998269982799828998299983099831998329983399834998359983699837998389983999840998419984299843998449984599846998479984899849998509985199852998539985499855998569985799858998599986099861998629986399864998659986699867998689986999870998719987299873998749987599876998779987899879998809988199882998839988499885998869988799888998899989099891998929989399894998959989699897998989989999900999019990299903999049990599906999079990899909999109991199912999139991499915999169991799918999199992099921999229992399924999259992699927999289992999930999319993299933999349993599936999379993899939999409994199942999439994499945999469994799948999499995099951999529995399954999559995699957999589995999960999619996299963999649996599966999679996899969999709997199972999739997499975999769997799978999799998099981999829998399984999859998699987999889998999990999919999299993999949999599996999979999899999100000100001100002100003100004100005100006100007100008100009100010100011100012100013100014100015100016100017100018100019100020100021100022100023100024100025100026100027100028100029100030100031100032100033100034100035100036100037100038100039100040100041100042100043100044100045100046100047100048100049100050100051100052100053100054100055100056100057100058100059100060100061100062100063100064100065100066100067100068100069100070100071100072100073100074100075100076100077100078100079100080100081100082100083100084100085100086100087100088100089100090100091100092100093100094100095100096100097100098100099100100100101100102100103100104100105100106100107100108100109100110100111100112100113100114100115100116100117100118100119100120100121100122100123100124100125100126100127100128100129100130100131100132100133100134100135100136100137100138100139100140100141100142100143100144100145100146100147100148100149100150100151100152100153100154100155100156100157100158100159100160100161100162100163100164100165100166100167100168100169100170100171100172100173100174100175100176100177100178100179100180100181100182100183100184100185100186100187100188100189100190100191100192100193100194100195100196100197100198100199100200100201100202100203100204100205100206100207100208100209100210100211100212100213100214100215100216100217100218100219100220100221100222100223100224100225100226100227100228100229100230100231100232100233100234100235100236100237100238100239100240100241100242100243100244100245100246100247100248100249100250100251100252100253100254100255100256100257100258100259100260100261100262100263100264100265100266100267100268100269100270100271100272100273100274100275100276100277100278100279100280100281100282100283100284100285100286100287100288100289100290100291100292100293100294100295100296100297100298100299100300100301100302100303100304100305100306100307100308100309100310100311100312100313100314100315100316100317100318100319100320100321100322100323100324100325100326100327100328100329100330100331100332100333100334100335100336100337100338100339100340100341100342100343100344100345100346100347100348100349100350100351100352100353100354100355100356100357100358100359100360100361100362100363100364100365100366100367100368100369100370100371100372100373100374100375100376100377100378100379100380100381100382100383100384100385100386100387100388100389100390100391100392100393100394100395100396100397100398100399100400100401100402100403100404100405100406100407100408100409100410100411100412100413100414100415100416100417100418100419100420100421100422100423100424100425100426100427100428100429100430100431100432100433100434100435100436100437100438100439100440100441100442100443100444100445100446100447100448100449100450100451100452100453100454100455100456100457100458100459100460100461100462100463100464100465100466100467100468100469100470100471100472100473100474100475100476100477100478100479100480100481100482100483100484100485100486100487100488100489100490100491100492100493100494100495100496100497100498100499100500100501100502100503100504100505100506100507100508100509100510100511100512100513100514100515100516100517100518100519100520100521100522100523100524100525100526100527100528100529100530100531100532100533100534100535100536100537100538100539100540100541100542100543100544100545100546100547100548100549100550100551100552100553100554100555100556100557100558100559100560100561100562100563100564100565100566100567100568100569100570100571100572100573100574100575100576100577100578100579100580100581100582100583100584100585100586100587100588100589100590100591100592100593100594100595100596100597100598100599100600100601100602100603100604100605100606100607100608100609100610100611100612100613100614100615100616100617100618100619100620100621100622100623100624100625100626100627100628100629100630100631100632100633100634100635100636100637100638100639100640100641100642100643100644100645100646100647100648100649100650100651100652100653100654100655100656100657100658100659100660100661100662100663100664100665100666100667100668100669100670100671100672100673100674100675100676100677100678100679100680100681100682100683100684100685100686100687100688100689100690100691100692100693100694100695100696100697100698100699100700100701100702100703100704100705100706100707100708100709100710100711100712100713100714100715100716100717100718100719100720100721100722100723100724100725100726100727100728100729100730100731100732100733100734100735100736100737100738100739100740100741100742100743100744100745100746100747100748100749100750100751100752100753100754100755100756100757100758100759100760100761100762100763100764100765100766100767100768100769100770100771100772100773100774100775100776100777100778100779100780100781100782100783100784100785100786100787100788100789100790100791100792100793100794100795100796100797100798100799100800100801100802100803100804100805100806100807100808100809100810100811100812100813100814100815100816100817100818100819100820100821100822100823100824100825100826100827100828100829100830100831100832100833100834100835100836100837100838100839100840100841100842100843100844100845100846100847100848100849100850100851100852100853100854100855100856100857100858100859100860100861100862100863100864100865100866100867100868100869100870100871100872100873100874100875100876100877100878100879100880100881100882100883100884100885100886100887100888100889100890100891100892100893100894100895100896100897100898100899100900100901100902100903100904100905100906100907100908100909100910100911100912100913100914100915100916100917100918100919100920100921100922100923100924100925100926100927100928100929100930100931100932100933100934100935100936100937100938100939100940100941100942100943100944100945100946100947100948100949100950100951100952100953100954100955100956100957100958100959100960100961100962100963100964100965100966100967100968100969100970100971100972100973100974100975100976100977100978100979100980100981100982100983100984100985100986100987100988100989100990100991100992100993100994100995100996100997100998100999101000101001101002101003101004101005101006101007101008101009101010101011101012101013101014101015101016101017101018101019101020101021101022101023101024101025101026101027101028101029101030101031101032101033101034101035101036101037101038101039101040101041101042101043101044101045101046101047101048101049101050101051101052101053101054101055101056101057101058101059101060101061101062101063101064101065101066101067101068101069101070101071101072101073101074101075101076101077101078101079101080101081101082101083101084101085101086101087101088101089101090101091101092101093101094101095101096101097101098101099101100101101101102101103101104101105101106101107101108101109101110101111101112101113101114101115101116101117101118101119101120101121101122101123101124101125101126101127101128101129101130101131101132101133101134101135101136101137101138101139101140101141101142101143101144101145101146101147101148101149101150101151101152101153101154101155101156101157101158101159101160101161101162101163101164101165101166101167101168101169101170101171101172101173101174101175101176101177101178101179101180101181101182101183101184101185101186101187101188101189101190101191101192101193101194101195101196101197101198101199101200101201101202101203101204101205101206101207101208101209101210101211101212101213101214101215101216101217101218101219101220101221101222101223101224101225101226101227101228101229101230101231101232101233101234101235101236101237101238101239101240101241101242101243101244101245101246101247101248101249101250101251101252101253101254101255101256101257101258101259101260101261101262101263101264101265101266101267101268101269101270101271101272101273101274101275101276101277101278101279101280101281101282101283101284101285101286101287101288101289101290101291101292101293101294101295101296101297101298101299101300101301101302101303101304101305101306101307101308101309101310101311101312101313101314101315101316101317101318101319101320101321101322101323101324101325101326101327101328101329101330101331101332101333101334101335101336101337101338101339101340101341101342101343101344101345101346101347101348101349101350101351101352101353101354101355101356101357101358101359101360101361101362101363101364101365101366101367101368101369101370101371101372101373101374101375101376101377101378101379101380101381101382101383101384101385101386101387101388101389101390101391101392101393101394101395101396101397101398101399101400101401101402101403101404101405101406101407101408101409101410101411101412101413101414101415101416101417101418101419101420101421101422101423101424101425101426101427101428101429101430101431101432101433101434101435101436101437101438101439101440101441101442101443101444101445101446101447101448101449101450101451101452101453101454101455101456101457101458101459101460101461101462101463101464101465101466101467101468101469101470101471101472101473101474101475101476101477101478101479101480101481101482101483101484101485101486101487101488101489101490101491101492101493101494101495101496101497101498101499101500101501101502101503101504101505101506101507101508101509101510101511101512101513101514101515101516101517101518101519101520101521101522101523101524101525101526101527101528101529101530101531101532101533101534101535101536101537101538101539101540101541101542101543101544101545101546101547101548101549101550101551101552101553101554101555101556101557101558101559101560101561101562101563101564101565101566101567101568101569101570101571101572101573101574101575101576101577101578101579101580101581101582101583101584101585101586101587101588101589101590101591101592101593101594101595101596101597101598101599101600101601101602101603101604101605101606101607101608101609101610101611101612101613101614101615101616101617101618101619101620101621101622101623101624101625101626101627101628101629101630101631101632101633101634101635101636101637101638101639101640101641101642101643101644101645101646101647101648101649101650101651101652101653101654101655101656101657101658101659101660101661101662101663101664101665101666101667101668101669101670101671101672101673101674101675101676101677101678101679101680101681101682101683101684101685101686101687101688101689101690101691101692101693101694101695101696101697101698101699101700101701101702101703101704101705101706101707101708101709101710101711101712101713101714101715101716101717101718101719101720101721101722101723101724101725101726101727101728101729101730101731101732101733101734101735101736101737101738101739101740101741101742101743101744101745101746101747101748101749101750101751101752101753101754101755101756101757101758101759101760101761101762101763101764101765101766101767101768101769101770101771101772101773101774101775101776101777101778101779101780101781101782101783101784101785101786101787101788101789101790101791101792101793101794101795101796101797101798101799101800101801101802101803101804101805101806101807101808101809101810101811101812101813101814101815101816101817101818101819101820101821101822101823101824101825101826101827101828101829101830101831101832101833101834101835101836101837101838101839101840101841101842101843101844101845101846101847101848101849101850101851101852101853101854101855101856101857101858101859101860101861101862101863101864101865101866101867101868101869101870101871101872101873101874101875101876101877101878101879101880101881101882101883101884101885101886101887101888101889101890101891101892101893101894101895101896101897101898101899101900101901101902101903101904101905101906101907101908101909101910101911101912101913101914101915101916101917101918101919101920101921101922101923101924101925101926101927101928101929101930101931101932101933101934101935101936101937101938101939101940101941101942101943101944101945101946101947101948101949101950101951101952101953101954101955101956101957101958101959101960101961101962101963101964101965101966101967101968101969101970101971101972101973101974101975101976101977101978101979101980101981101982101983101984101985101986101987101988101989101990101991101992101993101994101995101996101997101998101999102000102001102002102003102004102005102006102007102008102009102010102011102012102013102014102015102016102017102018102019102020102021102022102023102024102025102026102027102028102029102030102031102032102033102034102035102036102037102038102039102040102041102042102043102044102045102046102047102048102049102050102051102052102053102054102055102056102057102058102059102060102061102062102063102064102065102066102067102068102069102070102071102072102073102074102075102076102077102078102079102080102081102082102083102084102085102086102087102088102089102090102091102092102093102094102095102096102097102098102099102100102101102102102103102104102105102106102107102108102109102110102111102112102113102114102115102116102117102118102119102120102121102122102123102124102125102126102127102128102129102130102131102132102133102134102135102136102137102138102139102140102141102142102143102144102145102146102147102148102149102150102151102152102153102154102155102156102157102158102159102160102161102162102163102164102165102166102167102168102169102170102171102172102173102174102175102176102177102178102179102180102181102182102183102184102185102186102187102188102189102190102191102192102193102194102195102196102197102198102199102200102201102202102203102204102205102206102207102208102209102210102211102212102213102214102215102216102217102218102219102220102221102222102223102224102225102226102227102228102229102230102231102232102233102234102235102236102237102238102239102240102241102242102243102244102245102246102247102248102249102250102251102252102253102254102255102256102257102258102259102260102261102262102263102264102265102266102267102268102269102270102271102272102273102274102275102276102277102278102279102280102281102282102283102284102285102286102287102288102289102290102291102292102293102294102295102296102297102298102299102300102301102302102303102304102305102306102307102308102309102310102311102312102313102314102315102316102317102318102319102320102321102322102323102324102325102326102327102328102329102330102331102332102333102334102335102336102337102338102339102340102341102342102343102344102345102346102347102348102349102350102351102352102353102354102355102356102357102358102359102360102361102362102363102364102365102366102367102368102369102370102371102372102373102374102375102376102377102378102379102380102381102382102383102384102385102386102387102388102389102390102391102392102393102394102395102396102397102398102399102400102401102402102403102404102405102406102407102408102409102410102411102412102413102414102415102416102417102418102419102420102421102422102423102424102425102426102427102428102429102430102431102432102433102434102435102436102437102438102439102440102441102442102443102444102445102446102447102448102449102450102451102452102453102454102455102456102457102458102459102460102461102462102463102464102465102466102467102468102469102470102471102472102473102474102475102476102477102478102479102480102481102482102483102484102485102486102487102488102489102490102491102492102493102494102495102496102497102498102499102500102501102502102503102504102505102506102507102508102509102510102511102512102513102514102515102516102517102518102519102520102521102522102523102524102525102526102527102528102529102530102531102532102533102534102535102536102537102538102539102540102541102542102543102544102545102546102547102548102549102550102551102552102553102554102555102556102557102558102559102560102561102562102563102564102565102566102567102568102569102570102571102572102573102574102575102576102577102578102579102580102581102582102583102584102585102586102587102588102589102590102591102592102593102594102595102596102597102598102599102600102601102602102603102604102605102606102607102608102609102610102611102612102613102614102615102616102617102618102619102620102621102622102623102624102625102626102627102628102629102630102631102632102633102634102635102636102637102638102639102640102641102642102643102644102645102646102647102648102649102650102651102652102653102654102655102656102657102658102659102660102661102662102663102664102665102666102667102668102669102670102671102672102673102674102675102676102677102678102679102680102681102682102683102684102685102686102687102688102689102690102691102692102693102694102695102696102697102698102699102700102701102702102703102704102705102706102707102708102709102710102711102712102713102714102715102716102717102718102719102720102721102722102723102724102725102726102727102728102729102730102731102732102733102734102735102736102737102738102739102740102741102742102743102744102745102746102747102748102749102750102751102752102753102754102755102756102757102758102759102760102761102762102763102764102765102766102767102768102769102770102771102772102773102774102775102776102777102778102779102780102781102782102783102784102785102786102787102788102789102790102791102792102793102794102795102796102797102798102799102800102801102802102803102804102805102806102807102808102809102810102811102812102813102814102815102816102817102818102819102820102821102822102823102824102825102826102827102828102829102830102831102832102833102834102835102836102837102838102839102840102841102842102843102844102845102846102847102848102849102850102851102852102853102854102855102856102857102858102859102860102861102862102863102864102865102866102867102868102869102870102871102872102873102874102875102876102877102878102879102880102881102882102883102884102885102886102887102888102889102890102891102892102893102894102895102896102897102898102899102900102901102902102903102904102905102906102907102908102909102910102911102912102913102914102915102916102917102918102919102920102921102922102923102924102925102926102927102928102929102930102931102932102933102934102935102936102937102938102939102940102941102942102943102944102945102946102947102948102949102950102951102952102953102954102955102956102957102958102959102960102961102962102963102964102965102966102967102968102969102970102971102972102973102974102975102976102977102978102979102980102981102982102983102984102985102986102987102988102989102990102991102992102993102994102995102996102997102998102999103000103001103002103003103004103005103006103007103008103009103010103011103012103013103014103015103016103017103018103019103020103021103022103023103024103025103026103027103028103029103030103031103032103033103034103035103036103037103038103039103040103041103042103043103044103045103046103047103048103049103050103051103052103053103054103055103056103057103058103059103060103061103062103063103064103065103066103067103068103069103070103071103072103073103074103075103076103077103078103079103080103081103082103083103084103085103086103087103088103089103090103091103092103093103094103095103096103097103098103099103100103101103102103103103104103105103106103107103108103109103110103111103112103113103114103115103116103117103118103119103120103121103122103123103124103125103126103127103128103129103130103131103132103133103134103135103136103137103138103139103140103141103142103143103144103145103146103147103148103149103150103151103152103153103154103155103156103157103158103159103160103161103162103163103164103165103166103167103168103169103170103171103172103173103174103175103176103177103178103179103180103181103182103183103184103185103186103187103188103189103190103191103192103193103194103195103196103197103198103199103200103201103202103203103204103205103206103207103208103209103210103211103212103213103214103215103216103217103218103219103220103221103222103223103224103225103226103227103228103229103230103231103232103233103234103235103236103237103238103239103240103241103242103243103244103245103246103247103248103249103250103251103252103253103254103255103256103257103258103259103260103261103262103263103264103265103266103267103268103269103270103271103272103273103274103275103276103277103278103279103280103281103282103283103284103285103286103287103288103289103290103291103292103293103294103295103296103297103298103299103300103301103302103303103304103305103306103307103308103309103310103311103312103313103314103315103316103317103318103319103320103321103322103323103324103325103326103327103328103329103330103331103332103333103334103335103336103337103338103339103340103341103342103343103344103345103346103347103348103349103350103351103352103353103354103355103356103357103358103359103360103361103362103363103364103365103366103367103368103369103370103371103372103373103374103375103376103377103378103379103380103381103382103383103384103385103386103387103388103389103390103391103392103393103394103395103396103397103398103399103400103401103402103403103404103405103406103407103408103409103410103411103412103413103414103415103416103417103418103419103420103421103422103423103424103425103426103427103428103429103430103431103432103433103434103435103436103437103438103439103440103441103442103443103444103445103446103447103448103449103450103451103452103453103454103455103456103457103458103459103460103461103462103463103464103465103466103467103468103469103470103471103472103473103474103475103476103477103478103479103480103481103482103483103484103485103486103487103488103489103490103491103492103493103494103495103496103497103498103499103500103501103502103503103504103505103506103507103508103509103510103511103512103513103514103515103516103517103518103519103520103521103522103523103524103525103526103527103528103529103530103531103532103533103534103535103536103537103538103539103540103541103542103543103544103545103546103547103548103549103550103551103552103553103554103555103556103557103558103559103560103561103562103563103564103565103566103567103568103569103570103571103572103573103574103575103576103577103578103579103580103581103582103583103584103585103586103587103588103589103590103591103592103593103594103595103596103597103598103599103600103601103602103603103604103605103606103607103608103609103610103611103612103613103614103615103616103617103618103619103620103621103622103623103624103625103626103627103628103629103630103631103632103633103634103635103636103637103638103639103640103641103642103643103644103645103646103647103648103649103650103651103652103653103654103655103656103657103658103659103660103661103662103663103664103665103666103667103668103669103670103671103672103673103674103675103676103677103678103679103680103681103682103683103684103685103686103687103688103689103690103691103692103693103694103695103696103697103698103699103700103701103702103703103704103705103706103707103708103709103710103711103712103713103714103715103716103717103718103719103720103721103722103723103724103725103726103727103728103729103730103731103732103733103734103735103736103737103738103739103740103741103742103743103744103745103746103747103748103749103750103751103752103753103754103755103756103757103758103759103760103761103762103763103764103765103766103767103768103769103770103771103772103773103774103775103776103777103778103779103780103781103782103783103784103785103786103787103788103789103790103791103792103793103794103795103796103797103798103799103800103801103802103803103804103805103806103807103808103809103810103811103812103813103814103815103816103817103818103819103820103821103822103823103824103825103826103827103828103829103830103831103832103833103834103835103836103837103838103839103840103841103842103843103844103845103846103847103848103849103850103851103852103853103854103855103856103857103858103859103860103861103862103863103864103865103866103867103868103869103870103871103872103873103874103875103876103877103878103879103880103881103882103883103884103885103886103887103888103889103890103891103892103893103894103895103896103897103898103899103900103901103902103903103904103905103906103907103908103909103910103911103912103913103914103915103916103917103918103919103920103921103922103923103924103925103926103927103928103929103930103931103932103933103934103935103936103937103938103939103940103941103942103943103944103945103946103947103948103949103950103951103952103953103954103955103956103957103958103959103960103961103962103963103964103965103966103967103968103969103970103971103972103973103974103975103976103977103978103979103980103981103982103983103984103985103986103987103988103989103990103991103992103993103994103995103996103997103998103999104000104001104002104003104004104005104006104007104008104009104010104011104012104013104014104015104016104017104018104019104020104021104022104023104024104025104026104027104028104029104030104031104032104033104034104035104036104037104038104039104040104041104042104043104044104045104046104047104048104049104050104051104052104053104054104055104056104057104058104059104060104061104062104063104064104065104066104067104068104069104070104071104072104073104074104075104076104077104078104079104080104081104082104083104084104085104086104087104088104089104090104091104092104093104094104095104096104097104098104099104100104101104102104103104104104105104106104107104108104109104110104111104112104113104114104115104116104117104118104119104120104121104122104123104124104125104126104127104128104129104130104131104132104133104134104135104136104137104138104139104140104141104142104143104144104145104146104147104148104149104150104151104152104153104154104155104156104157104158104159104160104161104162104163104164104165104166104167104168104169104170104171104172104173104174104175104176104177104178104179104180104181104182104183104184104185104186104187104188104189104190104191104192104193104194104195104196104197104198104199104200104201104202104203104204104205104206104207104208104209104210104211104212104213104214104215104216104217104218104219104220104221104222104223104224104225104226104227104228104229104230104231104232104233104234104235104236104237104238104239104240104241104242104243104244104245104246104247104248104249104250104251104252104253104254104255104256104257104258104259104260104261104262104263104264104265104266104267104268104269104270104271104272104273104274104275104276104277104278104279104280104281104282104283104284104285104286104287104288104289104290104291104292104293104294104295104296104297104298104299104300104301104302104303104304104305104306104307104308104309104310104311104312104313104314104315104316104317104318104319104320104321104322104323104324104325104326104327104328104329104330104331104332104333104334104335104336104337104338104339104340104341104342104343104344104345104346104347104348104349104350104351104352104353104354104355104356104357104358104359104360104361104362104363104364104365104366104367104368104369104370104371104372104373104374104375104376104377104378104379104380104381104382104383104384104385104386104387104388104389104390104391104392104393104394104395104396104397104398104399104400104401104402104403104404104405104406104407104408104409104410104411104412104413104414104415104416104417104418104419104420104421104422104423104424104425104426104427104428104429104430104431104432104433104434104435104436104437104438104439104440104441104442104443104444104445104446104447104448104449104450104451104452104453104454104455104456104457104458104459104460104461104462104463104464104465104466104467104468104469104470104471104472104473104474104475104476104477104478104479104480104481104482104483104484104485104486104487104488104489104490104491104492104493104494104495104496104497104498104499104500104501104502104503104504104505104506104507104508104509104510104511104512104513104514104515104516104517104518104519104520104521104522104523104524104525104526104527104528104529104530104531104532104533104534104535104536104537104538104539104540104541104542104543104544104545104546104547104548104549104550104551104552104553104554104555104556104557104558104559104560104561104562104563104564104565104566104567104568104569104570104571104572104573104574104575104576104577104578104579104580104581104582104583104584104585104586104587104588104589104590104591104592104593104594104595104596104597104598104599104600104601104602104603104604104605104606104607104608104609104610104611104612104613104614104615104616104617104618104619104620104621104622104623104624104625104626104627104628104629104630104631104632104633104634104635104636104637104638104639104640104641104642104643104644104645104646104647104648104649104650104651104652104653104654104655104656104657104658104659104660104661104662104663104664104665104666104667104668104669104670104671104672104673104674104675104676104677104678104679104680104681104682104683104684104685104686104687104688104689104690104691104692104693104694104695104696104697104698104699104700104701104702104703104704104705104706104707104708104709104710104711104712104713104714104715104716104717104718104719104720104721104722104723104724104725104726104727104728104729104730104731104732104733104734104735104736104737104738104739104740104741104742104743104744104745104746104747104748104749104750104751104752104753104754104755104756104757104758104759104760104761104762104763104764104765104766104767104768104769104770104771104772104773104774104775104776104777104778104779104780104781104782104783104784104785104786104787104788104789104790104791104792104793104794104795104796104797104798104799104800104801104802104803104804104805104806104807104808104809104810104811104812104813104814104815104816104817104818104819104820104821104822104823104824104825104826104827104828104829104830104831104832104833104834104835104836104837104838104839104840104841104842104843104844104845104846104847104848104849104850104851104852104853104854104855104856104857104858104859104860104861104862104863104864104865104866104867104868104869104870104871104872104873104874104875104876104877104878104879104880104881104882104883104884104885104886104887104888104889104890104891104892104893104894104895104896104897104898104899104900104901104902104903104904104905104906104907104908104909104910104911104912104913104914104915104916104917104918104919104920104921104922104923104924104925104926104927104928104929104930104931104932104933104934104935104936104937104938104939104940104941104942104943104944104945104946104947104948104949104950104951104952104953104954104955104956104957104958104959104960104961104962104963104964104965104966104967104968104969104970104971104972104973104974104975104976104977104978104979104980104981104982104983104984104985104986104987104988104989104990104991104992104993104994104995104996104997104998104999105000105001105002105003105004105005105006105007105008105009105010105011105012105013105014105015105016105017105018105019105020105021105022105023105024105025105026105027105028105029105030105031105032105033105034105035105036105037105038105039105040105041105042105043105044105045105046105047105048105049105050105051105052105053105054105055105056105057105058105059105060105061105062105063105064105065105066105067105068105069105070105071105072105073105074105075105076105077105078105079105080105081105082105083105084105085105086105087105088105089105090105091105092105093105094105095105096105097105098105099105100105101105102105103105104105105105106105107105108105109105110105111105112105113105114105115105116105117105118105119105120105121105122105123105124105125105126105127105128105129105130105131105132105133105134105135105136105137105138105139105140105141105142105143105144105145105146105147105148105149105150105151105152105153105154105155105156105157105158105159105160105161105162105163105164105165105166105167105168105169105170105171105172105173105174105175105176105177105178105179105180105181105182105183105184105185105186105187105188105189105190105191105192105193105194105195105196105197105198105199105200105201105202105203105204105205105206105207105208105209105210105211105212105213105214105215105216105217105218105219105220105221105222105223105224105225105226105227105228105229105230105231105232105233105234105235105236105237105238105239105240105241105242105243105244105245105246105247105248105249105250105251105252105253105254105255105256105257105258105259105260105261105262105263105264105265105266105267105268105269105270105271105272105273105274105275105276105277105278105279105280105281105282105283105284105285105286105287105288105289105290105291105292105293105294105295105296105297105298105299105300105301105302105303105304105305105306105307105308105309105310105311105312105313105314105315105316105317105318105319105320105321105322105323105324105325105326105327105328105329105330105331105332105333105334105335105336105337105338105339105340105341105342105343105344105345105346105347105348105349105350105351105352105353105354105355105356105357105358105359105360105361105362105363105364105365105366105367105368105369105370105371105372105373105374105375105376105377105378105379105380105381105382105383105384105385105386105387105388105389105390105391105392105393105394105395105396105397105398105399105400105401105402105403105404105405105406105407105408105409105410105411105412105413105414105415105416105417105418105419105420105421105422105423105424105425105426105427105428105429105430105431105432105433105434105435105436105437105438105439105440105441105442105443105444105445105446105447105448105449105450105451105452105453105454105455105456105457105458105459105460105461105462105463105464105465105466105467105468105469105470105471105472105473105474105475105476105477105478105479105480105481105482105483105484105485105486105487105488105489105490105491105492105493105494105495105496105497105498105499105500105501105502105503105504105505105506105507105508105509105510105511105512105513105514105515105516105517105518105519105520105521105522105523105524105525105526105527105528105529105530105531105532105533105534105535105536105537105538105539105540105541105542105543105544105545105546105547105548105549105550105551105552105553105554105555105556105557105558105559105560105561105562105563105564105565105566105567105568105569105570105571105572105573105574105575105576105577105578105579105580105581105582105583105584105585105586105587105588105589105590105591105592105593105594105595105596105597105598105599105600105601105602105603105604105605105606105607105608105609105610105611105612105613105614105615105616105617105618105619105620105621105622105623105624105625105626105627105628105629105630105631105632105633105634105635105636105637105638105639105640105641105642105643105644105645105646105647105648105649105650105651105652105653105654105655105656105657105658105659105660105661105662105663105664105665105666105667105668105669105670105671105672105673105674105675105676105677105678105679105680105681105682105683105684105685105686105687105688105689105690105691105692105693105694105695105696105697105698105699105700105701105702105703105704105705105706105707105708105709105710105711105712105713105714105715105716105717105718105719105720105721105722105723105724105725105726105727105728105729105730105731105732105733105734105735105736105737105738105739105740105741105742105743105744105745105746105747105748105749105750105751105752105753105754105755105756105757105758105759105760105761105762105763105764105765105766105767105768105769105770105771105772105773105774105775105776105777105778105779105780105781105782105783105784105785105786105787105788105789105790105791105792105793105794105795105796105797105798105799105800105801105802105803105804105805105806105807105808105809105810105811105812105813105814105815105816105817105818105819105820105821105822105823105824105825105826105827105828105829105830105831105832105833105834105835105836105837105838105839105840105841105842105843105844105845105846105847105848105849105850105851105852105853105854105855105856105857105858105859105860105861105862105863105864105865105866105867105868105869105870105871105872105873105874105875105876105877105878105879105880105881105882105883105884105885105886105887105888105889105890105891105892105893105894105895105896105897105898105899105900105901105902105903105904105905105906105907105908105909105910105911105912105913105914105915105916105917105918105919105920105921105922105923105924105925105926105927105928105929105930105931105932105933105934105935105936105937105938105939105940105941105942105943105944105945105946105947105948105949105950105951105952105953105954105955105956105957105958105959105960105961105962105963105964105965105966105967105968105969105970105971105972105973105974105975105976105977105978105979105980105981105982105983105984105985105986105987105988105989105990105991105992105993105994105995105996105997105998105999106000106001106002106003106004106005106006106007106008106009106010106011106012106013106014106015106016106017106018106019106020106021106022106023106024106025106026106027106028106029106030106031106032106033106034106035106036106037106038106039106040106041106042106043106044106045106046106047106048106049106050106051106052106053106054106055106056106057106058106059106060106061106062106063106064106065106066106067106068106069106070106071106072106073106074106075106076106077106078106079106080106081106082106083106084106085106086106087106088106089106090106091106092106093106094106095106096106097106098106099106100106101106102106103106104106105106106106107106108106109106110106111106112106113106114106115106116106117106118106119106120106121106122106123106124106125106126106127106128106129106130106131106132106133106134106135106136106137106138106139106140106141106142106143106144106145106146106147106148106149106150106151106152106153106154106155106156106157106158106159106160106161106162106163106164106165106166106167106168106169106170106171106172106173106174106175106176106177106178106179106180106181106182106183106184106185106186106187106188106189106190106191106192106193106194106195106196106197106198106199106200106201106202106203106204106205106206106207106208106209106210106211106212106213106214106215106216106217106218106219106220106221106222106223106224106225106226106227106228106229106230106231106232106233106234106235106236106237106238106239106240106241106242106243106244106245106246106247106248106249106250106251106252106253106254106255106256106257106258106259106260106261106262106263106264106265106266106267106268106269106270106271106272106273106274106275106276106277106278106279106280106281106282106283106284106285106286106287106288106289106290106291106292106293106294106295106296106297106298106299106300106301106302106303106304106305106306106307106308106309106310106311106312106313106314106315106316106317106318106319106320106321106322106323106324106325106326106327106328106329106330106331106332106333106334106335106336106337106338106339106340106341106342106343106344106345106346106347106348106349106350106351106352106353106354106355106356106357106358106359106360106361106362106363106364106365106366106367106368106369106370106371106372106373106374106375106376106377106378106379106380106381106382106383106384106385106386106387106388106389106390106391106392106393106394106395106396106397106398106399106400106401106402106403106404106405106406106407106408106409106410106411106412106413106414106415106416106417106418106419106420106421106422106423106424106425106426106427106428106429106430106431106432106433106434106435106436106437106438106439106440106441106442106443106444106445106446106447106448106449106450106451106452106453106454106455106456106457106458106459106460106461106462106463106464106465106466106467106468106469106470106471106472106473106474106475106476106477106478106479106480106481106482106483106484106485106486106487106488106489106490106491106492106493106494106495106496106497106498106499106500106501106502106503106504106505106506106507106508106509106510106511106512106513106514106515106516106517106518106519106520106521106522106523106524106525106526106527106528106529106530106531106532106533106534106535106536106537106538106539106540106541106542106543106544106545106546106547106548106549106550106551106552106553106554106555106556106557106558106559106560106561106562106563106564106565106566106567106568106569106570106571106572106573106574106575106576106577106578106579106580106581106582106583106584106585106586106587106588106589106590106591106592106593106594106595106596106597106598106599106600106601106602106603106604106605106606106607106608106609106610106611106612106613106614106615106616106617106618106619106620106621106622106623106624106625106626106627106628106629106630106631106632106633106634106635106636106637106638106639106640106641106642106643106644106645106646106647106648106649106650106651106652106653106654106655106656106657106658106659106660106661106662106663106664106665106666106667106668106669106670106671106672106673106674106675106676106677106678106679106680106681106682106683106684106685106686106687106688106689106690106691106692106693106694106695106696106697106698106699106700106701106702106703106704106705106706106707106708106709106710106711106712106713106714106715106716106717106718106719106720106721106722106723106724106725106726106727106728106729106730106731106732106733106734106735106736106737106738106739106740106741106742106743106744106745106746106747106748106749106750106751106752106753106754106755106756106757106758106759106760106761106762106763106764106765106766106767106768106769106770106771106772106773106774106775106776106777106778106779106780106781106782106783106784106785106786106787106788106789106790106791106792106793106794106795106796106797106798106799106800106801106802106803106804106805106806106807106808106809106810106811106812106813106814106815106816106817106818106819106820106821106822106823106824106825106826106827106828106829106830106831106832106833106834106835106836106837106838106839106840106841106842106843106844106845106846106847106848106849106850106851106852106853106854106855106856106857106858106859106860106861106862106863106864106865106866106867106868106869106870106871106872106873106874106875106876106877106878106879106880106881106882106883106884106885106886106887106888106889106890106891106892106893106894106895106896106897106898106899106900106901106902106903106904106905106906106907106908106909106910106911106912106913106914106915106916106917106918106919106920106921106922106923106924106925106926106927106928106929106930106931106932106933106934106935106936106937106938106939106940106941106942106943106944106945106946106947106948106949106950106951106952106953106954106955106956106957106958106959106960106961106962106963106964106965106966106967106968106969106970106971106972106973106974106975106976106977106978106979106980106981106982106983106984106985106986106987106988106989106990106991106992106993106994106995106996106997106998106999107000107001107002107003107004107005107006107007107008107009107010107011107012107013107014107015107016107017107018107019107020107021107022107023107024107025107026107027107028107029107030107031107032107033107034107035107036107037107038107039107040107041107042107043107044107045107046107047107048107049107050107051107052107053107054107055107056107057107058107059107060107061107062107063107064107065107066107067107068107069107070107071107072107073107074107075107076107077107078107079107080107081107082107083107084107085107086107087107088107089107090107091107092107093107094107095107096107097107098107099107100107101107102107103107104107105107106107107107108107109107110107111107112107113107114107115107116107117107118107119107120107121107122107123107124107125107126107127107128107129107130107131107132107133107134107135107136107137107138107139107140107141107142107143107144107145107146107147107148107149107150107151107152107153107154107155107156107157107158107159107160107161107162107163107164107165107166107167107168107169107170107171107172107173107174107175107176107177107178107179107180107181107182107183107184107185107186107187107188107189107190107191107192107193107194107195107196107197107198107199107200107201107202107203107204107205107206107207107208107209107210107211107212107213107214107215107216107217107218107219107220107221107222107223107224107225107226107227107228107229107230107231107232107233107234107235107236107237107238107239107240107241107242107243107244107245107246107247107248107249107250107251107252107253107254107255107256107257107258107259107260107261107262107263107264107265107266107267107268107269107270107271107272107273107274107275107276107277107278107279107280107281107282107283107284107285107286107287107288107289107290107291107292107293107294107295107296107297107298107299107300107301107302107303107304107305107306107307107308107309107310107311107312107313107314107315107316107317107318107319107320107321107322107323107324107325107326107327107328107329107330107331107332107333107334107335107336107337107338107339107340107341107342107343107344107345107346107347107348107349107350107351107352107353107354107355107356107357107358107359107360107361107362107363107364107365107366107367107368107369107370107371107372107373107374107375107376107377107378107379107380107381107382107383107384107385107386107387107388107389107390107391107392107393107394107395107396107397107398107399107400107401107402107403107404107405107406107407107408107409107410107411107412107413107414107415107416107417107418107419107420107421107422107423107424107425107426107427107428107429107430107431107432107433107434107435107436107437107438107439107440107441107442107443107444107445107446107447107448107449107450107451107452107453107454107455107456107457107458107459107460107461107462107463107464107465107466107467107468107469107470107471107472107473107474107475107476107477107478107479107480107481107482107483107484107485107486107487107488107489107490107491107492107493107494107495107496107497107498107499107500107501107502107503107504107505107506107507107508107509107510107511107512107513107514107515107516107517107518107519107520107521107522107523107524107525107526107527107528107529107530107531107532107533107534107535107536107537107538107539107540107541107542107543107544107545107546107547107548107549107550107551107552107553107554107555107556107557107558107559107560107561107562107563107564107565107566107567107568107569107570107571107572107573107574107575107576107577107578107579107580107581107582107583107584107585107586107587107588107589107590107591107592107593107594107595107596107597107598107599107600107601107602107603107604107605107606107607107608107609107610107611107612107613107614107615107616107617107618107619107620107621107622107623107624107625107626107627107628107629107630107631107632107633107634107635107636107637107638107639107640107641107642107643107644107645107646107647107648107649107650107651107652107653107654107655107656107657107658107659107660107661107662107663107664107665107666107667107668107669107670107671107672107673107674107675107676107677107678107679107680107681107682107683107684107685107686107687107688107689107690107691107692107693107694107695107696107697107698107699107700107701107702107703107704107705107706107707107708107709107710107711107712107713107714107715107716107717107718107719107720107721107722107723107724107725107726107727107728107729107730107731107732107733107734107735107736107737107738107739107740107741107742107743107744107745107746107747107748107749107750107751107752107753107754107755107756107757107758107759107760107761107762107763107764107765107766107767107768107769107770107771107772107773107774107775107776107777107778107779107780107781107782107783107784107785107786107787107788107789107790107791107792107793107794107795107796107797107798107799107800107801107802107803107804107805107806107807107808107809107810107811107812107813107814107815107816107817107818107819107820107821107822107823107824107825107826107827107828107829107830107831107832107833107834107835107836107837107838107839107840107841107842107843107844107845107846107847107848107849107850107851107852107853107854107855107856107857107858107859107860107861107862107863107864107865107866107867107868107869107870107871107872107873107874107875107876107877107878107879107880107881107882107883107884107885107886107887107888107889107890107891107892107893107894107895107896107897107898107899107900107901107902107903107904107905107906107907107908107909107910107911107912107913107914107915107916107917107918107919107920107921107922107923107924107925107926107927107928107929107930107931107932107933107934107935107936107937107938107939107940107941107942107943107944107945107946107947107948107949107950107951107952107953107954107955107956107957107958107959107960107961107962107963107964107965107966107967107968107969107970107971107972107973107974107975107976107977107978107979107980107981107982107983107984107985107986107987107988107989107990107991107992107993107994107995107996107997107998107999108000108001108002108003108004108005108006108007108008108009108010108011108012108013108014108015108016108017108018108019108020108021108022108023108024108025108026108027108028108029108030108031108032108033108034108035108036108037108038108039108040108041108042108043108044108045108046108047108048108049108050108051108052
  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. /** @hidden */
  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. /** @hidden */
  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. /** @hidden */
  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. /** @hidden */
  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. /** @hidden */
  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. /** @hidden */
  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. /**
  2278. * Class representing a vector containing 2 coordinates
  2279. */
  2280. var Vector2 = /** @class */ (function () {
  2281. /**
  2282. * Creates a new Vector2 from the given x and y coordinates
  2283. * @param x defines the first coordinate
  2284. * @param y defines the second coordinate
  2285. */
  2286. function Vector2(
  2287. /** defines the first coordinate */
  2288. x,
  2289. /** defines the second coordinate */
  2290. y) {
  2291. this.x = x;
  2292. this.y = y;
  2293. }
  2294. /**
  2295. * Gets a string with the Vector2 coordinates
  2296. * @returns a string with the Vector2 coordinates
  2297. */
  2298. Vector2.prototype.toString = function () {
  2299. return "{X: " + this.x + " Y:" + this.y + "}";
  2300. };
  2301. /**
  2302. * Gets class name
  2303. * @returns the string "Vector2"
  2304. */
  2305. Vector2.prototype.getClassName = function () {
  2306. return "Vector2";
  2307. };
  2308. /**
  2309. * Gets current vector hash code
  2310. * @returns the Vector2 hash code as a number
  2311. */
  2312. Vector2.prototype.getHashCode = function () {
  2313. var hash = this.x || 0;
  2314. hash = (hash * 397) ^ (this.y || 0);
  2315. return hash;
  2316. };
  2317. // Operators
  2318. /**
  2319. * Sets the Vector2 coordinates in the given array or Float32Array from the given index.
  2320. * @param array defines the source array
  2321. * @param index defines the offset in source array
  2322. * @returns the current Vector2
  2323. */
  2324. Vector2.prototype.toArray = function (array, index) {
  2325. if (index === void 0) { index = 0; }
  2326. array[index] = this.x;
  2327. array[index + 1] = this.y;
  2328. return this;
  2329. };
  2330. /**
  2331. * Copy the current vector to an array
  2332. * @returns a new array with 2 elements: the Vector2 coordinates.
  2333. */
  2334. Vector2.prototype.asArray = function () {
  2335. var result = new Array();
  2336. this.toArray(result, 0);
  2337. return result;
  2338. };
  2339. /**
  2340. * Sets the Vector2 coordinates with the given Vector2 coordinates
  2341. * @param source defines the source Vector2
  2342. * @returns the current updated Vector2
  2343. */
  2344. Vector2.prototype.copyFrom = function (source) {
  2345. this.x = source.x;
  2346. this.y = source.y;
  2347. return this;
  2348. };
  2349. /**
  2350. * Sets the Vector2 coordinates with the given floats
  2351. * @param x defines the first coordinate
  2352. * @param y defines the second coordinate
  2353. * @returns the current updated Vector2
  2354. */
  2355. Vector2.prototype.copyFromFloats = function (x, y) {
  2356. this.x = x;
  2357. this.y = y;
  2358. return this;
  2359. };
  2360. /**
  2361. * Sets the Vector2 coordinates with the given floats
  2362. * @param x defines the first coordinate
  2363. * @param y defines the second coordinate
  2364. * @returns the current updated Vector2
  2365. */
  2366. Vector2.prototype.set = function (x, y) {
  2367. return this.copyFromFloats(x, y);
  2368. };
  2369. /**
  2370. * Add another vector with the current one
  2371. * @param otherVector defines the other vector
  2372. * @returns a new Vector2 set with the addition of the current Vector2 and the given one coordinates
  2373. */
  2374. Vector2.prototype.add = function (otherVector) {
  2375. return new Vector2(this.x + otherVector.x, this.y + otherVector.y);
  2376. };
  2377. /**
  2378. * Sets the "result" coordinates with the addition of the current Vector2 and the given one coordinates
  2379. * @param otherVector defines the other vector
  2380. * @param result defines the target vector
  2381. * @returns the unmodified current Vector2
  2382. */
  2383. Vector2.prototype.addToRef = function (otherVector, result) {
  2384. result.x = this.x + otherVector.x;
  2385. result.y = this.y + otherVector.y;
  2386. return this;
  2387. };
  2388. /**
  2389. * Set the Vector2 coordinates by adding the given Vector2 coordinates
  2390. * @param otherVector defines the other vector
  2391. * @returns the current updated Vector2
  2392. */
  2393. Vector2.prototype.addInPlace = function (otherVector) {
  2394. this.x += otherVector.x;
  2395. this.y += otherVector.y;
  2396. return this;
  2397. };
  2398. /**
  2399. * Gets a new Vector2 by adding the current Vector2 coordinates to the given Vector3 x, y coordinates
  2400. * @param otherVector defines the other vector
  2401. * @returns a new Vector2
  2402. */
  2403. Vector2.prototype.addVector3 = function (otherVector) {
  2404. return new Vector2(this.x + otherVector.x, this.y + otherVector.y);
  2405. };
  2406. /**
  2407. * Gets a new Vector2 set with the subtracted coordinates of the given one from the current Vector2
  2408. * @param otherVector defines the other vector
  2409. * @returns a new Vector2
  2410. */
  2411. Vector2.prototype.subtract = function (otherVector) {
  2412. return new Vector2(this.x - otherVector.x, this.y - otherVector.y);
  2413. };
  2414. /**
  2415. * Sets the "result" coordinates with the subtraction of the given one from the current Vector2 coordinates.
  2416. * @param otherVector defines the other vector
  2417. * @param result defines the target vector
  2418. * @returns the unmodified current Vector2
  2419. */
  2420. Vector2.prototype.subtractToRef = function (otherVector, result) {
  2421. result.x = this.x - otherVector.x;
  2422. result.y = this.y - otherVector.y;
  2423. return this;
  2424. };
  2425. /**
  2426. * Sets the current Vector2 coordinates by subtracting from it the given one coordinates
  2427. * @param otherVector defines the other vector
  2428. * @returns the current updated Vector2
  2429. */
  2430. Vector2.prototype.subtractInPlace = function (otherVector) {
  2431. this.x -= otherVector.x;
  2432. this.y -= otherVector.y;
  2433. return this;
  2434. };
  2435. /**
  2436. * Multiplies in place the current Vector2 coordinates by the given ones
  2437. * @param otherVector defines the other vector
  2438. * @returns the current updated Vector2
  2439. */
  2440. Vector2.prototype.multiplyInPlace = function (otherVector) {
  2441. this.x *= otherVector.x;
  2442. this.y *= otherVector.y;
  2443. return this;
  2444. };
  2445. /**
  2446. * Returns a new Vector2 set with the multiplication of the current Vector2 and the given one coordinates
  2447. * @param otherVector defines the other vector
  2448. * @returns a new Vector2
  2449. */
  2450. Vector2.prototype.multiply = function (otherVector) {
  2451. return new Vector2(this.x * otherVector.x, this.y * otherVector.y);
  2452. };
  2453. /**
  2454. * Sets "result" coordinates with the multiplication of the current Vector2 and the given one coordinates
  2455. * @param otherVector defines the other vector
  2456. * @param result defines the target vector
  2457. * @returns the unmodified current Vector2
  2458. */
  2459. Vector2.prototype.multiplyToRef = function (otherVector, result) {
  2460. result.x = this.x * otherVector.x;
  2461. result.y = this.y * otherVector.y;
  2462. return this;
  2463. };
  2464. /**
  2465. * Gets a new Vector2 set with the Vector2 coordinates multiplied by the given floats
  2466. * @param x defines the first coordinate
  2467. * @param y defines the second coordinate
  2468. * @returns a new Vector2
  2469. */
  2470. Vector2.prototype.multiplyByFloats = function (x, y) {
  2471. return new Vector2(this.x * x, this.y * y);
  2472. };
  2473. /**
  2474. * Returns a new Vector2 set with the Vector2 coordinates divided by the given one coordinates
  2475. * @param otherVector defines the other vector
  2476. * @returns a new Vector2
  2477. */
  2478. Vector2.prototype.divide = function (otherVector) {
  2479. return new Vector2(this.x / otherVector.x, this.y / otherVector.y);
  2480. };
  2481. /**
  2482. * Sets the "result" coordinates with the Vector2 divided by the given one coordinates
  2483. * @param otherVector defines the other vector
  2484. * @param result defines the target vector
  2485. * @returns the unmodified current Vector2
  2486. */
  2487. Vector2.prototype.divideToRef = function (otherVector, result) {
  2488. result.x = this.x / otherVector.x;
  2489. result.y = this.y / otherVector.y;
  2490. return this;
  2491. };
  2492. /**
  2493. * Divides the current Vector3 coordinates by the given ones
  2494. * @param otherVector defines the other vector
  2495. * @returns the current updated Vector2
  2496. */
  2497. Vector2.prototype.divideInPlace = function (otherVector) {
  2498. return this.divideToRef(otherVector, this);
  2499. };
  2500. /**
  2501. * Gets a new Vector2 with current Vector2 negated coordinates
  2502. * @returns a new Vector2
  2503. */
  2504. Vector2.prototype.negate = function () {
  2505. return new Vector2(-this.x, -this.y);
  2506. };
  2507. /**
  2508. * Multiply the Vector2 coordinates by scale
  2509. * @param scale defines the scaling factor
  2510. * @returns the current updated Vector2
  2511. */
  2512. Vector2.prototype.scaleInPlace = function (scale) {
  2513. this.x *= scale;
  2514. this.y *= scale;
  2515. return this;
  2516. };
  2517. /**
  2518. * Returns a new Vector2 scaled by "scale" from the current Vector2
  2519. * @param scale defines the scaling factor
  2520. * @returns a new Vector2
  2521. */
  2522. Vector2.prototype.scale = function (scale) {
  2523. var result = new Vector2(0, 0);
  2524. this.scaleToRef(scale, result);
  2525. return result;
  2526. };
  2527. /**
  2528. * Scale the current Vector2 values by a factor to a given Vector2
  2529. * @param scale defines the scale factor
  2530. * @param result defines the Vector2 object where to store the result
  2531. * @returns the unmodified current Vector2
  2532. */
  2533. Vector2.prototype.scaleToRef = function (scale, result) {
  2534. result.x = this.x * scale;
  2535. result.y = this.y * scale;
  2536. return this;
  2537. };
  2538. /**
  2539. * Scale the current Vector2 values by a factor and add the result to a given Vector2
  2540. * @param scale defines the scale factor
  2541. * @param result defines the Vector2 object where to store the result
  2542. * @returns the unmodified current Vector2
  2543. */
  2544. Vector2.prototype.scaleAndAddToRef = function (scale, result) {
  2545. result.x += this.x * scale;
  2546. result.y += this.y * scale;
  2547. return this;
  2548. };
  2549. /**
  2550. * Gets a boolean if two vectors are equals
  2551. * @param otherVector defines the other vector
  2552. * @returns true if the given vector coordinates strictly equal the current Vector2 ones
  2553. */
  2554. Vector2.prototype.equals = function (otherVector) {
  2555. return otherVector && this.x === otherVector.x && this.y === otherVector.y;
  2556. };
  2557. /**
  2558. * Gets a boolean if two vectors are equals (using an epsilon value)
  2559. * @param otherVector defines the other vector
  2560. * @param epsilon defines the minimal distance to consider equality
  2561. * @returns true if the given vector coordinates are close to the current ones by a distance of epsilon.
  2562. */
  2563. Vector2.prototype.equalsWithEpsilon = function (otherVector, epsilon) {
  2564. if (epsilon === void 0) { epsilon = BABYLON.Epsilon; }
  2565. return otherVector && BABYLON.Scalar.WithinEpsilon(this.x, otherVector.x, epsilon) && BABYLON.Scalar.WithinEpsilon(this.y, otherVector.y, epsilon);
  2566. };
  2567. // Properties
  2568. /**
  2569. * Gets the length of the vector
  2570. * @returns the vector length (float)
  2571. */
  2572. Vector2.prototype.length = function () {
  2573. return Math.sqrt(this.x * this.x + this.y * this.y);
  2574. };
  2575. /**
  2576. * Gets the vector squared length
  2577. * @returns the vector squared length (float)
  2578. */
  2579. Vector2.prototype.lengthSquared = function () {
  2580. return (this.x * this.x + this.y * this.y);
  2581. };
  2582. // Methods
  2583. /**
  2584. * Normalize the vector
  2585. * @returns the current updated Vector2
  2586. */
  2587. Vector2.prototype.normalize = function () {
  2588. var len = this.length();
  2589. if (len === 0)
  2590. return this;
  2591. var num = 1.0 / len;
  2592. this.x *= num;
  2593. this.y *= num;
  2594. return this;
  2595. };
  2596. /**
  2597. * Gets a new Vector2 copied from the Vector2
  2598. * @returns a new Vector2
  2599. */
  2600. Vector2.prototype.clone = function () {
  2601. return new Vector2(this.x, this.y);
  2602. };
  2603. // Statics
  2604. /**
  2605. * Gets a new Vector2(0, 0)
  2606. * @returns a new Vector2
  2607. */
  2608. Vector2.Zero = function () {
  2609. return new Vector2(0, 0);
  2610. };
  2611. /**
  2612. * Gets a new Vector2(1, 1)
  2613. * @returns a new Vector2
  2614. */
  2615. Vector2.One = function () {
  2616. return new Vector2(1, 1);
  2617. };
  2618. /**
  2619. * Gets a new Vector2 set from the given index element of the given array
  2620. * @param array defines the data source
  2621. * @param offset defines the offset in the data source
  2622. * @returns a new Vector2
  2623. */
  2624. Vector2.FromArray = function (array, offset) {
  2625. if (offset === void 0) { offset = 0; }
  2626. return new Vector2(array[offset], array[offset + 1]);
  2627. };
  2628. /**
  2629. * Sets "result" from the given index element of the given array
  2630. * @param array defines the data source
  2631. * @param offset defines the offset in the data source
  2632. * @param result defines the target vector
  2633. */
  2634. Vector2.FromArrayToRef = function (array, offset, result) {
  2635. result.x = array[offset];
  2636. result.y = array[offset + 1];
  2637. };
  2638. /**
  2639. * Gets a new Vector2 located for "amount" (float) on the CatmullRom spline defined by the given four Vector2
  2640. * @param value1 defines 1st point of control
  2641. * @param value2 defines 2nd point of control
  2642. * @param value3 defines 3rd point of control
  2643. * @param value4 defines 4th point of control
  2644. * @param amount defines the interpolation factor
  2645. * @returns a new Vector2
  2646. */
  2647. Vector2.CatmullRom = function (value1, value2, value3, value4, amount) {
  2648. var squared = amount * amount;
  2649. var cubed = amount * squared;
  2650. var x = 0.5 * ((((2.0 * value2.x) + ((-value1.x + value3.x) * amount)) +
  2651. (((((2.0 * value1.x) - (5.0 * value2.x)) + (4.0 * value3.x)) - value4.x) * squared)) +
  2652. ((((-value1.x + (3.0 * value2.x)) - (3.0 * value3.x)) + value4.x) * cubed));
  2653. var y = 0.5 * ((((2.0 * value2.y) + ((-value1.y + value3.y) * amount)) +
  2654. (((((2.0 * value1.y) - (5.0 * value2.y)) + (4.0 * value3.y)) - value4.y) * squared)) +
  2655. ((((-value1.y + (3.0 * value2.y)) - (3.0 * value3.y)) + value4.y) * cubed));
  2656. return new Vector2(x, y);
  2657. };
  2658. /**
  2659. * 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".
  2660. * If a coordinate of "value" is lower than "min" coordinates, the returned Vector2 is given this "min" coordinate.
  2661. * If a coordinate of "value" is greater than "max" coordinates, the returned Vector2 is given this "max" coordinate
  2662. * @param value defines the value to clamp
  2663. * @param min defines the lower limit
  2664. * @param max defines the upper limit
  2665. * @returns a new Vector2
  2666. */
  2667. Vector2.Clamp = function (value, min, max) {
  2668. var x = value.x;
  2669. x = (x > max.x) ? max.x : x;
  2670. x = (x < min.x) ? min.x : x;
  2671. var y = value.y;
  2672. y = (y > max.y) ? max.y : y;
  2673. y = (y < min.y) ? min.y : y;
  2674. return new Vector2(x, y);
  2675. };
  2676. /**
  2677. * Returns a new Vector2 located for "amount" (float) on the Hermite spline defined by the vectors "value1", "value3", "tangent1", "tangent2"
  2678. * @param value1 defines the 1st control point
  2679. * @param tangent1 defines the outgoing tangent
  2680. * @param value2 defines the 2nd control point
  2681. * @param tangent2 defines the incoming tangent
  2682. * @param amount defines the interpolation factor
  2683. * @returns a new Vector2
  2684. */
  2685. Vector2.Hermite = function (value1, tangent1, value2, tangent2, amount) {
  2686. var squared = amount * amount;
  2687. var cubed = amount * squared;
  2688. var part1 = ((2.0 * cubed) - (3.0 * squared)) + 1.0;
  2689. var part2 = (-2.0 * cubed) + (3.0 * squared);
  2690. var part3 = (cubed - (2.0 * squared)) + amount;
  2691. var part4 = cubed - squared;
  2692. var x = (((value1.x * part1) + (value2.x * part2)) + (tangent1.x * part3)) + (tangent2.x * part4);
  2693. var y = (((value1.y * part1) + (value2.y * part2)) + (tangent1.y * part3)) + (tangent2.y * part4);
  2694. return new Vector2(x, y);
  2695. };
  2696. /**
  2697. * Returns a new Vector2 located for "amount" (float) on the linear interpolation between the vector "start" adn the vector "end".
  2698. * @param start defines the start vector
  2699. * @param end defines the end vector
  2700. * @param amount defines the interpolation factor
  2701. * @returns a new Vector2
  2702. */
  2703. Vector2.Lerp = function (start, end, amount) {
  2704. var x = start.x + ((end.x - start.x) * amount);
  2705. var y = start.y + ((end.y - start.y) * amount);
  2706. return new Vector2(x, y);
  2707. };
  2708. /**
  2709. * Gets the dot product of the vector "left" and the vector "right"
  2710. * @param left defines first vector
  2711. * @param right defines second vector
  2712. * @returns the dot product (float)
  2713. */
  2714. Vector2.Dot = function (left, right) {
  2715. return left.x * right.x + left.y * right.y;
  2716. };
  2717. /**
  2718. * Returns a new Vector2 equal to the normalized given vector
  2719. * @param vector defines the vector to normalize
  2720. * @returns a new Vector2
  2721. */
  2722. Vector2.Normalize = function (vector) {
  2723. var newVector = vector.clone();
  2724. newVector.normalize();
  2725. return newVector;
  2726. };
  2727. /**
  2728. * Gets a new Vector2 set with the minimal coordinate values from the "left" and "right" vectors
  2729. * @param left defines 1st vector
  2730. * @param right defines 2nd vector
  2731. * @returns a new Vector2
  2732. */
  2733. Vector2.Minimize = function (left, right) {
  2734. var x = (left.x < right.x) ? left.x : right.x;
  2735. var y = (left.y < right.y) ? left.y : right.y;
  2736. return new Vector2(x, y);
  2737. };
  2738. /**
  2739. * Gets a new Vecto2 set with the maximal coordinate values from the "left" and "right" vectors
  2740. * @param left defines 1st vector
  2741. * @param right defines 2nd vector
  2742. * @returns a new Vector2
  2743. */
  2744. Vector2.Maximize = function (left, right) {
  2745. var x = (left.x > right.x) ? left.x : right.x;
  2746. var y = (left.y > right.y) ? left.y : right.y;
  2747. return new Vector2(x, y);
  2748. };
  2749. /**
  2750. * Gets a new Vector2 set with the transformed coordinates of the given vector by the given transformation matrix
  2751. * @param vector defines the vector to transform
  2752. * @param transformation defines the matrix to apply
  2753. * @returns a new Vector2
  2754. */
  2755. Vector2.Transform = function (vector, transformation) {
  2756. var r = Vector2.Zero();
  2757. Vector2.TransformToRef(vector, transformation, r);
  2758. return r;
  2759. };
  2760. /**
  2761. * Transforms the given vector coordinates by the given transformation matrix and stores the result in the vector "result" coordinates
  2762. * @param vector defines the vector to transform
  2763. * @param transformation defines the matrix to apply
  2764. * @param result defines the target vector
  2765. */
  2766. Vector2.TransformToRef = function (vector, transformation, result) {
  2767. var x = (vector.x * transformation.m[0]) + (vector.y * transformation.m[4]) + transformation.m[12];
  2768. var y = (vector.x * transformation.m[1]) + (vector.y * transformation.m[5]) + transformation.m[13];
  2769. result.x = x;
  2770. result.y = y;
  2771. };
  2772. /**
  2773. * Determines if a given vector is included in a triangle
  2774. * @param p defines the vector to test
  2775. * @param p0 defines 1st triangle point
  2776. * @param p1 defines 2nd triangle point
  2777. * @param p2 defines 3rd triangle point
  2778. * @returns true if the point "p" is in the triangle defined by the vertors "p0", "p1", "p2"
  2779. */
  2780. Vector2.PointInTriangle = function (p, p0, p1, p2) {
  2781. var a = 1 / 2 * (-p1.y * p2.x + p0.y * (-p1.x + p2.x) + p0.x * (p1.y - p2.y) + p1.x * p2.y);
  2782. var sign = a < 0 ? -1 : 1;
  2783. var s = (p0.y * p2.x - p0.x * p2.y + (p2.y - p0.y) * p.x + (p0.x - p2.x) * p.y) * sign;
  2784. var t = (p0.x * p1.y - p0.y * p1.x + (p0.y - p1.y) * p.x + (p1.x - p0.x) * p.y) * sign;
  2785. return s > 0 && t > 0 && (s + t) < 2 * a * sign;
  2786. };
  2787. /**
  2788. * Gets the distance between the vectors "value1" and "value2"
  2789. * @param value1 defines first vector
  2790. * @param value2 defines second vector
  2791. * @returns the distance between vectors
  2792. */
  2793. Vector2.Distance = function (value1, value2) {
  2794. return Math.sqrt(Vector2.DistanceSquared(value1, value2));
  2795. };
  2796. /**
  2797. * Returns the squared distance between the vectors "value1" and "value2"
  2798. * @param value1 defines first vector
  2799. * @param value2 defines second vector
  2800. * @returns the squared distance between vectors
  2801. */
  2802. Vector2.DistanceSquared = function (value1, value2) {
  2803. var x = value1.x - value2.x;
  2804. var y = value1.y - value2.y;
  2805. return (x * x) + (y * y);
  2806. };
  2807. /**
  2808. * Gets a new Vector2 located at the center of the vectors "value1" and "value2"
  2809. * @param value1 defines first vector
  2810. * @param value2 defines second vector
  2811. * @returns a new Vector2
  2812. */
  2813. Vector2.Center = function (value1, value2) {
  2814. var center = value1.add(value2);
  2815. center.scaleInPlace(0.5);
  2816. return center;
  2817. };
  2818. /**
  2819. * Gets the shortest distance (float) between the point "p" and the segment defined by the two points "segA" and "segB".
  2820. * @param p defines the middle point
  2821. * @param segA defines one point of the segment
  2822. * @param segB defines the other point of the segment
  2823. * @returns the shortest distance
  2824. */
  2825. Vector2.DistanceOfPointFromSegment = function (p, segA, segB) {
  2826. var l2 = Vector2.DistanceSquared(segA, segB);
  2827. if (l2 === 0.0) {
  2828. return Vector2.Distance(p, segA);
  2829. }
  2830. var v = segB.subtract(segA);
  2831. var t = Math.max(0, Math.min(1, Vector2.Dot(p.subtract(segA), v) / l2));
  2832. var proj = segA.add(v.multiplyByFloats(t, t));
  2833. return Vector2.Distance(p, proj);
  2834. };
  2835. return Vector2;
  2836. }());
  2837. BABYLON.Vector2 = Vector2;
  2838. /**
  2839. * Classed used to store (x,y,z) vector representation
  2840. * A Vector3 is the main object used in 3D geometry
  2841. * It can represent etiher the coordinates of a point the space, either a direction
  2842. * Reminder: Babylon.js uses a left handed forward facing system
  2843. */
  2844. var Vector3 = /** @class */ (function () {
  2845. /**
  2846. * Creates a new Vector3 object from the given x, y, z (floats) coordinates.
  2847. * @param x defines the first coordinates (on X axis)
  2848. * @param y defines the second coordinates (on Y axis)
  2849. * @param z defines the third coordinates (on Z axis)
  2850. */
  2851. function Vector3(
  2852. /**
  2853. * Defines the first coordinates (on X axis)
  2854. */
  2855. x,
  2856. /**
  2857. * Defines the second coordinates (on Y axis)
  2858. */
  2859. y,
  2860. /**
  2861. * Defines the third coordinates (on Z axis)
  2862. */
  2863. z) {
  2864. this.x = x;
  2865. this.y = y;
  2866. this.z = z;
  2867. }
  2868. /**
  2869. * Creates a string representation of the Vector3
  2870. * @returns a string with the Vector3 coordinates.
  2871. */
  2872. Vector3.prototype.toString = function () {
  2873. return "{X: " + this.x + " Y:" + this.y + " Z:" + this.z + "}";
  2874. };
  2875. /**
  2876. * Gets the class name
  2877. * @returns the string "Vector3"
  2878. */
  2879. Vector3.prototype.getClassName = function () {
  2880. return "Vector3";
  2881. };
  2882. /**
  2883. * Creates the Vector3 hash code
  2884. * @returns a number which tends to be unique between Vector3 instances
  2885. */
  2886. Vector3.prototype.getHashCode = function () {
  2887. var hash = this.x || 0;
  2888. hash = (hash * 397) ^ (this.y || 0);
  2889. hash = (hash * 397) ^ (this.z || 0);
  2890. return hash;
  2891. };
  2892. // Operators
  2893. /**
  2894. * Creates an array containing three elements : the coordinates of the Vector3
  2895. * @returns a new array of numbers
  2896. */
  2897. Vector3.prototype.asArray = function () {
  2898. var result = [];
  2899. this.toArray(result, 0);
  2900. return result;
  2901. };
  2902. /**
  2903. * Populates the given array or Float32Array from the given index with the successive coordinates of the Vector3
  2904. * @param array defines the destination array
  2905. * @param index defines the offset in the destination array
  2906. * @returns the current Vector3
  2907. */
  2908. Vector3.prototype.toArray = function (array, index) {
  2909. if (index === void 0) { index = 0; }
  2910. array[index] = this.x;
  2911. array[index + 1] = this.y;
  2912. array[index + 2] = this.z;
  2913. return this;
  2914. };
  2915. /**
  2916. * Converts the current Vector3 into a quaternion (considering that the Vector3 contains Euler angles representation of a rotation)
  2917. * @returns a new Quaternion object, computed from the Vector3 coordinates
  2918. */
  2919. Vector3.prototype.toQuaternion = function () {
  2920. var result = new Quaternion(0.0, 0.0, 0.0, 1.0);
  2921. var cosxPlusz = Math.cos((this.x + this.z) * 0.5);
  2922. var sinxPlusz = Math.sin((this.x + this.z) * 0.5);
  2923. var coszMinusx = Math.cos((this.z - this.x) * 0.5);
  2924. var sinzMinusx = Math.sin((this.z - this.x) * 0.5);
  2925. var cosy = Math.cos(this.y * 0.5);
  2926. var siny = Math.sin(this.y * 0.5);
  2927. result.x = coszMinusx * siny;
  2928. result.y = -sinzMinusx * siny;
  2929. result.z = sinxPlusz * cosy;
  2930. result.w = cosxPlusz * cosy;
  2931. return result;
  2932. };
  2933. /**
  2934. * Adds the given vector to the current Vector3
  2935. * @param otherVector defines the second operand
  2936. * @returns the current updated Vector3
  2937. */
  2938. Vector3.prototype.addInPlace = function (otherVector) {
  2939. this.x += otherVector.x;
  2940. this.y += otherVector.y;
  2941. this.z += otherVector.z;
  2942. return this;
  2943. };
  2944. /**
  2945. * Gets a new Vector3, result of the addition the current Vector3 and the given vector
  2946. * @param otherVector defines the second operand
  2947. * @returns the resulting Vector3
  2948. */
  2949. Vector3.prototype.add = function (otherVector) {
  2950. return new Vector3(this.x + otherVector.x, this.y + otherVector.y, this.z + otherVector.z);
  2951. };
  2952. /**
  2953. * Adds the current Vector3 to the given one and stores the result in the vector "result"
  2954. * @param otherVector defines the second operand
  2955. * @param result defines the Vector3 object where to store the result
  2956. * @returns the current Vector3
  2957. */
  2958. Vector3.prototype.addToRef = function (otherVector, result) {
  2959. result.x = this.x + otherVector.x;
  2960. result.y = this.y + otherVector.y;
  2961. result.z = this.z + otherVector.z;
  2962. return this;
  2963. };
  2964. /**
  2965. * Subtract the given vector from the current Vector3
  2966. * @param otherVector defines the second operand
  2967. * @returns the current updated Vector3
  2968. */
  2969. Vector3.prototype.subtractInPlace = function (otherVector) {
  2970. this.x -= otherVector.x;
  2971. this.y -= otherVector.y;
  2972. this.z -= otherVector.z;
  2973. return this;
  2974. };
  2975. /**
  2976. * Returns a new Vector3, result of the subtraction of the given vector from the current Vector3
  2977. * @param otherVector defines the second operand
  2978. * @returns the resulting Vector3
  2979. */
  2980. Vector3.prototype.subtract = function (otherVector) {
  2981. return new Vector3(this.x - otherVector.x, this.y - otherVector.y, this.z - otherVector.z);
  2982. };
  2983. /**
  2984. * Subtracts the given vector from the current Vector3 and stores the result in the vector "result".
  2985. * @param otherVector defines the second operand
  2986. * @param result defines the Vector3 object where to store the result
  2987. * @returns the current Vector3
  2988. */
  2989. Vector3.prototype.subtractToRef = function (otherVector, result) {
  2990. result.x = this.x - otherVector.x;
  2991. result.y = this.y - otherVector.y;
  2992. result.z = this.z - otherVector.z;
  2993. return this;
  2994. };
  2995. /**
  2996. * Returns a new Vector3 set with the subtraction of the given floats from the current Vector3 coordinates
  2997. * @param x defines the x coordinate of the operand
  2998. * @param y defines the y coordinate of the operand
  2999. * @param z defines the z coordinate of the operand
  3000. * @returns the resulting Vector3
  3001. */
  3002. Vector3.prototype.subtractFromFloats = function (x, y, z) {
  3003. return new Vector3(this.x - x, this.y - y, this.z - z);
  3004. };
  3005. /**
  3006. * Subtracts the given floats from the current Vector3 coordinates and set the given vector "result" with this result
  3007. * @param x defines the x coordinate of the operand
  3008. * @param y defines the y coordinate of the operand
  3009. * @param z defines the z coordinate of the operand
  3010. * @param result defines the Vector3 object where to store the result
  3011. * @returns the current Vector3
  3012. */
  3013. Vector3.prototype.subtractFromFloatsToRef = function (x, y, z, result) {
  3014. result.x = this.x - x;
  3015. result.y = this.y - y;
  3016. result.z = this.z - z;
  3017. return this;
  3018. };
  3019. /**
  3020. * Gets a new Vector3 set with the current Vector3 negated coordinates
  3021. * @returns a new Vector3
  3022. */
  3023. Vector3.prototype.negate = function () {
  3024. return new Vector3(-this.x, -this.y, -this.z);
  3025. };
  3026. /**
  3027. * Multiplies the Vector3 coordinates by the float "scale"
  3028. * @param scale defines the multiplier factor
  3029. * @returns the current updated Vector3
  3030. */
  3031. Vector3.prototype.scaleInPlace = function (scale) {
  3032. this.x *= scale;
  3033. this.y *= scale;
  3034. this.z *= scale;
  3035. return this;
  3036. };
  3037. /**
  3038. * Returns a new Vector3 set with the current Vector3 coordinates multiplied by the float "scale"
  3039. * @param scale defines the multiplier factor
  3040. * @returns a new Vector3
  3041. */
  3042. Vector3.prototype.scale = function (scale) {
  3043. return new Vector3(this.x * scale, this.y * scale, this.z * scale);
  3044. };
  3045. /**
  3046. * Multiplies the current Vector3 coordinates by the float "scale" and stores the result in the given vector "result" coordinates
  3047. * @param scale defines the multiplier factor
  3048. * @param result defines the Vector3 object where to store the result
  3049. * @returns the current Vector3
  3050. */
  3051. Vector3.prototype.scaleToRef = function (scale, result) {
  3052. result.x = this.x * scale;
  3053. result.y = this.y * scale;
  3054. result.z = this.z * scale;
  3055. return this;
  3056. };
  3057. /**
  3058. * Scale the current Vector3 values by a factor and add the result to a given Vector3
  3059. * @param scale defines the scale factor
  3060. * @param result defines the Vector3 object where to store the result
  3061. * @returns the unmodified current Vector3
  3062. */
  3063. Vector3.prototype.scaleAndAddToRef = function (scale, result) {
  3064. result.x += this.x * scale;
  3065. result.y += this.y * scale;
  3066. result.z += this.z * scale;
  3067. return this;
  3068. };
  3069. /**
  3070. * Returns true if the current Vector3 and the given vector coordinates are strictly equal
  3071. * @param otherVector defines the second operand
  3072. * @returns true if both vectors are equals
  3073. */
  3074. Vector3.prototype.equals = function (otherVector) {
  3075. return otherVector && this.x === otherVector.x && this.y === otherVector.y && this.z === otherVector.z;
  3076. };
  3077. /**
  3078. * Returns true if the current Vector3 and the given vector coordinates are distant less than epsilon
  3079. * @param otherVector defines the second operand
  3080. * @param epsilon defines the minimal distance to define values as equals
  3081. * @returns true if both vectors are distant less than epsilon
  3082. */
  3083. Vector3.prototype.equalsWithEpsilon = function (otherVector, epsilon) {
  3084. if (epsilon === void 0) { epsilon = BABYLON.Epsilon; }
  3085. 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);
  3086. };
  3087. /**
  3088. * Returns true if the current Vector3 coordinates equals the given floats
  3089. * @param x defines the x coordinate of the operand
  3090. * @param y defines the y coordinate of the operand
  3091. * @param z defines the z coordinate of the operand
  3092. * @returns true if both vectors are equals
  3093. */
  3094. Vector3.prototype.equalsToFloats = function (x, y, z) {
  3095. return this.x === x && this.y === y && this.z === z;
  3096. };
  3097. /**
  3098. * Multiplies the current Vector3 coordinates by the given ones
  3099. * @param otherVector defines the second operand
  3100. * @returns the current updated Vector3
  3101. */
  3102. Vector3.prototype.multiplyInPlace = function (otherVector) {
  3103. this.x *= otherVector.x;
  3104. this.y *= otherVector.y;
  3105. this.z *= otherVector.z;
  3106. return this;
  3107. };
  3108. /**
  3109. * Returns a new Vector3, result of the multiplication of the current Vector3 by the given vector
  3110. * @param otherVector defines the second operand
  3111. * @returns the new Vector3
  3112. */
  3113. Vector3.prototype.multiply = function (otherVector) {
  3114. return new Vector3(this.x * otherVector.x, this.y * otherVector.y, this.z * otherVector.z);
  3115. };
  3116. /**
  3117. * Multiplies the current Vector3 by the given one and stores the result in the given vector "result"
  3118. * @param otherVector defines the second operand
  3119. * @param result defines the Vector3 object where to store the result
  3120. * @returns the current Vector3
  3121. */
  3122. Vector3.prototype.multiplyToRef = function (otherVector, result) {
  3123. result.x = this.x * otherVector.x;
  3124. result.y = this.y * otherVector.y;
  3125. result.z = this.z * otherVector.z;
  3126. return this;
  3127. };
  3128. /**
  3129. * Returns a new Vector3 set with the result of the mulliplication of the current Vector3 coordinates by the given floats
  3130. * @param x defines the x coordinate of the operand
  3131. * @param y defines the y coordinate of the operand
  3132. * @param z defines the z coordinate of the operand
  3133. * @returns the new Vector3
  3134. */
  3135. Vector3.prototype.multiplyByFloats = function (x, y, z) {
  3136. return new Vector3(this.x * x, this.y * y, this.z * z);
  3137. };
  3138. /**
  3139. * Returns a new Vector3 set with the result of the division of the current Vector3 coordinates by the given ones
  3140. * @param otherVector defines the second operand
  3141. * @returns the new Vector3
  3142. */
  3143. Vector3.prototype.divide = function (otherVector) {
  3144. return new Vector3(this.x / otherVector.x, this.y / otherVector.y, this.z / otherVector.z);
  3145. };
  3146. /**
  3147. * Divides the current Vector3 coordinates by the given ones and stores the result in the given vector "result"
  3148. * @param otherVector defines the second operand
  3149. * @param result defines the Vector3 object where to store the result
  3150. * @returns the current Vector3
  3151. */
  3152. Vector3.prototype.divideToRef = function (otherVector, result) {
  3153. result.x = this.x / otherVector.x;
  3154. result.y = this.y / otherVector.y;
  3155. result.z = this.z / otherVector.z;
  3156. return this;
  3157. };
  3158. /**
  3159. * Divides the current Vector3 coordinates by the given ones.
  3160. * @param otherVector defines the second operand
  3161. * @returns the current updated Vector3
  3162. */
  3163. Vector3.prototype.divideInPlace = function (otherVector) {
  3164. return this.divideToRef(otherVector, this);
  3165. };
  3166. /**
  3167. * Updates the current Vector3 with the minimal coordinate values between its and the given vector ones
  3168. * @param other defines the second operand
  3169. * @returns the current updated Vector3
  3170. */
  3171. Vector3.prototype.minimizeInPlace = function (other) {
  3172. if (other.x < this.x)
  3173. this.x = other.x;
  3174. if (other.y < this.y)
  3175. this.y = other.y;
  3176. if (other.z < this.z)
  3177. this.z = other.z;
  3178. return this;
  3179. };
  3180. /**
  3181. * Updates the current Vector3 with the maximal coordinate values between its and the given vector ones.
  3182. * @param other defines the second operand
  3183. * @returns the current updated Vector3
  3184. */
  3185. Vector3.prototype.maximizeInPlace = function (other) {
  3186. if (other.x > this.x)
  3187. this.x = other.x;
  3188. if (other.y > this.y)
  3189. this.y = other.y;
  3190. if (other.z > this.z)
  3191. this.z = other.z;
  3192. return this;
  3193. };
  3194. Object.defineProperty(Vector3.prototype, "isNonUniform", {
  3195. /**
  3196. * Gets a boolean indicating that the vector is non uniform meaning x, y or z are not all the same
  3197. */
  3198. get: function () {
  3199. var absX = Math.abs(this.x);
  3200. var absY = Math.abs(this.y);
  3201. if (absX !== absY) {
  3202. return true;
  3203. }
  3204. var absZ = Math.abs(this.z);
  3205. if (absX !== absZ) {
  3206. return true;
  3207. }
  3208. if (absY !== absZ) {
  3209. return true;
  3210. }
  3211. return false;
  3212. },
  3213. enumerable: true,
  3214. configurable: true
  3215. });
  3216. // Properties
  3217. /**
  3218. * Gets the length of the Vector3
  3219. * @returns the length of the Vecto3
  3220. */
  3221. Vector3.prototype.length = function () {
  3222. return Math.sqrt(this.x * this.x + this.y * this.y + this.z * this.z);
  3223. };
  3224. /**
  3225. * Gets the squared length of the Vector3
  3226. * @returns squared length of the Vector3
  3227. */
  3228. Vector3.prototype.lengthSquared = function () {
  3229. return (this.x * this.x + this.y * this.y + this.z * this.z);
  3230. };
  3231. /**
  3232. * Normalize the current Vector3.
  3233. * Please note that this is an in place operation.
  3234. * @returns the current updated Vector3
  3235. */
  3236. Vector3.prototype.normalize = function () {
  3237. var len = this.length();
  3238. if (len === 0 || len === 1.0)
  3239. return this;
  3240. var num = 1.0 / len;
  3241. this.x *= num;
  3242. this.y *= num;
  3243. this.z *= num;
  3244. return this;
  3245. };
  3246. /**
  3247. * Normalize the current Vector3 to a new vector
  3248. * @returns the new Vector3
  3249. */
  3250. Vector3.prototype.normalizeToNew = function () {
  3251. var normalized = new Vector3(0, 0, 0);
  3252. this.normalizeToRef(normalized);
  3253. return normalized;
  3254. };
  3255. /**
  3256. * Normalize the current Vector3 to the reference
  3257. * @param reference define the Vector3 to update
  3258. * @returns the updated Vector3
  3259. */
  3260. Vector3.prototype.normalizeToRef = function (reference) {
  3261. var len = this.length();
  3262. if (len === 0 || len === 1.0) {
  3263. reference.set(this.x, this.y, this.z);
  3264. return reference;
  3265. }
  3266. var scale = 1.0 / len;
  3267. this.scaleToRef(scale, reference);
  3268. return reference;
  3269. };
  3270. /**
  3271. * Creates a new Vector3 copied from the current Vector3
  3272. * @returns the new Vector3
  3273. */
  3274. Vector3.prototype.clone = function () {
  3275. return new Vector3(this.x, this.y, this.z);
  3276. };
  3277. /**
  3278. * Copies the given vector coordinates to the current Vector3 ones
  3279. * @param source defines the source Vector3
  3280. * @returns the current updated Vector3
  3281. */
  3282. Vector3.prototype.copyFrom = function (source) {
  3283. this.x = source.x;
  3284. this.y = source.y;
  3285. this.z = source.z;
  3286. return this;
  3287. };
  3288. /**
  3289. * Copies the given floats to the current Vector3 coordinates
  3290. * @param x defines the x coordinate of the operand
  3291. * @param y defines the y coordinate of the operand
  3292. * @param z defines the z coordinate of the operand
  3293. * @returns the current updated Vector3
  3294. */
  3295. Vector3.prototype.copyFromFloats = function (x, y, z) {
  3296. this.x = x;
  3297. this.y = y;
  3298. this.z = z;
  3299. return this;
  3300. };
  3301. /**
  3302. * Copies the given floats to the current Vector3 coordinates
  3303. * @param x defines the x coordinate of the operand
  3304. * @param y defines the y coordinate of the operand
  3305. * @param z defines the z coordinate of the operand
  3306. * @returns the current updated Vector3
  3307. */
  3308. Vector3.prototype.set = function (x, y, z) {
  3309. return this.copyFromFloats(x, y, z);
  3310. };
  3311. // Statics
  3312. /**
  3313. * Get the clip factor between two vectors
  3314. * @param vector0 defines the first operand
  3315. * @param vector1 defines the second operand
  3316. * @param axis defines the axis to use
  3317. * @param size defines the size along the axis
  3318. * @returns the clip factor
  3319. */
  3320. Vector3.GetClipFactor = function (vector0, vector1, axis, size) {
  3321. var d0 = Vector3.Dot(vector0, axis) - size;
  3322. var d1 = Vector3.Dot(vector1, axis) - size;
  3323. var s = d0 / (d0 - d1);
  3324. return s;
  3325. };
  3326. /**
  3327. * Get angle between two vectors
  3328. * @param vector0 angle between vector0 and vector1
  3329. * @param vector1 angle between vector0 and vector1
  3330. * @param normal direction of the normal
  3331. * @return the angle between vector0 and vector1
  3332. */
  3333. Vector3.GetAngleBetweenVectors = function (vector0, vector1, normal) {
  3334. var v0 = vector0.clone().normalize();
  3335. var v1 = vector1.clone().normalize();
  3336. var dot = Vector3.Dot(v0, v1);
  3337. var n = Vector3.Cross(v0, v1);
  3338. if (Vector3.Dot(n, normal) > 0) {
  3339. return Math.acos(dot);
  3340. }
  3341. return -Math.acos(dot);
  3342. };
  3343. /**
  3344. * Returns a new Vector3 set from the index "offset" of the given array
  3345. * @param array defines the source array
  3346. * @param offset defines the offset in the source array
  3347. * @returns the new Vector3
  3348. */
  3349. Vector3.FromArray = function (array, offset) {
  3350. if (!offset) {
  3351. offset = 0;
  3352. }
  3353. return new Vector3(array[offset], array[offset + 1], array[offset + 2]);
  3354. };
  3355. /**
  3356. * Returns a new Vector3 set from the index "offset" of the given Float32Array
  3357. * This function is deprecated. Use FromArray instead
  3358. * @param array defines the source array
  3359. * @param offset defines the offset in the source array
  3360. * @returns the new Vector3
  3361. */
  3362. Vector3.FromFloatArray = function (array, offset) {
  3363. return Vector3.FromArray(array, offset);
  3364. };
  3365. /**
  3366. * Sets the given vector "result" with the element values from the index "offset" of the given array
  3367. * @param array defines the source array
  3368. * @param offset defines the offset in the source array
  3369. * @param result defines the Vector3 where to store the result
  3370. */
  3371. Vector3.FromArrayToRef = function (array, offset, result) {
  3372. result.x = array[offset];
  3373. result.y = array[offset + 1];
  3374. result.z = array[offset + 2];
  3375. };
  3376. /**
  3377. * Sets the given vector "result" with the element values from the index "offset" of the given Float32Array
  3378. * This function is deprecated. Use FromArrayToRef instead.
  3379. * @param array defines the source array
  3380. * @param offset defines the offset in the source array
  3381. * @param result defines the Vector3 where to store the result
  3382. */
  3383. Vector3.FromFloatArrayToRef = function (array, offset, result) {
  3384. return Vector3.FromArrayToRef(array, offset, result);
  3385. };
  3386. /**
  3387. * Sets the given vector "result" with the given floats.
  3388. * @param x defines the x coordinate of the source
  3389. * @param y defines the y coordinate of the source
  3390. * @param z defines the z coordinate of the source
  3391. * @param result defines the Vector3 where to store the result
  3392. */
  3393. Vector3.FromFloatsToRef = function (x, y, z, result) {
  3394. result.x = x;
  3395. result.y = y;
  3396. result.z = z;
  3397. };
  3398. /**
  3399. * Returns a new Vector3 set to (0.0, 0.0, 0.0)
  3400. * @returns a new empty Vector3
  3401. */
  3402. Vector3.Zero = function () {
  3403. return new Vector3(0.0, 0.0, 0.0);
  3404. };
  3405. /**
  3406. * Returns a new Vector3 set to (1.0, 1.0, 1.0)
  3407. * @returns a new unit Vector3
  3408. */
  3409. Vector3.One = function () {
  3410. return new Vector3(1.0, 1.0, 1.0);
  3411. };
  3412. /**
  3413. * Returns a new Vector3 set to (0.0, 1.0, 0.0)
  3414. * @returns a new up Vector3
  3415. */
  3416. Vector3.Up = function () {
  3417. return new Vector3(0.0, 1.0, 0.0);
  3418. };
  3419. /**
  3420. * Returns a new Vector3 set to (0.0, 0.0, 1.0)
  3421. * @returns a new forward Vector3
  3422. */
  3423. Vector3.Forward = function () {
  3424. return new Vector3(0.0, 0.0, 1.0);
  3425. };
  3426. /**
  3427. * Returns a new Vector3 set to (1.0, 0.0, 0.0)
  3428. * @returns a new right Vector3
  3429. */
  3430. Vector3.Right = function () {
  3431. return new Vector3(1.0, 0.0, 0.0);
  3432. };
  3433. /**
  3434. * Returns a new Vector3 set to (-1.0, 0.0, 0.0)
  3435. * @returns a new left Vector3
  3436. */
  3437. Vector3.Left = function () {
  3438. return new Vector3(-1.0, 0.0, 0.0);
  3439. };
  3440. /**
  3441. * Returns a new Vector3 set with the result of the transformation by the given matrix of the given vector.
  3442. * This method computes tranformed coordinates only, not transformed direction vectors (ie. it takes translation in account)
  3443. * @param vector defines the Vector3 to transform
  3444. * @param transformation defines the transformation matrix
  3445. * @returns the transformed Vector3
  3446. */
  3447. Vector3.TransformCoordinates = function (vector, transformation) {
  3448. var result = Vector3.Zero();
  3449. Vector3.TransformCoordinatesToRef(vector, transformation, result);
  3450. return result;
  3451. };
  3452. /**
  3453. * Sets the given vector "result" coordinates with the result of the transformation by the given matrix of the given vector
  3454. * This method computes tranformed coordinates only, not transformed direction vectors (ie. it takes translation in account)
  3455. * @param vector defines the Vector3 to transform
  3456. * @param transformation defines the transformation matrix
  3457. * @param result defines the Vector3 where to store the result
  3458. */
  3459. Vector3.TransformCoordinatesToRef = function (vector, transformation, result) {
  3460. var x = (vector.x * transformation.m[0]) + (vector.y * transformation.m[4]) + (vector.z * transformation.m[8]) + transformation.m[12];
  3461. var y = (vector.x * transformation.m[1]) + (vector.y * transformation.m[5]) + (vector.z * transformation.m[9]) + transformation.m[13];
  3462. var z = (vector.x * transformation.m[2]) + (vector.y * transformation.m[6]) + (vector.z * transformation.m[10]) + transformation.m[14];
  3463. var w = (vector.x * transformation.m[3]) + (vector.y * transformation.m[7]) + (vector.z * transformation.m[11]) + transformation.m[15];
  3464. result.x = x / w;
  3465. result.y = y / w;
  3466. result.z = z / w;
  3467. };
  3468. /**
  3469. * Sets the given vector "result" coordinates with the result of the transformation by the given matrix of the given floats (x, y, z)
  3470. * This method computes tranformed coordinates only, not transformed direction vectors
  3471. * @param x define the x coordinate of the source vector
  3472. * @param y define the y coordinate of the source vector
  3473. * @param z define the z coordinate of the source vector
  3474. * @param transformation defines the transformation matrix
  3475. * @param result defines the Vector3 where to store the result
  3476. */
  3477. Vector3.TransformCoordinatesFromFloatsToRef = function (x, y, z, transformation, result) {
  3478. var rx = (x * transformation.m[0]) + (y * transformation.m[4]) + (z * transformation.m[8]) + transformation.m[12];
  3479. var ry = (x * transformation.m[1]) + (y * transformation.m[5]) + (z * transformation.m[9]) + transformation.m[13];
  3480. var rz = (x * transformation.m[2]) + (y * transformation.m[6]) + (z * transformation.m[10]) + transformation.m[14];
  3481. var rw = (x * transformation.m[3]) + (y * transformation.m[7]) + (z * transformation.m[11]) + transformation.m[15];
  3482. result.x = rx / rw;
  3483. result.y = ry / rw;
  3484. result.z = rz / rw;
  3485. };
  3486. /**
  3487. * Returns a new Vector3 set with the result of the normal transformation by the given matrix of the given vector
  3488. * This methods computes transformed normalized direction vectors only (ie. it does not apply translation)
  3489. * @param vector defines the Vector3 to transform
  3490. * @param transformation defines the transformation matrix
  3491. * @returns the new Vector3
  3492. */
  3493. Vector3.TransformNormal = function (vector, transformation) {
  3494. var result = Vector3.Zero();
  3495. Vector3.TransformNormalToRef(vector, transformation, result);
  3496. return result;
  3497. };
  3498. /**
  3499. * Sets the given vector "result" with the result of the normal transformation by the given matrix of the given vector
  3500. * This methods computes transformed normalized direction vectors only (ie. it does not apply translation)
  3501. * @param vector defines the Vector3 to transform
  3502. * @param transformation defines the transformation matrix
  3503. * @param result defines the Vector3 where to store the result
  3504. */
  3505. Vector3.TransformNormalToRef = function (vector, transformation, result) {
  3506. var x = (vector.x * transformation.m[0]) + (vector.y * transformation.m[4]) + (vector.z * transformation.m[8]);
  3507. var y = (vector.x * transformation.m[1]) + (vector.y * transformation.m[5]) + (vector.z * transformation.m[9]);
  3508. var z = (vector.x * transformation.m[2]) + (vector.y * transformation.m[6]) + (vector.z * transformation.m[10]);
  3509. result.x = x;
  3510. result.y = y;
  3511. result.z = z;
  3512. };
  3513. /**
  3514. * Sets the given vector "result" with the result of the normal transformation by the given matrix of the given floats (x, y, z)
  3515. * This methods computes transformed normalized direction vectors only (ie. it does not apply translation)
  3516. * @param x define the x coordinate of the source vector
  3517. * @param y define the y coordinate of the source vector
  3518. * @param z define the z coordinate of the source vector
  3519. * @param transformation defines the transformation matrix
  3520. * @param result defines the Vector3 where to store the result
  3521. */
  3522. Vector3.TransformNormalFromFloatsToRef = function (x, y, z, transformation, result) {
  3523. result.x = (x * transformation.m[0]) + (y * transformation.m[4]) + (z * transformation.m[8]);
  3524. result.y = (x * transformation.m[1]) + (y * transformation.m[5]) + (z * transformation.m[9]);
  3525. result.z = (x * transformation.m[2]) + (y * transformation.m[6]) + (z * transformation.m[10]);
  3526. };
  3527. /**
  3528. * Returns a new Vector3 located for "amount" on the CatmullRom interpolation spline defined by the vectors "value1", "value2", "value3", "value4"
  3529. * @param value1 defines the first control point
  3530. * @param value2 defines the second control point
  3531. * @param value3 defines the third control point
  3532. * @param value4 defines the fourth control point
  3533. * @param amount defines the amount on the spline to use
  3534. * @returns the new Vector3
  3535. */
  3536. Vector3.CatmullRom = function (value1, value2, value3, value4, amount) {
  3537. var squared = amount * amount;
  3538. var cubed = amount * squared;
  3539. var x = 0.5 * ((((2.0 * value2.x) + ((-value1.x + value3.x) * amount)) +
  3540. (((((2.0 * value1.x) - (5.0 * value2.x)) + (4.0 * value3.x)) - value4.x) * squared)) +
  3541. ((((-value1.x + (3.0 * value2.x)) - (3.0 * value3.x)) + value4.x) * cubed));
  3542. var y = 0.5 * ((((2.0 * value2.y) + ((-value1.y + value3.y) * amount)) +
  3543. (((((2.0 * value1.y) - (5.0 * value2.y)) + (4.0 * value3.y)) - value4.y) * squared)) +
  3544. ((((-value1.y + (3.0 * value2.y)) - (3.0 * value3.y)) + value4.y) * cubed));
  3545. var z = 0.5 * ((((2.0 * value2.z) + ((-value1.z + value3.z) * amount)) +
  3546. (((((2.0 * value1.z) - (5.0 * value2.z)) + (4.0 * value3.z)) - value4.z) * squared)) +
  3547. ((((-value1.z + (3.0 * value2.z)) - (3.0 * value3.z)) + value4.z) * cubed));
  3548. return new Vector3(x, y, z);
  3549. };
  3550. /**
  3551. * 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"
  3552. * If a coordinate value of "value" is lower than one of the "min" coordinate, then this "value" coordinate is set with the "min" one
  3553. * If a coordinate value of "value" is greater than one of the "max" coordinate, then this "value" coordinate is set with the "max" one
  3554. * @param value defines the current value
  3555. * @param min defines the lower range value
  3556. * @param max defines the upper range value
  3557. * @returns the new Vector3
  3558. */
  3559. Vector3.Clamp = function (value, min, max) {
  3560. var x = value.x;
  3561. x = (x > max.x) ? max.x : x;
  3562. x = (x < min.x) ? min.x : x;
  3563. var y = value.y;
  3564. y = (y > max.y) ? max.y : y;
  3565. y = (y < min.y) ? min.y : y;
  3566. var z = value.z;
  3567. z = (z > max.z) ? max.z : z;
  3568. z = (z < min.z) ? min.z : z;
  3569. return new Vector3(x, y, z);
  3570. };
  3571. /**
  3572. * Returns a new Vector3 located for "amount" (float) on the Hermite interpolation spline defined by the vectors "value1", "tangent1", "value2", "tangent2"
  3573. * @param value1 defines the first control point
  3574. * @param tangent1 defines the first tangent vector
  3575. * @param value2 defines the second control point
  3576. * @param tangent2 defines the second tangent vector
  3577. * @param amount defines the amount on the interpolation spline (between 0 and 1)
  3578. * @returns the new Vector3
  3579. */
  3580. Vector3.Hermite = function (value1, tangent1, value2, tangent2, amount) {
  3581. var squared = amount * amount;
  3582. var cubed = amount * squared;
  3583. var part1 = ((2.0 * cubed) - (3.0 * squared)) + 1.0;
  3584. var part2 = (-2.0 * cubed) + (3.0 * squared);
  3585. var part3 = (cubed - (2.0 * squared)) + amount;
  3586. var part4 = cubed - squared;
  3587. var x = (((value1.x * part1) + (value2.x * part2)) + (tangent1.x * part3)) + (tangent2.x * part4);
  3588. var y = (((value1.y * part1) + (value2.y * part2)) + (tangent1.y * part3)) + (tangent2.y * part4);
  3589. var z = (((value1.z * part1) + (value2.z * part2)) + (tangent1.z * part3)) + (tangent2.z * part4);
  3590. return new Vector3(x, y, z);
  3591. };
  3592. /**
  3593. * Returns a new Vector3 located for "amount" (float) on the linear interpolation between the vectors "start" and "end"
  3594. * @param start defines the start value
  3595. * @param end defines the end value
  3596. * @param amount max defines amount between both (between 0 and 1)
  3597. * @returns the new Vector3
  3598. */
  3599. Vector3.Lerp = function (start, end, amount) {
  3600. var result = new Vector3(0, 0, 0);
  3601. Vector3.LerpToRef(start, end, amount, result);
  3602. return result;
  3603. };
  3604. /**
  3605. * Sets the given vector "result" with the result of the linear interpolation from the vector "start" for "amount" to the vector "end"
  3606. * @param start defines the start value
  3607. * @param end defines the end value
  3608. * @param amount max defines amount between both (between 0 and 1)
  3609. * @param result defines the Vector3 where to store the result
  3610. */
  3611. Vector3.LerpToRef = function (start, end, amount, result) {
  3612. result.x = start.x + ((end.x - start.x) * amount);
  3613. result.y = start.y + ((end.y - start.y) * amount);
  3614. result.z = start.z + ((end.z - start.z) * amount);
  3615. };
  3616. /**
  3617. * Returns the dot product (float) between the vectors "left" and "right"
  3618. * @param left defines the left operand
  3619. * @param right defines the right operand
  3620. * @returns the dot product
  3621. */
  3622. Vector3.Dot = function (left, right) {
  3623. return (left.x * right.x + left.y * right.y + left.z * right.z);
  3624. };
  3625. /**
  3626. * Returns a new Vector3 as the cross product of the vectors "left" and "right"
  3627. * The cross product is then orthogonal to both "left" and "right"
  3628. * @param left defines the left operand
  3629. * @param right defines the right operand
  3630. * @returns the cross product
  3631. */
  3632. Vector3.Cross = function (left, right) {
  3633. var result = Vector3.Zero();
  3634. Vector3.CrossToRef(left, right, result);
  3635. return result;
  3636. };
  3637. /**
  3638. * Sets the given vector "result" with the cross product of "left" and "right"
  3639. * The cross product is then orthogonal to both "left" and "right"
  3640. * @param left defines the left operand
  3641. * @param right defines the right operand
  3642. * @param result defines the Vector3 where to store the result
  3643. */
  3644. Vector3.CrossToRef = function (left, right, result) {
  3645. MathTmp.Vector3[0].x = left.y * right.z - left.z * right.y;
  3646. MathTmp.Vector3[0].y = left.z * right.x - left.x * right.z;
  3647. MathTmp.Vector3[0].z = left.x * right.y - left.y * right.x;
  3648. result.copyFrom(MathTmp.Vector3[0]);
  3649. };
  3650. /**
  3651. * Returns a new Vector3 as the normalization of the given vector
  3652. * @param vector defines the Vector3 to normalize
  3653. * @returns the new Vector3
  3654. */
  3655. Vector3.Normalize = function (vector) {
  3656. var result = Vector3.Zero();
  3657. Vector3.NormalizeToRef(vector, result);
  3658. return result;
  3659. };
  3660. /**
  3661. * Sets the given vector "result" with the normalization of the given first vector
  3662. * @param vector defines the Vector3 to normalize
  3663. * @param result defines the Vector3 where to store the result
  3664. */
  3665. Vector3.NormalizeToRef = function (vector, result) {
  3666. result.copyFrom(vector);
  3667. result.normalize();
  3668. };
  3669. /**
  3670. * Project a Vector3 onto screen space
  3671. * @param vector defines the Vector3 to project
  3672. * @param world defines the world matrix to use
  3673. * @param transform defines the transform (view x projection) matrix to use
  3674. * @param viewport defines the screen viewport to use
  3675. * @returns the new Vector3
  3676. */
  3677. Vector3.Project = function (vector, world, transform, viewport) {
  3678. var cw = viewport.width;
  3679. var ch = viewport.height;
  3680. var cx = viewport.x;
  3681. var cy = viewport.y;
  3682. var viewportMatrix = Vector3._viewportMatrixCache ? Vector3._viewportMatrixCache : (Vector3._viewportMatrixCache = new Matrix());
  3683. 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);
  3684. var matrix = MathTmp.Matrix[0];
  3685. world.multiplyToRef(transform, matrix);
  3686. matrix.multiplyToRef(viewportMatrix, matrix);
  3687. return Vector3.TransformCoordinates(vector, matrix);
  3688. };
  3689. /**
  3690. * Unproject from screen space to object space
  3691. * @param source defines the screen space Vector3 to use
  3692. * @param viewportWidth defines the current width of the viewport
  3693. * @param viewportHeight defines the current height of the viewport
  3694. * @param world defines the world matrix to use (can be set to Identity to go to world space)
  3695. * @param transform defines the transform (view x projection) matrix to use
  3696. * @returns the new Vector3
  3697. */
  3698. Vector3.UnprojectFromTransform = function (source, viewportWidth, viewportHeight, world, transform) {
  3699. var matrix = MathTmp.Matrix[0];
  3700. world.multiplyToRef(transform, matrix);
  3701. matrix.invert();
  3702. source.x = source.x / viewportWidth * 2 - 1;
  3703. source.y = -(source.y / viewportHeight * 2 - 1);
  3704. var vector = Vector3.TransformCoordinates(source, matrix);
  3705. var num = source.x * matrix.m[3] + source.y * matrix.m[7] + source.z * matrix.m[11] + matrix.m[15];
  3706. if (BABYLON.Scalar.WithinEpsilon(num, 1.0)) {
  3707. vector = vector.scale(1.0 / num);
  3708. }
  3709. return vector;
  3710. };
  3711. /**
  3712. * Unproject from screen space to object space
  3713. * @param source defines the screen space Vector3 to use
  3714. * @param viewportWidth defines the current width of the viewport
  3715. * @param viewportHeight defines the current height of the viewport
  3716. * @param world defines the world matrix to use (can be set to Identity to go to world space)
  3717. * @param view defines the view matrix to use
  3718. * @param projection defines the projection matrix to use
  3719. * @returns the new Vector3
  3720. */
  3721. Vector3.Unproject = function (source, viewportWidth, viewportHeight, world, view, projection) {
  3722. var result = Vector3.Zero();
  3723. Vector3.UnprojectToRef(source, viewportWidth, viewportHeight, world, view, projection, result);
  3724. return result;
  3725. };
  3726. /**
  3727. * Unproject from screen space to object space
  3728. * @param source defines the screen space Vector3 to use
  3729. * @param viewportWidth defines the current width of the viewport
  3730. * @param viewportHeight defines the current height of the viewport
  3731. * @param world defines the world matrix to use (can be set to Identity to go to world space)
  3732. * @param view defines the view matrix to use
  3733. * @param projection defines the projection matrix to use
  3734. * @param result defines the Vector3 where to store the result
  3735. */
  3736. Vector3.UnprojectToRef = function (source, viewportWidth, viewportHeight, world, view, projection, result) {
  3737. Vector3.UnprojectFloatsToRef(source.x, source.y, source.z, viewportWidth, viewportHeight, world, view, projection, result);
  3738. };
  3739. /**
  3740. * Unproject from screen space to object space
  3741. * @param sourceX defines the screen space x coordinate to use
  3742. * @param sourceY defines the screen space y coordinate to use
  3743. * @param sourceZ defines the screen space z coordinate to use
  3744. * @param viewportWidth defines the current width of the viewport
  3745. * @param viewportHeight defines the current height of the viewport
  3746. * @param world defines the world matrix to use (can be set to Identity to go to world space)
  3747. * @param view defines the view matrix to use
  3748. * @param projection defines the projection matrix to use
  3749. * @param result defines the Vector3 where to store the result
  3750. */
  3751. Vector3.UnprojectFloatsToRef = function (sourceX, sourceY, sourceZ, viewportWidth, viewportHeight, world, view, projection, result) {
  3752. var matrix = MathTmp.Matrix[0];
  3753. world.multiplyToRef(view, matrix);
  3754. matrix.multiplyToRef(projection, matrix);
  3755. matrix.invert();
  3756. var screenSource = MathTmp.Vector3[0];
  3757. screenSource.x = sourceX / viewportWidth * 2 - 1;
  3758. screenSource.y = -(sourceY / viewportHeight * 2 - 1);
  3759. screenSource.z = 2 * sourceZ - 1.0;
  3760. Vector3.TransformCoordinatesToRef(screenSource, matrix, result);
  3761. var num = screenSource.x * matrix.m[3] + screenSource.y * matrix.m[7] + screenSource.z * matrix.m[11] + matrix.m[15];
  3762. if (BABYLON.Scalar.WithinEpsilon(num, 1.0)) {
  3763. result.scaleInPlace(1.0 / num);
  3764. }
  3765. };
  3766. /**
  3767. * Gets the minimal coordinate values between two Vector3
  3768. * @param left defines the first operand
  3769. * @param right defines the second operand
  3770. * @returns the new Vector3
  3771. */
  3772. Vector3.Minimize = function (left, right) {
  3773. var min = left.clone();
  3774. min.minimizeInPlace(right);
  3775. return min;
  3776. };
  3777. /**
  3778. * Gets the maximal coordinate values between two Vector3
  3779. * @param left defines the first operand
  3780. * @param right defines the second operand
  3781. * @returns the new Vector3
  3782. */
  3783. Vector3.Maximize = function (left, right) {
  3784. var max = left.clone();
  3785. max.maximizeInPlace(right);
  3786. return max;
  3787. };
  3788. /**
  3789. * Returns the distance between the vectors "value1" and "value2"
  3790. * @param value1 defines the first operand
  3791. * @param value2 defines the second operand
  3792. * @returns the distance
  3793. */
  3794. Vector3.Distance = function (value1, value2) {
  3795. return Math.sqrt(Vector3.DistanceSquared(value1, value2));
  3796. };
  3797. /**
  3798. * Returns the squared distance between the vectors "value1" and "value2"
  3799. * @param value1 defines the first operand
  3800. * @param value2 defines the second operand
  3801. * @returns the squared distance
  3802. */
  3803. Vector3.DistanceSquared = function (value1, value2) {
  3804. var x = value1.x - value2.x;
  3805. var y = value1.y - value2.y;
  3806. var z = value1.z - value2.z;
  3807. return (x * x) + (y * y) + (z * z);
  3808. };
  3809. /**
  3810. * Returns a new Vector3 located at the center between "value1" and "value2"
  3811. * @param value1 defines the first operand
  3812. * @param value2 defines the second operand
  3813. * @returns the new Vector3
  3814. */
  3815. Vector3.Center = function (value1, value2) {
  3816. var center = value1.add(value2);
  3817. center.scaleInPlace(0.5);
  3818. return center;
  3819. };
  3820. /**
  3821. * Given three orthogonal normalized left-handed oriented Vector3 axis in space (target system),
  3822. * RotationFromAxis() returns the rotation Euler angles (ex : rotation.x, rotation.y, rotation.z) to apply
  3823. * to something in order to rotate it from its local system to the given target system
  3824. * Note: axis1, axis2 and axis3 are normalized during this operation
  3825. * @param axis1 defines the first axis
  3826. * @param axis2 defines the second axis
  3827. * @param axis3 defines the third axis
  3828. * @returns a new Vector3
  3829. */
  3830. Vector3.RotationFromAxis = function (axis1, axis2, axis3) {
  3831. var rotation = Vector3.Zero();
  3832. Vector3.RotationFromAxisToRef(axis1, axis2, axis3, rotation);
  3833. return rotation;
  3834. };
  3835. /**
  3836. * The same than RotationFromAxis but updates the given ref Vector3 parameter instead of returning a new Vector3
  3837. * @param axis1 defines the first axis
  3838. * @param axis2 defines the second axis
  3839. * @param axis3 defines the third axis
  3840. * @param ref defines the Vector3 where to store the result
  3841. */
  3842. Vector3.RotationFromAxisToRef = function (axis1, axis2, axis3, ref) {
  3843. var quat = MathTmp.Quaternion[0];
  3844. Quaternion.RotationQuaternionFromAxisToRef(axis1, axis2, axis3, quat);
  3845. quat.toEulerAnglesToRef(ref);
  3846. };
  3847. return Vector3;
  3848. }());
  3849. BABYLON.Vector3 = Vector3;
  3850. //Vector4 class created for EulerAngle class conversion to Quaternion
  3851. var Vector4 = /** @class */ (function () {
  3852. /**
  3853. * Creates a Vector4 object from the given floats.
  3854. */
  3855. function Vector4(x, y, z, w) {
  3856. this.x = x;
  3857. this.y = y;
  3858. this.z = z;
  3859. this.w = w;
  3860. }
  3861. /**
  3862. * Returns the string with the Vector4 coordinates.
  3863. */
  3864. Vector4.prototype.toString = function () {
  3865. return "{X: " + this.x + " Y:" + this.y + " Z:" + this.z + " W:" + this.w + "}";
  3866. };
  3867. /**
  3868. * Returns the string "Vector4".
  3869. */
  3870. Vector4.prototype.getClassName = function () {
  3871. return "Vector4";
  3872. };
  3873. /**
  3874. * Returns the Vector4 hash code.
  3875. */
  3876. Vector4.prototype.getHashCode = function () {
  3877. var hash = this.x || 0;
  3878. hash = (hash * 397) ^ (this.y || 0);
  3879. hash = (hash * 397) ^ (this.z || 0);
  3880. hash = (hash * 397) ^ (this.w || 0);
  3881. return hash;
  3882. };
  3883. // Operators
  3884. /**
  3885. * Returns a new array populated with 4 elements : the Vector4 coordinates.
  3886. */
  3887. Vector4.prototype.asArray = function () {
  3888. var result = new Array();
  3889. this.toArray(result, 0);
  3890. return result;
  3891. };
  3892. /**
  3893. * Populates the given array from the given index with the Vector4 coordinates.
  3894. * Returns the Vector4.
  3895. */
  3896. Vector4.prototype.toArray = function (array, index) {
  3897. if (index === undefined) {
  3898. index = 0;
  3899. }
  3900. array[index] = this.x;
  3901. array[index + 1] = this.y;
  3902. array[index + 2] = this.z;
  3903. array[index + 3] = this.w;
  3904. return this;
  3905. };
  3906. /**
  3907. * Adds the given vector to the current Vector4.
  3908. * Returns the updated Vector4.
  3909. */
  3910. Vector4.prototype.addInPlace = function (otherVector) {
  3911. this.x += otherVector.x;
  3912. this.y += otherVector.y;
  3913. this.z += otherVector.z;
  3914. this.w += otherVector.w;
  3915. return this;
  3916. };
  3917. /**
  3918. * Returns a new Vector4 as the result of the addition of the current Vector4 and the given one.
  3919. */
  3920. Vector4.prototype.add = function (otherVector) {
  3921. return new Vector4(this.x + otherVector.x, this.y + otherVector.y, this.z + otherVector.z, this.w + otherVector.w);
  3922. };
  3923. /**
  3924. * Updates the given vector "result" with the result of the addition of the current Vector4 and the given one.
  3925. * Returns the current Vector4.
  3926. */
  3927. Vector4.prototype.addToRef = function (otherVector, result) {
  3928. result.x = this.x + otherVector.x;
  3929. result.y = this.y + otherVector.y;
  3930. result.z = this.z + otherVector.z;
  3931. result.w = this.w + otherVector.w;
  3932. return this;
  3933. };
  3934. /**
  3935. * Subtract in place the given vector from the current Vector4.
  3936. * Returns the updated Vector4.
  3937. */
  3938. Vector4.prototype.subtractInPlace = function (otherVector) {
  3939. this.x -= otherVector.x;
  3940. this.y -= otherVector.y;
  3941. this.z -= otherVector.z;
  3942. this.w -= otherVector.w;
  3943. return this;
  3944. };
  3945. /**
  3946. * Returns a new Vector4 with the result of the subtraction of the given vector from the current Vector4.
  3947. */
  3948. Vector4.prototype.subtract = function (otherVector) {
  3949. return new Vector4(this.x - otherVector.x, this.y - otherVector.y, this.z - otherVector.z, this.w - otherVector.w);
  3950. };
  3951. /**
  3952. * Sets the given vector "result" with the result of the subtraction of the given vector from the current Vector4.
  3953. * Returns the current Vector4.
  3954. */
  3955. Vector4.prototype.subtractToRef = function (otherVector, result) {
  3956. result.x = this.x - otherVector.x;
  3957. result.y = this.y - otherVector.y;
  3958. result.z = this.z - otherVector.z;
  3959. result.w = this.w - otherVector.w;
  3960. return this;
  3961. };
  3962. /**
  3963. * Returns a new Vector4 set with the result of the subtraction of the given floats from the current Vector4 coordinates.
  3964. */
  3965. Vector4.prototype.subtractFromFloats = function (x, y, z, w) {
  3966. return new Vector4(this.x - x, this.y - y, this.z - z, this.w - w);
  3967. };
  3968. /**
  3969. * Sets the given vector "result" set with the result of the subtraction of the given floats from the current Vector4 coordinates.
  3970. * Returns the current Vector4.
  3971. */
  3972. Vector4.prototype.subtractFromFloatsToRef = function (x, y, z, w, result) {
  3973. result.x = this.x - x;
  3974. result.y = this.y - y;
  3975. result.z = this.z - z;
  3976. result.w = this.w - w;
  3977. return this;
  3978. };
  3979. /**
  3980. * Returns a new Vector4 set with the current Vector4 negated coordinates.
  3981. */
  3982. Vector4.prototype.negate = function () {
  3983. return new Vector4(-this.x, -this.y, -this.z, -this.w);
  3984. };
  3985. /**
  3986. * Multiplies the current Vector4 coordinates by scale (float).
  3987. * Returns the updated Vector4.
  3988. */
  3989. Vector4.prototype.scaleInPlace = function (scale) {
  3990. this.x *= scale;
  3991. this.y *= scale;
  3992. this.z *= scale;
  3993. this.w *= scale;
  3994. return this;
  3995. };
  3996. /**
  3997. * Returns a new Vector4 set with the current Vector4 coordinates multiplied by scale (float).
  3998. */
  3999. Vector4.prototype.scale = function (scale) {
  4000. return new Vector4(this.x * scale, this.y * scale, this.z * scale, this.w * scale);
  4001. };
  4002. /**
  4003. * Sets the given vector "result" with the current Vector4 coordinates multiplied by scale (float).
  4004. * Returns the current Vector4.
  4005. */
  4006. Vector4.prototype.scaleToRef = function (scale, result) {
  4007. result.x = this.x * scale;
  4008. result.y = this.y * scale;
  4009. result.z = this.z * scale;
  4010. result.w = this.w * scale;
  4011. return this;
  4012. };
  4013. /**
  4014. * Scale the current Vector4 values by a factor and add the result to a given Vector4
  4015. * @param scale defines the scale factor
  4016. * @param result defines the Vector4 object where to store the result
  4017. * @returns the unmodified current Vector4
  4018. */
  4019. Vector4.prototype.scaleAndAddToRef = function (scale, result) {
  4020. result.x += this.x * scale;
  4021. result.y += this.y * scale;
  4022. result.z += this.z * scale;
  4023. result.w += this.w * scale;
  4024. return this;
  4025. };
  4026. /**
  4027. * Boolean : True if the current Vector4 coordinates are stricly equal to the given ones.
  4028. */
  4029. Vector4.prototype.equals = function (otherVector) {
  4030. return otherVector && this.x === otherVector.x && this.y === otherVector.y && this.z === otherVector.z && this.w === otherVector.w;
  4031. };
  4032. /**
  4033. * Boolean : True if the current Vector4 coordinates are each beneath the distance "epsilon" from the given vector ones.
  4034. */
  4035. Vector4.prototype.equalsWithEpsilon = function (otherVector, epsilon) {
  4036. if (epsilon === void 0) { epsilon = BABYLON.Epsilon; }
  4037. return otherVector
  4038. && BABYLON.Scalar.WithinEpsilon(this.x, otherVector.x, epsilon)
  4039. && BABYLON.Scalar.WithinEpsilon(this.y, otherVector.y, epsilon)
  4040. && BABYLON.Scalar.WithinEpsilon(this.z, otherVector.z, epsilon)
  4041. && BABYLON.Scalar.WithinEpsilon(this.w, otherVector.w, epsilon);
  4042. };
  4043. /**
  4044. * Boolean : True if the given floats are strictly equal to the current Vector4 coordinates.
  4045. */
  4046. Vector4.prototype.equalsToFloats = function (x, y, z, w) {
  4047. return this.x === x && this.y === y && this.z === z && this.w === w;
  4048. };
  4049. /**
  4050. * Multiplies in place the current Vector4 by the given one.
  4051. * Returns the updated Vector4.
  4052. */
  4053. Vector4.prototype.multiplyInPlace = function (otherVector) {
  4054. this.x *= otherVector.x;
  4055. this.y *= otherVector.y;
  4056. this.z *= otherVector.z;
  4057. this.w *= otherVector.w;
  4058. return this;
  4059. };
  4060. /**
  4061. * Returns a new Vector4 set with the multiplication result of the current Vector4 and the given one.
  4062. */
  4063. Vector4.prototype.multiply = function (otherVector) {
  4064. return new Vector4(this.x * otherVector.x, this.y * otherVector.y, this.z * otherVector.z, this.w * otherVector.w);
  4065. };
  4066. /**
  4067. * Updates the given vector "result" with the multiplication result of the current Vector4 and the given one.
  4068. * Returns the current Vector4.
  4069. */
  4070. Vector4.prototype.multiplyToRef = function (otherVector, result) {
  4071. result.x = this.x * otherVector.x;
  4072. result.y = this.y * otherVector.y;
  4073. result.z = this.z * otherVector.z;
  4074. result.w = this.w * otherVector.w;
  4075. return this;
  4076. };
  4077. /**
  4078. * Returns a new Vector4 set with the multiplication result of the given floats and the current Vector4 coordinates.
  4079. */
  4080. Vector4.prototype.multiplyByFloats = function (x, y, z, w) {
  4081. return new Vector4(this.x * x, this.y * y, this.z * z, this.w * w);
  4082. };
  4083. /**
  4084. * Returns a new Vector4 set with the division result of the current Vector4 by the given one.
  4085. */
  4086. Vector4.prototype.divide = function (otherVector) {
  4087. return new Vector4(this.x / otherVector.x, this.y / otherVector.y, this.z / otherVector.z, this.w / otherVector.w);
  4088. };
  4089. /**
  4090. * Updates the given vector "result" with the division result of the current Vector4 by the given one.
  4091. * Returns the current Vector4.
  4092. */
  4093. Vector4.prototype.divideToRef = function (otherVector, result) {
  4094. result.x = this.x / otherVector.x;
  4095. result.y = this.y / otherVector.y;
  4096. result.z = this.z / otherVector.z;
  4097. result.w = this.w / otherVector.w;
  4098. return this;
  4099. };
  4100. /**
  4101. * Divides the current Vector3 coordinates by the given ones.
  4102. * @returns the updated Vector3.
  4103. */
  4104. Vector4.prototype.divideInPlace = function (otherVector) {
  4105. return this.divideToRef(otherVector, this);
  4106. };
  4107. /**
  4108. * Updates the Vector4 coordinates with the minimum values between its own and the given vector ones
  4109. * @param other defines the second operand
  4110. * @returns the current updated Vector4
  4111. */
  4112. Vector4.prototype.minimizeInPlace = function (other) {
  4113. if (other.x < this.x)
  4114. this.x = other.x;
  4115. if (other.y < this.y)
  4116. this.y = other.y;
  4117. if (other.z < this.z)
  4118. this.z = other.z;
  4119. if (other.w < this.w)
  4120. this.w = other.w;
  4121. return this;
  4122. };
  4123. /**
  4124. * Updates the Vector4 coordinates with the maximum values between its own and the given vector ones
  4125. * @param other defines the second operand
  4126. * @returns the current updated Vector4
  4127. */
  4128. Vector4.prototype.maximizeInPlace = function (other) {
  4129. if (other.x > this.x)
  4130. this.x = other.x;
  4131. if (other.y > this.y)
  4132. this.y = other.y;
  4133. if (other.z > this.z)
  4134. this.z = other.z;
  4135. if (other.w > this.w)
  4136. this.w = other.w;
  4137. return this;
  4138. };
  4139. // Properties
  4140. /**
  4141. * Returns the Vector4 length (float).
  4142. */
  4143. Vector4.prototype.length = function () {
  4144. return Math.sqrt(this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w);
  4145. };
  4146. /**
  4147. * Returns the Vector4 squared length (float).
  4148. */
  4149. Vector4.prototype.lengthSquared = function () {
  4150. return (this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w);
  4151. };
  4152. // Methods
  4153. /**
  4154. * Normalizes in place the Vector4.
  4155. * Returns the updated Vector4.
  4156. */
  4157. Vector4.prototype.normalize = function () {
  4158. var len = this.length();
  4159. if (len === 0)
  4160. return this;
  4161. var num = 1.0 / len;
  4162. this.x *= num;
  4163. this.y *= num;
  4164. this.z *= num;
  4165. this.w *= num;
  4166. return this;
  4167. };
  4168. /**
  4169. * Returns a new Vector3 from the Vector4 (x, y, z) coordinates.
  4170. */
  4171. Vector4.prototype.toVector3 = function () {
  4172. return new Vector3(this.x, this.y, this.z);
  4173. };
  4174. /**
  4175. * Returns a new Vector4 copied from the current one.
  4176. */
  4177. Vector4.prototype.clone = function () {
  4178. return new Vector4(this.x, this.y, this.z, this.w);
  4179. };
  4180. /**
  4181. * Updates the current Vector4 with the given one coordinates.
  4182. * Returns the updated Vector4.
  4183. */
  4184. Vector4.prototype.copyFrom = function (source) {
  4185. this.x = source.x;
  4186. this.y = source.y;
  4187. this.z = source.z;
  4188. this.w = source.w;
  4189. return this;
  4190. };
  4191. /**
  4192. * Updates the current Vector4 coordinates with the given floats.
  4193. * Returns the updated Vector4.
  4194. */
  4195. Vector4.prototype.copyFromFloats = function (x, y, z, w) {
  4196. this.x = x;
  4197. this.y = y;
  4198. this.z = z;
  4199. this.w = w;
  4200. return this;
  4201. };
  4202. /**
  4203. * Updates the current Vector4 coordinates with the given floats.
  4204. * Returns the updated Vector4.
  4205. */
  4206. Vector4.prototype.set = function (x, y, z, w) {
  4207. return this.copyFromFloats(x, y, z, w);
  4208. };
  4209. // Statics
  4210. /**
  4211. * Returns a new Vector4 set from the starting index of the given array.
  4212. */
  4213. Vector4.FromArray = function (array, offset) {
  4214. if (!offset) {
  4215. offset = 0;
  4216. }
  4217. return new Vector4(array[offset], array[offset + 1], array[offset + 2], array[offset + 3]);
  4218. };
  4219. /**
  4220. * Updates the given vector "result" from the starting index of the given array.
  4221. */
  4222. Vector4.FromArrayToRef = function (array, offset, result) {
  4223. result.x = array[offset];
  4224. result.y = array[offset + 1];
  4225. result.z = array[offset + 2];
  4226. result.w = array[offset + 3];
  4227. };
  4228. /**
  4229. * Updates the given vector "result" from the starting index of the given Float32Array.
  4230. */
  4231. Vector4.FromFloatArrayToRef = function (array, offset, result) {
  4232. Vector4.FromArrayToRef(array, offset, result);
  4233. };
  4234. /**
  4235. * Updates the given vector "result" coordinates from the given floats.
  4236. */
  4237. Vector4.FromFloatsToRef = function (x, y, z, w, result) {
  4238. result.x = x;
  4239. result.y = y;
  4240. result.z = z;
  4241. result.w = w;
  4242. };
  4243. /**
  4244. * Returns a new Vector4 set to (0.0, 0.0, 0.0, 0.0)
  4245. */
  4246. Vector4.Zero = function () {
  4247. return new Vector4(0.0, 0.0, 0.0, 0.0);
  4248. };
  4249. /**
  4250. * Returns a new Vector4 set to (1.0, 1.0, 1.0, 1.0)
  4251. */
  4252. Vector4.One = function () {
  4253. return new Vector4(1.0, 1.0, 1.0, 1.0);
  4254. };
  4255. /**
  4256. * Returns a new normalized Vector4 from the given one.
  4257. */
  4258. Vector4.Normalize = function (vector) {
  4259. var result = Vector4.Zero();
  4260. Vector4.NormalizeToRef(vector, result);
  4261. return result;
  4262. };
  4263. /**
  4264. * Updates the given vector "result" from the normalization of the given one.
  4265. */
  4266. Vector4.NormalizeToRef = function (vector, result) {
  4267. result.copyFrom(vector);
  4268. result.normalize();
  4269. };
  4270. Vector4.Minimize = function (left, right) {
  4271. var min = left.clone();
  4272. min.minimizeInPlace(right);
  4273. return min;
  4274. };
  4275. Vector4.Maximize = function (left, right) {
  4276. var max = left.clone();
  4277. max.maximizeInPlace(right);
  4278. return max;
  4279. };
  4280. /**
  4281. * Returns the distance (float) between the vectors "value1" and "value2".
  4282. */
  4283. Vector4.Distance = function (value1, value2) {
  4284. return Math.sqrt(Vector4.DistanceSquared(value1, value2));
  4285. };
  4286. /**
  4287. * Returns the squared distance (float) between the vectors "value1" and "value2".
  4288. */
  4289. Vector4.DistanceSquared = function (value1, value2) {
  4290. var x = value1.x - value2.x;
  4291. var y = value1.y - value2.y;
  4292. var z = value1.z - value2.z;
  4293. var w = value1.w - value2.w;
  4294. return (x * x) + (y * y) + (z * z) + (w * w);
  4295. };
  4296. /**
  4297. * Returns a new Vector4 located at the center between the vectors "value1" and "value2".
  4298. */
  4299. Vector4.Center = function (value1, value2) {
  4300. var center = value1.add(value2);
  4301. center.scaleInPlace(0.5);
  4302. return center;
  4303. };
  4304. /**
  4305. * Returns a new Vector4 set with the result of the normal transformation by the given matrix of the given vector.
  4306. * This methods computes transformed normalized direction vectors only.
  4307. */
  4308. Vector4.TransformNormal = function (vector, transformation) {
  4309. var result = Vector4.Zero();
  4310. Vector4.TransformNormalToRef(vector, transformation, result);
  4311. return result;
  4312. };
  4313. /**
  4314. * Sets the given vector "result" with the result of the normal transformation by the given matrix of the given vector.
  4315. * This methods computes transformed normalized direction vectors only.
  4316. */
  4317. Vector4.TransformNormalToRef = function (vector, transformation, result) {
  4318. var x = (vector.x * transformation.m[0]) + (vector.y * transformation.m[4]) + (vector.z * transformation.m[8]);
  4319. var y = (vector.x * transformation.m[1]) + (vector.y * transformation.m[5]) + (vector.z * transformation.m[9]);
  4320. var z = (vector.x * transformation.m[2]) + (vector.y * transformation.m[6]) + (vector.z * transformation.m[10]);
  4321. result.x = x;
  4322. result.y = y;
  4323. result.z = z;
  4324. result.w = vector.w;
  4325. };
  4326. /**
  4327. * Sets the given vector "result" with the result of the normal transformation by the given matrix of the given floats (x, y, z, w).
  4328. * This methods computes transformed normalized direction vectors only.
  4329. */
  4330. Vector4.TransformNormalFromFloatsToRef = function (x, y, z, w, transformation, result) {
  4331. result.x = (x * transformation.m[0]) + (y * transformation.m[4]) + (z * transformation.m[8]);
  4332. result.y = (x * transformation.m[1]) + (y * transformation.m[5]) + (z * transformation.m[9]);
  4333. result.z = (x * transformation.m[2]) + (y * transformation.m[6]) + (z * transformation.m[10]);
  4334. result.w = w;
  4335. };
  4336. return Vector4;
  4337. }());
  4338. BABYLON.Vector4 = Vector4;
  4339. var Size = /** @class */ (function () {
  4340. /**
  4341. * Creates a Size object from the given width and height (floats).
  4342. */
  4343. function Size(width, height) {
  4344. this.width = width;
  4345. this.height = height;
  4346. }
  4347. // Returns a string with the Size width and height.
  4348. Size.prototype.toString = function () {
  4349. return "{W: " + this.width + ", H: " + this.height + "}";
  4350. };
  4351. /**
  4352. * Returns the string "Size"
  4353. */
  4354. Size.prototype.getClassName = function () {
  4355. return "Size";
  4356. };
  4357. /**
  4358. * Returns the Size hash code.
  4359. */
  4360. Size.prototype.getHashCode = function () {
  4361. var hash = this.width || 0;
  4362. hash = (hash * 397) ^ (this.height || 0);
  4363. return hash;
  4364. };
  4365. /**
  4366. * Updates the current size from the given one.
  4367. * Returns the updated Size.
  4368. */
  4369. Size.prototype.copyFrom = function (src) {
  4370. this.width = src.width;
  4371. this.height = src.height;
  4372. };
  4373. /**
  4374. * Updates in place the current Size from the given floats.
  4375. * Returns the updated Size.
  4376. */
  4377. Size.prototype.copyFromFloats = function (width, height) {
  4378. this.width = width;
  4379. this.height = height;
  4380. return this;
  4381. };
  4382. /**
  4383. * Updates in place the current Size from the given floats.
  4384. * Returns the updated Size.
  4385. */
  4386. Size.prototype.set = function (width, height) {
  4387. return this.copyFromFloats(width, height);
  4388. };
  4389. /**
  4390. * Returns a new Size set with the multiplication result of the current Size and the given floats.
  4391. */
  4392. Size.prototype.multiplyByFloats = function (w, h) {
  4393. return new Size(this.width * w, this.height * h);
  4394. };
  4395. /**
  4396. * Returns a new Size copied from the given one.
  4397. */
  4398. Size.prototype.clone = function () {
  4399. return new Size(this.width, this.height);
  4400. };
  4401. /**
  4402. * Boolean : True if the current Size and the given one width and height are strictly equal.
  4403. */
  4404. Size.prototype.equals = function (other) {
  4405. if (!other) {
  4406. return false;
  4407. }
  4408. return (this.width === other.width) && (this.height === other.height);
  4409. };
  4410. Object.defineProperty(Size.prototype, "surface", {
  4411. /**
  4412. * Returns the surface of the Size : width * height (float).
  4413. */
  4414. get: function () {
  4415. return this.width * this.height;
  4416. },
  4417. enumerable: true,
  4418. configurable: true
  4419. });
  4420. /**
  4421. * Returns a new Size set to (0.0, 0.0)
  4422. */
  4423. Size.Zero = function () {
  4424. return new Size(0.0, 0.0);
  4425. };
  4426. /**
  4427. * Returns a new Size set as the addition result of the current Size and the given one.
  4428. */
  4429. Size.prototype.add = function (otherSize) {
  4430. var r = new Size(this.width + otherSize.width, this.height + otherSize.height);
  4431. return r;
  4432. };
  4433. /**
  4434. * Returns a new Size set as the subtraction result of the given one from the current Size.
  4435. */
  4436. Size.prototype.subtract = function (otherSize) {
  4437. var r = new Size(this.width - otherSize.width, this.height - otherSize.height);
  4438. return r;
  4439. };
  4440. /**
  4441. * Returns a new Size set at the linear interpolation "amount" between "start" and "end".
  4442. */
  4443. Size.Lerp = function (start, end, amount) {
  4444. var w = start.width + ((end.width - start.width) * amount);
  4445. var h = start.height + ((end.height - start.height) * amount);
  4446. return new Size(w, h);
  4447. };
  4448. return Size;
  4449. }());
  4450. BABYLON.Size = Size;
  4451. /**
  4452. * Class used to store quaternion data
  4453. * @see https://en.wikipedia.org/wiki/Quaternion
  4454. * @see http://doc.babylonjs.com/features/position,_rotation,_scaling
  4455. */
  4456. var Quaternion = /** @class */ (function () {
  4457. /**
  4458. * Creates a new Quaternion from the given floats
  4459. * @param x defines the first component (0 by default)
  4460. * @param y defines the second component (0 by default)
  4461. * @param z defines the third component (0 by default)
  4462. * @param w defines the fourth component (1.0 by default)
  4463. */
  4464. function Quaternion(
  4465. /** defines the first component (0 by default) */
  4466. x,
  4467. /** defines the second component (0 by default) */
  4468. y,
  4469. /** defines the third component (0 by default) */
  4470. z,
  4471. /** defines the fourth component (1.0 by default) */
  4472. w) {
  4473. if (x === void 0) { x = 0.0; }
  4474. if (y === void 0) { y = 0.0; }
  4475. if (z === void 0) { z = 0.0; }
  4476. if (w === void 0) { w = 1.0; }
  4477. this.x = x;
  4478. this.y = y;
  4479. this.z = z;
  4480. this.w = w;
  4481. }
  4482. /**
  4483. * Gets a string representation for the current quaternion
  4484. * @returns a string with the Quaternion coordinates
  4485. */
  4486. Quaternion.prototype.toString = function () {
  4487. return "{X: " + this.x + " Y:" + this.y + " Z:" + this.z + " W:" + this.w + "}";
  4488. };
  4489. /**
  4490. * Gets the class name of the quaternion
  4491. * @returns the string "Quaternion"
  4492. */
  4493. Quaternion.prototype.getClassName = function () {
  4494. return "Quaternion";
  4495. };
  4496. /**
  4497. * Gets a hash code for this quaternion
  4498. * @returns the quaternion hash code
  4499. */
  4500. Quaternion.prototype.getHashCode = function () {
  4501. var hash = this.x || 0;
  4502. hash = (hash * 397) ^ (this.y || 0);
  4503. hash = (hash * 397) ^ (this.z || 0);
  4504. hash = (hash * 397) ^ (this.w || 0);
  4505. return hash;
  4506. };
  4507. /**
  4508. * Copy the quaternion to an array
  4509. * @returns a new array populated with 4 elements from the quaternion coordinates
  4510. */
  4511. Quaternion.prototype.asArray = function () {
  4512. return [this.x, this.y, this.z, this.w];
  4513. };
  4514. /**
  4515. * Check if two quaternions are equals
  4516. * @param otherQuaternion defines the second operand
  4517. * @return true if the current quaternion and the given one coordinates are strictly equals
  4518. */
  4519. Quaternion.prototype.equals = function (otherQuaternion) {
  4520. return otherQuaternion && this.x === otherQuaternion.x && this.y === otherQuaternion.y && this.z === otherQuaternion.z && this.w === otherQuaternion.w;
  4521. };
  4522. /**
  4523. * Clone the current quaternion
  4524. * @returns a new quaternion copied from the current one
  4525. */
  4526. Quaternion.prototype.clone = function () {
  4527. return new Quaternion(this.x, this.y, this.z, this.w);
  4528. };
  4529. /**
  4530. * Copy a quaternion to the current one
  4531. * @param other defines the other quaternion
  4532. * @returns the updated current quaternion
  4533. */
  4534. Quaternion.prototype.copyFrom = function (other) {
  4535. this.x = other.x;
  4536. this.y = other.y;
  4537. this.z = other.z;
  4538. this.w = other.w;
  4539. return this;
  4540. };
  4541. /**
  4542. * Updates the current quaternion with the given float coordinates
  4543. * @param x defines the x coordinate
  4544. * @param y defines the y coordinate
  4545. * @param z defines the z coordinate
  4546. * @param w defines the w coordinate
  4547. * @returns the updated current quaternion
  4548. */
  4549. Quaternion.prototype.copyFromFloats = function (x, y, z, w) {
  4550. this.x = x;
  4551. this.y = y;
  4552. this.z = z;
  4553. this.w = w;
  4554. return this;
  4555. };
  4556. /**
  4557. * Updates the current quaternion from the given float coordinates
  4558. * @param x defines the x coordinate
  4559. * @param y defines the y coordinate
  4560. * @param z defines the z coordinate
  4561. * @param w defines the w coordinate
  4562. * @returns the updated current quaternion
  4563. */
  4564. Quaternion.prototype.set = function (x, y, z, w) {
  4565. return this.copyFromFloats(x, y, z, w);
  4566. };
  4567. /**
  4568. * Adds two quaternions
  4569. * @param other defines the second operand
  4570. * @returns a new quaternion as the addition result of the given one and the current quaternion
  4571. */
  4572. Quaternion.prototype.add = function (other) {
  4573. return new Quaternion(this.x + other.x, this.y + other.y, this.z + other.z, this.w + other.w);
  4574. };
  4575. /**
  4576. * Add a quaternion to the current one
  4577. * @param other defines the quaternion to add
  4578. * @returns the current quaternion
  4579. */
  4580. Quaternion.prototype.addInPlace = function (other) {
  4581. this.x += other.x;
  4582. this.y += other.y;
  4583. this.z += other.z;
  4584. this.w += other.w;
  4585. return this;
  4586. };
  4587. /**
  4588. * Subtract two quaternions
  4589. * @param other defines the second operand
  4590. * @returns a new quaternion as the subtraction result of the given one from the current one
  4591. */
  4592. Quaternion.prototype.subtract = function (other) {
  4593. return new Quaternion(this.x - other.x, this.y - other.y, this.z - other.z, this.w - other.w);
  4594. };
  4595. /**
  4596. * Multiplies the current quaternion by a scale factor
  4597. * @param value defines the scale factor
  4598. * @returns a new quaternion set by multiplying the current quaternion coordinates by the float "scale"
  4599. */
  4600. Quaternion.prototype.scale = function (value) {
  4601. return new Quaternion(this.x * value, this.y * value, this.z * value, this.w * value);
  4602. };
  4603. /**
  4604. * Scale the current quaternion values by a factor and stores the result to a given quaternion
  4605. * @param scale defines the scale factor
  4606. * @param result defines the Quaternion object where to store the result
  4607. * @returns the unmodified current quaternion
  4608. */
  4609. Quaternion.prototype.scaleToRef = function (scale, result) {
  4610. result.x = this.x * scale;
  4611. result.y = this.y * scale;
  4612. result.z = this.z * scale;
  4613. result.w = this.w * scale;
  4614. return this;
  4615. };
  4616. /**
  4617. * Multiplies in place the current quaternion by a scale factor
  4618. * @param value defines the scale factor
  4619. * @returns the current modified quaternion
  4620. */
  4621. Quaternion.prototype.scaleInPlace = function (value) {
  4622. this.x *= value;
  4623. this.y *= value;
  4624. this.z *= value;
  4625. this.w *= value;
  4626. return this;
  4627. };
  4628. /**
  4629. * Scale the current quaternion values by a factor and add the result to a given quaternion
  4630. * @param scale defines the scale factor
  4631. * @param result defines the Quaternion object where to store the result
  4632. * @returns the unmodified current quaternion
  4633. */
  4634. Quaternion.prototype.scaleAndAddToRef = function (scale, result) {
  4635. result.x += this.x * scale;
  4636. result.y += this.y * scale;
  4637. result.z += this.z * scale;
  4638. result.w += this.w * scale;
  4639. return this;
  4640. };
  4641. /**
  4642. * Multiplies two quaternions
  4643. * @param q1 defines the second operand
  4644. * @returns a new quaternion set as the multiplication result of the current one with the given one "q1"
  4645. */
  4646. Quaternion.prototype.multiply = function (q1) {
  4647. var result = new Quaternion(0, 0, 0, 1.0);
  4648. this.multiplyToRef(q1, result);
  4649. return result;
  4650. };
  4651. /**
  4652. * Sets the given "result" as the the multiplication result of the current one with the given one "q1"
  4653. * @param q1 defines the second operand
  4654. * @param result defines the target quaternion
  4655. * @returns the current quaternion
  4656. */
  4657. Quaternion.prototype.multiplyToRef = function (q1, result) {
  4658. var x = this.x * q1.w + this.y * q1.z - this.z * q1.y + this.w * q1.x;
  4659. var y = -this.x * q1.z + this.y * q1.w + this.z * q1.x + this.w * q1.y;
  4660. var z = this.x * q1.y - this.y * q1.x + this.z * q1.w + this.w * q1.z;
  4661. var w = -this.x * q1.x - this.y * q1.y - this.z * q1.z + this.w * q1.w;
  4662. result.copyFromFloats(x, y, z, w);
  4663. return this;
  4664. };
  4665. /**
  4666. * Updates the current quaternion with the multiplication of itself with the given one "q1"
  4667. * @param q1 defines the second operand
  4668. * @returns the currentupdated quaternion
  4669. */
  4670. Quaternion.prototype.multiplyInPlace = function (q1) {
  4671. this.multiplyToRef(q1, this);
  4672. return this;
  4673. };
  4674. /**
  4675. * Conjugates (1-q) the current quaternion and stores the result in the given quaternion
  4676. * @param ref defines the target quaternion
  4677. * @returns the current quaternion
  4678. */
  4679. Quaternion.prototype.conjugateToRef = function (ref) {
  4680. ref.copyFromFloats(-this.x, -this.y, -this.z, this.w);
  4681. return this;
  4682. };
  4683. /**
  4684. * Conjugates in place (1-q) the current quaternion
  4685. * @returns the current updated quaternion
  4686. */
  4687. Quaternion.prototype.conjugateInPlace = function () {
  4688. this.x *= -1;
  4689. this.y *= -1;
  4690. this.z *= -1;
  4691. return this;
  4692. };
  4693. /**
  4694. * Conjugates in place (1-q) the current quaternion
  4695. * @returns a new quaternion
  4696. */
  4697. Quaternion.prototype.conjugate = function () {
  4698. var result = new Quaternion(-this.x, -this.y, -this.z, this.w);
  4699. return result;
  4700. };
  4701. /**
  4702. * Gets length of current quaternion
  4703. * @returns the quaternion length (float)
  4704. */
  4705. Quaternion.prototype.length = function () {
  4706. return Math.sqrt((this.x * this.x) + (this.y * this.y) + (this.z * this.z) + (this.w * this.w));
  4707. };
  4708. /**
  4709. * Normalize in place the current quaternion
  4710. * @returns the current updated quaternion
  4711. */
  4712. Quaternion.prototype.normalize = function () {
  4713. var length = 1.0 / this.length();
  4714. this.x *= length;
  4715. this.y *= length;
  4716. this.z *= length;
  4717. this.w *= length;
  4718. return this;
  4719. };
  4720. /**
  4721. * Returns a new Vector3 set with the Euler angles translated from the current quaternion
  4722. * @param order is a reserved parameter and is ignore for now
  4723. * @returns a new Vector3 containing the Euler angles
  4724. */
  4725. Quaternion.prototype.toEulerAngles = function (order) {
  4726. if (order === void 0) { order = "YZX"; }
  4727. var result = Vector3.Zero();
  4728. this.toEulerAnglesToRef(result, order);
  4729. return result;
  4730. };
  4731. /**
  4732. * Sets the given vector3 "result" with the Euler angles translated from the current quaternion
  4733. * @param result defines the vector which will be filled with the Euler angles
  4734. * @param order is a reserved parameter and is ignore for now
  4735. * @returns the current unchanged quaternion
  4736. */
  4737. Quaternion.prototype.toEulerAnglesToRef = function (result, order) {
  4738. if (order === void 0) { order = "YZX"; }
  4739. var qz = this.z;
  4740. var qx = this.x;
  4741. var qy = this.y;
  4742. var qw = this.w;
  4743. var sqw = qw * qw;
  4744. var sqz = qz * qz;
  4745. var sqx = qx * qx;
  4746. var sqy = qy * qy;
  4747. var zAxisY = qy * qz - qx * qw;
  4748. var limit = .4999999;
  4749. if (zAxisY < -limit) {
  4750. result.y = 2 * Math.atan2(qy, qw);
  4751. result.x = Math.PI / 2;
  4752. result.z = 0;
  4753. }
  4754. else if (zAxisY > limit) {
  4755. result.y = 2 * Math.atan2(qy, qw);
  4756. result.x = -Math.PI / 2;
  4757. result.z = 0;
  4758. }
  4759. else {
  4760. result.z = Math.atan2(2.0 * (qx * qy + qz * qw), (-sqz - sqx + sqy + sqw));
  4761. result.x = Math.asin(-2.0 * (qz * qy - qx * qw));
  4762. result.y = Math.atan2(2.0 * (qz * qx + qy * qw), (sqz - sqx - sqy + sqw));
  4763. }
  4764. return this;
  4765. };
  4766. /**
  4767. * Updates the given rotation matrix with the current quaternion values
  4768. * @param result defines the target matrix
  4769. * @returns the current unchanged quaternion
  4770. */
  4771. Quaternion.prototype.toRotationMatrix = function (result) {
  4772. var xx = this.x * this.x;
  4773. var yy = this.y * this.y;
  4774. var zz = this.z * this.z;
  4775. var xy = this.x * this.y;
  4776. var zw = this.z * this.w;
  4777. var zx = this.z * this.x;
  4778. var yw = this.y * this.w;
  4779. var yz = this.y * this.z;
  4780. var xw = this.x * this.w;
  4781. result.m[0] = 1.0 - (2.0 * (yy + zz));
  4782. result.m[1] = 2.0 * (xy + zw);
  4783. result.m[2] = 2.0 * (zx - yw);
  4784. result.m[3] = 0;
  4785. result.m[4] = 2.0 * (xy - zw);
  4786. result.m[5] = 1.0 - (2.0 * (zz + xx));
  4787. result.m[6] = 2.0 * (yz + xw);
  4788. result.m[7] = 0;
  4789. result.m[8] = 2.0 * (zx + yw);
  4790. result.m[9] = 2.0 * (yz - xw);
  4791. result.m[10] = 1.0 - (2.0 * (yy + xx));
  4792. result.m[11] = 0;
  4793. result.m[12] = 0;
  4794. result.m[13] = 0;
  4795. result.m[14] = 0;
  4796. result.m[15] = 1.0;
  4797. result._markAsUpdated();
  4798. return this;
  4799. };
  4800. /**
  4801. * Updates the current quaternion from the given rotation matrix values
  4802. * @param matrix defines the source matrix
  4803. * @returns the current updated quaternion
  4804. */
  4805. Quaternion.prototype.fromRotationMatrix = function (matrix) {
  4806. Quaternion.FromRotationMatrixToRef(matrix, this);
  4807. return this;
  4808. };
  4809. // Statics
  4810. /**
  4811. * Creates a new quaternion from a rotation matrix
  4812. * @param matrix defines the source matrix
  4813. * @returns a new quaternion created from the given rotation matrix values
  4814. */
  4815. Quaternion.FromRotationMatrix = function (matrix) {
  4816. var result = new Quaternion();
  4817. Quaternion.FromRotationMatrixToRef(matrix, result);
  4818. return result;
  4819. };
  4820. /**
  4821. * Updates the given quaternion with the given rotation matrix values
  4822. * @param matrix defines the source matrix
  4823. * @param result defines the target quaternion
  4824. */
  4825. Quaternion.FromRotationMatrixToRef = function (matrix, result) {
  4826. var data = matrix.m;
  4827. var m11 = data[0], m12 = data[4], m13 = data[8];
  4828. var m21 = data[1], m22 = data[5], m23 = data[9];
  4829. var m31 = data[2], m32 = data[6], m33 = data[10];
  4830. var trace = m11 + m22 + m33;
  4831. var s;
  4832. if (trace > 0) {
  4833. s = 0.5 / Math.sqrt(trace + 1.0);
  4834. result.w = 0.25 / s;
  4835. result.x = (m32 - m23) * s;
  4836. result.y = (m13 - m31) * s;
  4837. result.z = (m21 - m12) * s;
  4838. }
  4839. else if (m11 > m22 && m11 > m33) {
  4840. s = 2.0 * Math.sqrt(1.0 + m11 - m22 - m33);
  4841. result.w = (m32 - m23) / s;
  4842. result.x = 0.25 * s;
  4843. result.y = (m12 + m21) / s;
  4844. result.z = (m13 + m31) / s;
  4845. }
  4846. else if (m22 > m33) {
  4847. s = 2.0 * Math.sqrt(1.0 + m22 - m11 - m33);
  4848. result.w = (m13 - m31) / s;
  4849. result.x = (m12 + m21) / s;
  4850. result.y = 0.25 * s;
  4851. result.z = (m23 + m32) / s;
  4852. }
  4853. else {
  4854. s = 2.0 * Math.sqrt(1.0 + m33 - m11 - m22);
  4855. result.w = (m21 - m12) / s;
  4856. result.x = (m13 + m31) / s;
  4857. result.y = (m23 + m32) / s;
  4858. result.z = 0.25 * s;
  4859. }
  4860. };
  4861. /**
  4862. * Creates an empty quaternion
  4863. * @returns a new quaternion set to (0.0, 0.0, 0.0)
  4864. */
  4865. Quaternion.Zero = function () {
  4866. return new Quaternion(0.0, 0.0, 0.0, 0.0);
  4867. };
  4868. /**
  4869. * Inverse a given quaternion
  4870. * @param q defines the source quaternion
  4871. * @returns a new quaternion as the inverted current quaternion
  4872. */
  4873. Quaternion.Inverse = function (q) {
  4874. return new Quaternion(-q.x, -q.y, -q.z, q.w);
  4875. };
  4876. /**
  4877. * Creates an identity quaternion
  4878. * @returns the identity quaternion
  4879. */
  4880. Quaternion.Identity = function () {
  4881. return new Quaternion(0.0, 0.0, 0.0, 1.0);
  4882. };
  4883. /**
  4884. * Gets a boolean indicating if the given quaternion is identity
  4885. * @param quaternion defines the quaternion to check
  4886. * @returns true if the quaternion is identity
  4887. */
  4888. Quaternion.IsIdentity = function (quaternion) {
  4889. return quaternion && quaternion.x === 0 && quaternion.y === 0 && quaternion.z === 0 && quaternion.w === 1;
  4890. };
  4891. /**
  4892. * Creates a quaternion from a rotation around an axis
  4893. * @param axis defines the axis to use
  4894. * @param angle defines the angle to use
  4895. * @returns a new quaternion created from the given axis (Vector3) and angle in radians (float)
  4896. */
  4897. Quaternion.RotationAxis = function (axis, angle) {
  4898. return Quaternion.RotationAxisToRef(axis, angle, new Quaternion());
  4899. };
  4900. /**
  4901. * Creates a rotation around an axis and stores it into the given quaternion
  4902. * @param axis defines the axis to use
  4903. * @param angle defines the angle to use
  4904. * @param result defines the target quaternion
  4905. * @returns the target quaternion
  4906. */
  4907. Quaternion.RotationAxisToRef = function (axis, angle, result) {
  4908. var sin = Math.sin(angle / 2);
  4909. axis.normalize();
  4910. result.w = Math.cos(angle / 2);
  4911. result.x = axis.x * sin;
  4912. result.y = axis.y * sin;
  4913. result.z = axis.z * sin;
  4914. return result;
  4915. };
  4916. /**
  4917. * Creates a new quaternion from data stored into an array
  4918. * @param array defines the data source
  4919. * @param offset defines the offset in the source array where the data starts
  4920. * @returns a new quaternion
  4921. */
  4922. Quaternion.FromArray = function (array, offset) {
  4923. if (!offset) {
  4924. offset = 0;
  4925. }
  4926. return new Quaternion(array[offset], array[offset + 1], array[offset + 2], array[offset + 3]);
  4927. };
  4928. /**
  4929. * Creates a new quaternion from the given Euler float angles (y, x, z)
  4930. * @param yaw defines the rotation around Y axis
  4931. * @param pitch defines the rotation around X axis
  4932. * @param roll defines the rotation around Z axis
  4933. * @returns the new quaternion
  4934. */
  4935. Quaternion.RotationYawPitchRoll = function (yaw, pitch, roll) {
  4936. var q = new Quaternion();
  4937. Quaternion.RotationYawPitchRollToRef(yaw, pitch, roll, q);
  4938. return q;
  4939. };
  4940. /**
  4941. * Creates a new rotation from the given Euler float angles (y, x, z) and stores it in the target quaternion
  4942. * @param yaw defines the rotation around Y axis
  4943. * @param pitch defines the rotation around X axis
  4944. * @param roll defines the rotation around Z axis
  4945. * @param result defines the target quaternion
  4946. */
  4947. Quaternion.RotationYawPitchRollToRef = function (yaw, pitch, roll, result) {
  4948. // Produces a quaternion from Euler angles in the z-y-x orientation (Tait-Bryan angles)
  4949. var halfRoll = roll * 0.5;
  4950. var halfPitch = pitch * 0.5;
  4951. var halfYaw = yaw * 0.5;
  4952. var sinRoll = Math.sin(halfRoll);
  4953. var cosRoll = Math.cos(halfRoll);
  4954. var sinPitch = Math.sin(halfPitch);
  4955. var cosPitch = Math.cos(halfPitch);
  4956. var sinYaw = Math.sin(halfYaw);
  4957. var cosYaw = Math.cos(halfYaw);
  4958. result.x = (cosYaw * sinPitch * cosRoll) + (sinYaw * cosPitch * sinRoll);
  4959. result.y = (sinYaw * cosPitch * cosRoll) - (cosYaw * sinPitch * sinRoll);
  4960. result.z = (cosYaw * cosPitch * sinRoll) - (sinYaw * sinPitch * cosRoll);
  4961. result.w = (cosYaw * cosPitch * cosRoll) + (sinYaw * sinPitch * sinRoll);
  4962. };
  4963. /**
  4964. * Creates a new quaternion from the given Euler float angles expressed in z-x-z orientation
  4965. * @param alpha defines the rotation around first axis
  4966. * @param beta defines the rotation around second axis
  4967. * @param gamma defines the rotation around third axis
  4968. * @returns the new quaternion
  4969. */
  4970. Quaternion.RotationAlphaBetaGamma = function (alpha, beta, gamma) {
  4971. var result = new Quaternion();
  4972. Quaternion.RotationAlphaBetaGammaToRef(alpha, beta, gamma, result);
  4973. return result;
  4974. };
  4975. /**
  4976. * Creates a new quaternion from the given Euler float angles expressed in z-x-z orientation and stores it in the target quaternion
  4977. * @param alpha defines the rotation around first axis
  4978. * @param beta defines the rotation around second axis
  4979. * @param gamma defines the rotation around third axis
  4980. * @param result defines the target quaternion
  4981. */
  4982. Quaternion.RotationAlphaBetaGammaToRef = function (alpha, beta, gamma, result) {
  4983. // Produces a quaternion from Euler angles in the z-x-z orientation
  4984. var halfGammaPlusAlpha = (gamma + alpha) * 0.5;
  4985. var halfGammaMinusAlpha = (gamma - alpha) * 0.5;
  4986. var halfBeta = beta * 0.5;
  4987. result.x = Math.cos(halfGammaMinusAlpha) * Math.sin(halfBeta);
  4988. result.y = Math.sin(halfGammaMinusAlpha) * Math.sin(halfBeta);
  4989. result.z = Math.sin(halfGammaPlusAlpha) * Math.cos(halfBeta);
  4990. result.w = Math.cos(halfGammaPlusAlpha) * Math.cos(halfBeta);
  4991. };
  4992. /**
  4993. * 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)
  4994. * @param axis1 defines the first axis
  4995. * @param axis2 defines the second axis
  4996. * @param axis3 defines the third axis
  4997. * @returns the new quaternion
  4998. */
  4999. Quaternion.RotationQuaternionFromAxis = function (axis1, axis2, axis3) {
  5000. var quat = new Quaternion(0.0, 0.0, 0.0, 0.0);
  5001. Quaternion.RotationQuaternionFromAxisToRef(axis1, axis2, axis3, quat);
  5002. return quat;
  5003. };
  5004. /**
  5005. * 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
  5006. * @param axis1 defines the first axis
  5007. * @param axis2 defines the second axis
  5008. * @param axis3 defines the third axis
  5009. * @param ref defines the target quaternion
  5010. */
  5011. Quaternion.RotationQuaternionFromAxisToRef = function (axis1, axis2, axis3, ref) {
  5012. var rotMat = MathTmp.Matrix[0];
  5013. Matrix.FromXYZAxesToRef(axis1.normalize(), axis2.normalize(), axis3.normalize(), rotMat);
  5014. Quaternion.FromRotationMatrixToRef(rotMat, ref);
  5015. };
  5016. /**
  5017. * Interpolates between two quaternions
  5018. * @param left defines first quaternion
  5019. * @param right defines second quaternion
  5020. * @param amount defines the gradient to use
  5021. * @returns the new interpolated quaternion
  5022. */
  5023. Quaternion.Slerp = function (left, right, amount) {
  5024. var result = Quaternion.Identity();
  5025. Quaternion.SlerpToRef(left, right, amount, result);
  5026. return result;
  5027. };
  5028. /**
  5029. * Interpolates between two quaternions and stores it into a target quaternion
  5030. * @param left defines first quaternion
  5031. * @param right defines second quaternion
  5032. * @param amount defines the gradient to use
  5033. * @param result defines the target quaternion
  5034. */
  5035. Quaternion.SlerpToRef = function (left, right, amount, result) {
  5036. var num2;
  5037. var num3;
  5038. var num4 = (((left.x * right.x) + (left.y * right.y)) + (left.z * right.z)) + (left.w * right.w);
  5039. var flag = false;
  5040. if (num4 < 0) {
  5041. flag = true;
  5042. num4 = -num4;
  5043. }
  5044. if (num4 > 0.999999) {
  5045. num3 = 1 - amount;
  5046. num2 = flag ? -amount : amount;
  5047. }
  5048. else {
  5049. var num5 = Math.acos(num4);
  5050. var num6 = (1.0 / Math.sin(num5));
  5051. num3 = (Math.sin((1.0 - amount) * num5)) * num6;
  5052. num2 = flag ? ((-Math.sin(amount * num5)) * num6) : ((Math.sin(amount * num5)) * num6);
  5053. }
  5054. result.x = (num3 * left.x) + (num2 * right.x);
  5055. result.y = (num3 * left.y) + (num2 * right.y);
  5056. result.z = (num3 * left.z) + (num2 * right.z);
  5057. result.w = (num3 * left.w) + (num2 * right.w);
  5058. };
  5059. /**
  5060. * Interpolate between two quaternions using Hermite interpolation
  5061. * @param value1 defines first quaternion
  5062. * @param tangent1 defines the incoming tangent
  5063. * @param value2 defines second quaternion
  5064. * @param tangent2 defines the outgoing tangent
  5065. * @param amount defines the target quaternion
  5066. * @returns the new interpolated quaternion
  5067. */
  5068. Quaternion.Hermite = function (value1, tangent1, value2, tangent2, amount) {
  5069. var squared = amount * amount;
  5070. var cubed = amount * squared;
  5071. var part1 = ((2.0 * cubed) - (3.0 * squared)) + 1.0;
  5072. var part2 = (-2.0 * cubed) + (3.0 * squared);
  5073. var part3 = (cubed - (2.0 * squared)) + amount;
  5074. var part4 = cubed - squared;
  5075. var x = (((value1.x * part1) + (value2.x * part2)) + (tangent1.x * part3)) + (tangent2.x * part4);
  5076. var y = (((value1.y * part1) + (value2.y * part2)) + (tangent1.y * part3)) + (tangent2.y * part4);
  5077. var z = (((value1.z * part1) + (value2.z * part2)) + (tangent1.z * part3)) + (tangent2.z * part4);
  5078. var w = (((value1.w * part1) + (value2.w * part2)) + (tangent1.w * part3)) + (tangent2.w * part4);
  5079. return new Quaternion(x, y, z, w);
  5080. };
  5081. return Quaternion;
  5082. }());
  5083. BABYLON.Quaternion = Quaternion;
  5084. /**
  5085. * Class used to store matrix data (4x4)
  5086. */
  5087. var Matrix = /** @class */ (function () {
  5088. /**
  5089. * Creates an empty matrix (filled with zeros)
  5090. */
  5091. function Matrix() {
  5092. this._isIdentity = false;
  5093. this._isIdentityDirty = true;
  5094. /**
  5095. * Gets or sets the internal data of the matrix
  5096. */
  5097. this.m = new Float32Array(16);
  5098. this._markAsUpdated();
  5099. }
  5100. /** @hidden */
  5101. Matrix.prototype._markAsUpdated = function () {
  5102. this.updateFlag = Matrix._updateFlagSeed++;
  5103. this._isIdentityDirty = true;
  5104. };
  5105. // Properties
  5106. /**
  5107. * Check if the current matrix is indentity
  5108. * @param considerAsTextureMatrix defines if the current matrix must be considered as a texture matrix (3x2)
  5109. * @returns true is the matrix is the identity matrix
  5110. */
  5111. Matrix.prototype.isIdentity = function (considerAsTextureMatrix) {
  5112. if (considerAsTextureMatrix === void 0) { considerAsTextureMatrix = false; }
  5113. if (this._isIdentityDirty) {
  5114. this._isIdentityDirty = false;
  5115. if (this.m[0] !== 1.0 || this.m[5] !== 1.0 || this.m[15] !== 1.0) {
  5116. this._isIdentity = false;
  5117. }
  5118. else if (this.m[1] !== 0.0 || this.m[2] !== 0.0 || this.m[3] !== 0.0 ||
  5119. this.m[4] !== 0.0 || this.m[6] !== 0.0 || this.m[7] !== 0.0 ||
  5120. this.m[8] !== 0.0 || this.m[9] !== 0.0 || this.m[11] !== 0.0 ||
  5121. this.m[12] !== 0.0 || this.m[13] !== 0.0 || this.m[14] !== 0.0) {
  5122. this._isIdentity = false;
  5123. }
  5124. else {
  5125. this._isIdentity = true;
  5126. }
  5127. if (!considerAsTextureMatrix && this.m[10] !== 1.0) {
  5128. this._isIdentity = false;
  5129. }
  5130. }
  5131. return this._isIdentity;
  5132. };
  5133. /**
  5134. * Gets the determinant of the matrix
  5135. * @returns the matrix determinant
  5136. */
  5137. Matrix.prototype.determinant = function () {
  5138. var temp1 = (this.m[10] * this.m[15]) - (this.m[11] * this.m[14]);
  5139. var temp2 = (this.m[9] * this.m[15]) - (this.m[11] * this.m[13]);
  5140. var temp3 = (this.m[9] * this.m[14]) - (this.m[10] * this.m[13]);
  5141. var temp4 = (this.m[8] * this.m[15]) - (this.m[11] * this.m[12]);
  5142. var temp5 = (this.m[8] * this.m[14]) - (this.m[10] * this.m[12]);
  5143. var temp6 = (this.m[8] * this.m[13]) - (this.m[9] * this.m[12]);
  5144. return ((((this.m[0] * (((this.m[5] * temp1) - (this.m[6] * temp2)) + (this.m[7] * temp3))) - (this.m[1] * (((this.m[4] * temp1) -
  5145. (this.m[6] * temp4)) + (this.m[7] * temp5)))) + (this.m[2] * (((this.m[4] * temp2) - (this.m[5] * temp4)) + (this.m[7] * temp6)))) -
  5146. (this.m[3] * (((this.m[4] * temp3) - (this.m[5] * temp5)) + (this.m[6] * temp6))));
  5147. };
  5148. // Methods
  5149. /**
  5150. * Returns the matrix as a Float32Array
  5151. * @returns the matrix underlying array
  5152. */
  5153. Matrix.prototype.toArray = function () {
  5154. return this.m;
  5155. };
  5156. /**
  5157. * Returns the matrix as a Float32Array
  5158. * @returns the matrix underlying array.
  5159. */
  5160. Matrix.prototype.asArray = function () {
  5161. return this.toArray();
  5162. };
  5163. /**
  5164. * Inverts the current matrix in place
  5165. * @returns the current inverted matrix
  5166. */
  5167. Matrix.prototype.invert = function () {
  5168. this.invertToRef(this);
  5169. return this;
  5170. };
  5171. /**
  5172. * Sets all the matrix elements to zero
  5173. * @returns the current matrix
  5174. */
  5175. Matrix.prototype.reset = function () {
  5176. for (var index = 0; index < 16; index++) {
  5177. this.m[index] = 0.0;
  5178. }
  5179. this._markAsUpdated();
  5180. return this;
  5181. };
  5182. /**
  5183. * Adds the current matrix with a second one
  5184. * @param other defines the matrix to add
  5185. * @returns a new matrix as the addition of the current matrix and the given one
  5186. */
  5187. Matrix.prototype.add = function (other) {
  5188. var result = new Matrix();
  5189. this.addToRef(other, result);
  5190. return result;
  5191. };
  5192. /**
  5193. * Sets the given matrix "result" to the addition of the current matrix and the given one
  5194. * @param other defines the matrix to add
  5195. * @param result defines the target matrix
  5196. * @returns the current matrix
  5197. */
  5198. Matrix.prototype.addToRef = function (other, result) {
  5199. for (var index = 0; index < 16; index++) {
  5200. result.m[index] = this.m[index] + other.m[index];
  5201. }
  5202. result._markAsUpdated();
  5203. return this;
  5204. };
  5205. /**
  5206. * Adds in place the given matrix to the current matrix
  5207. * @param other defines the second operand
  5208. * @returns the current updated matrix
  5209. */
  5210. Matrix.prototype.addToSelf = function (other) {
  5211. for (var index = 0; index < 16; index++) {
  5212. this.m[index] += other.m[index];
  5213. }
  5214. this._markAsUpdated();
  5215. return this;
  5216. };
  5217. /**
  5218. * Sets the given matrix to the current inverted Matrix
  5219. * @param other defines the target matrix
  5220. * @returns the unmodified current matrix
  5221. */
  5222. Matrix.prototype.invertToRef = function (other) {
  5223. var l1 = this.m[0];
  5224. var l2 = this.m[1];
  5225. var l3 = this.m[2];
  5226. var l4 = this.m[3];
  5227. var l5 = this.m[4];
  5228. var l6 = this.m[5];
  5229. var l7 = this.m[6];
  5230. var l8 = this.m[7];
  5231. var l9 = this.m[8];
  5232. var l10 = this.m[9];
  5233. var l11 = this.m[10];
  5234. var l12 = this.m[11];
  5235. var l13 = this.m[12];
  5236. var l14 = this.m[13];
  5237. var l15 = this.m[14];
  5238. var l16 = this.m[15];
  5239. var l17 = (l11 * l16) - (l12 * l15);
  5240. var l18 = (l10 * l16) - (l12 * l14);
  5241. var l19 = (l10 * l15) - (l11 * l14);
  5242. var l20 = (l9 * l16) - (l12 * l13);
  5243. var l21 = (l9 * l15) - (l11 * l13);
  5244. var l22 = (l9 * l14) - (l10 * l13);
  5245. var l23 = ((l6 * l17) - (l7 * l18)) + (l8 * l19);
  5246. var l24 = -(((l5 * l17) - (l7 * l20)) + (l8 * l21));
  5247. var l25 = ((l5 * l18) - (l6 * l20)) + (l8 * l22);
  5248. var l26 = -(((l5 * l19) - (l6 * l21)) + (l7 * l22));
  5249. var l27 = 1.0 / ((((l1 * l23) + (l2 * l24)) + (l3 * l25)) + (l4 * l26));
  5250. var l28 = (l7 * l16) - (l8 * l15);
  5251. var l29 = (l6 * l16) - (l8 * l14);
  5252. var l30 = (l6 * l15) - (l7 * l14);
  5253. var l31 = (l5 * l16) - (l8 * l13);
  5254. var l32 = (l5 * l15) - (l7 * l13);
  5255. var l33 = (l5 * l14) - (l6 * l13);
  5256. var l34 = (l7 * l12) - (l8 * l11);
  5257. var l35 = (l6 * l12) - (l8 * l10);
  5258. var l36 = (l6 * l11) - (l7 * l10);
  5259. var l37 = (l5 * l12) - (l8 * l9);
  5260. var l38 = (l5 * l11) - (l7 * l9);
  5261. var l39 = (l5 * l10) - (l6 * l9);
  5262. other.m[0] = l23 * l27;
  5263. other.m[4] = l24 * l27;
  5264. other.m[8] = l25 * l27;
  5265. other.m[12] = l26 * l27;
  5266. other.m[1] = -(((l2 * l17) - (l3 * l18)) + (l4 * l19)) * l27;
  5267. other.m[5] = (((l1 * l17) - (l3 * l20)) + (l4 * l21)) * l27;
  5268. other.m[9] = -(((l1 * l18) - (l2 * l20)) + (l4 * l22)) * l27;
  5269. other.m[13] = (((l1 * l19) - (l2 * l21)) + (l3 * l22)) * l27;
  5270. other.m[2] = (((l2 * l28) - (l3 * l29)) + (l4 * l30)) * l27;
  5271. other.m[6] = -(((l1 * l28) - (l3 * l31)) + (l4 * l32)) * l27;
  5272. other.m[10] = (((l1 * l29) - (l2 * l31)) + (l4 * l33)) * l27;
  5273. other.m[14] = -(((l1 * l30) - (l2 * l32)) + (l3 * l33)) * l27;
  5274. other.m[3] = -(((l2 * l34) - (l3 * l35)) + (l4 * l36)) * l27;
  5275. other.m[7] = (((l1 * l34) - (l3 * l37)) + (l4 * l38)) * l27;
  5276. other.m[11] = -(((l1 * l35) - (l2 * l37)) + (l4 * l39)) * l27;
  5277. other.m[15] = (((l1 * l36) - (l2 * l38)) + (l3 * l39)) * l27;
  5278. other._markAsUpdated();
  5279. return this;
  5280. };
  5281. /**
  5282. * Inserts the translation vector (using 3 floats) in the current matrix
  5283. * @param x defines the 1st component of the translation
  5284. * @param y defines the 2nd component of the translation
  5285. * @param z defines the 3rd component of the translation
  5286. * @returns the current updated matrix
  5287. */
  5288. Matrix.prototype.setTranslationFromFloats = function (x, y, z) {
  5289. this.m[12] = x;
  5290. this.m[13] = y;
  5291. this.m[14] = z;
  5292. this._markAsUpdated();
  5293. return this;
  5294. };
  5295. /**
  5296. * Inserts the translation vector in the current matrix
  5297. * @param vector3 defines the translation to insert
  5298. * @returns the current updated matrix
  5299. */
  5300. Matrix.prototype.setTranslation = function (vector3) {
  5301. this.m[12] = vector3.x;
  5302. this.m[13] = vector3.y;
  5303. this.m[14] = vector3.z;
  5304. this._markAsUpdated();
  5305. return this;
  5306. };
  5307. /**
  5308. * Gets the translation value of the current matrix
  5309. * @returns a new Vector3 as the extracted translation from the matrix
  5310. */
  5311. Matrix.prototype.getTranslation = function () {
  5312. return new Vector3(this.m[12], this.m[13], this.m[14]);
  5313. };
  5314. /**
  5315. * Fill a Vector3 with the extracted translation from the matrix
  5316. * @param result defines the Vector3 where to store the translation
  5317. * @returns the current matrix
  5318. */
  5319. Matrix.prototype.getTranslationToRef = function (result) {
  5320. result.x = this.m[12];
  5321. result.y = this.m[13];
  5322. result.z = this.m[14];
  5323. return this;
  5324. };
  5325. /**
  5326. * Remove rotation and scaling part from the matrix
  5327. * @returns the updated matrix
  5328. */
  5329. Matrix.prototype.removeRotationAndScaling = function () {
  5330. this.setRowFromFloats(0, 1, 0, 0, 0);
  5331. this.setRowFromFloats(1, 0, 1, 0, 0);
  5332. this.setRowFromFloats(2, 0, 0, 1, 0);
  5333. return this;
  5334. };
  5335. /**
  5336. * Multiply two matrices
  5337. * @param other defines the second operand
  5338. * @returns a new matrix set with the multiplication result of the current Matrix and the given one
  5339. */
  5340. Matrix.prototype.multiply = function (other) {
  5341. var result = new Matrix();
  5342. this.multiplyToRef(other, result);
  5343. return result;
  5344. };
  5345. /**
  5346. * Copy the current matrix from the given one
  5347. * @param other defines the source matrix
  5348. * @returns the current updated matrix
  5349. */
  5350. Matrix.prototype.copyFrom = function (other) {
  5351. for (var index = 0; index < 16; index++) {
  5352. this.m[index] = other.m[index];
  5353. }
  5354. this._markAsUpdated();
  5355. return this;
  5356. };
  5357. /**
  5358. * Populates the given array from the starting index with the current matrix values
  5359. * @param array defines the target array
  5360. * @param offset defines the offset in the target array where to start storing values
  5361. * @returns the current matrix
  5362. */
  5363. Matrix.prototype.copyToArray = function (array, offset) {
  5364. if (offset === void 0) { offset = 0; }
  5365. for (var index = 0; index < 16; index++) {
  5366. array[offset + index] = this.m[index];
  5367. }
  5368. return this;
  5369. };
  5370. /**
  5371. * Sets the given matrix "result" with the multiplication result of the current Matrix and the given one
  5372. * @param other defines the second operand
  5373. * @param result defines the matrix where to store the multiplication
  5374. * @returns the current matrix
  5375. */
  5376. Matrix.prototype.multiplyToRef = function (other, result) {
  5377. this.multiplyToArray(other, result.m, 0);
  5378. result._markAsUpdated();
  5379. return this;
  5380. };
  5381. /**
  5382. * Sets the Float32Array "result" from the given index "offset" with the multiplication of the current matrix and the given one
  5383. * @param other defines the second operand
  5384. * @param result defines the array where to store the multiplication
  5385. * @param offset defines the offset in the target array where to start storing values
  5386. * @returns the current matrix
  5387. */
  5388. Matrix.prototype.multiplyToArray = function (other, result, offset) {
  5389. var tm0 = this.m[0];
  5390. var tm1 = this.m[1];
  5391. var tm2 = this.m[2];
  5392. var tm3 = this.m[3];
  5393. var tm4 = this.m[4];
  5394. var tm5 = this.m[5];
  5395. var tm6 = this.m[6];
  5396. var tm7 = this.m[7];
  5397. var tm8 = this.m[8];
  5398. var tm9 = this.m[9];
  5399. var tm10 = this.m[10];
  5400. var tm11 = this.m[11];
  5401. var tm12 = this.m[12];
  5402. var tm13 = this.m[13];
  5403. var tm14 = this.m[14];
  5404. var tm15 = this.m[15];
  5405. var om0 = other.m[0];
  5406. var om1 = other.m[1];
  5407. var om2 = other.m[2];
  5408. var om3 = other.m[3];
  5409. var om4 = other.m[4];
  5410. var om5 = other.m[5];
  5411. var om6 = other.m[6];
  5412. var om7 = other.m[7];
  5413. var om8 = other.m[8];
  5414. var om9 = other.m[9];
  5415. var om10 = other.m[10];
  5416. var om11 = other.m[11];
  5417. var om12 = other.m[12];
  5418. var om13 = other.m[13];
  5419. var om14 = other.m[14];
  5420. var om15 = other.m[15];
  5421. result[offset] = tm0 * om0 + tm1 * om4 + tm2 * om8 + tm3 * om12;
  5422. result[offset + 1] = tm0 * om1 + tm1 * om5 + tm2 * om9 + tm3 * om13;
  5423. result[offset + 2] = tm0 * om2 + tm1 * om6 + tm2 * om10 + tm3 * om14;
  5424. result[offset + 3] = tm0 * om3 + tm1 * om7 + tm2 * om11 + tm3 * om15;
  5425. result[offset + 4] = tm4 * om0 + tm5 * om4 + tm6 * om8 + tm7 * om12;
  5426. result[offset + 5] = tm4 * om1 + tm5 * om5 + tm6 * om9 + tm7 * om13;
  5427. result[offset + 6] = tm4 * om2 + tm5 * om6 + tm6 * om10 + tm7 * om14;
  5428. result[offset + 7] = tm4 * om3 + tm5 * om7 + tm6 * om11 + tm7 * om15;
  5429. result[offset + 8] = tm8 * om0 + tm9 * om4 + tm10 * om8 + tm11 * om12;
  5430. result[offset + 9] = tm8 * om1 + tm9 * om5 + tm10 * om9 + tm11 * om13;
  5431. result[offset + 10] = tm8 * om2 + tm9 * om6 + tm10 * om10 + tm11 * om14;
  5432. result[offset + 11] = tm8 * om3 + tm9 * om7 + tm10 * om11 + tm11 * om15;
  5433. result[offset + 12] = tm12 * om0 + tm13 * om4 + tm14 * om8 + tm15 * om12;
  5434. result[offset + 13] = tm12 * om1 + tm13 * om5 + tm14 * om9 + tm15 * om13;
  5435. result[offset + 14] = tm12 * om2 + tm13 * om6 + tm14 * om10 + tm15 * om14;
  5436. result[offset + 15] = tm12 * om3 + tm13 * om7 + tm14 * om11 + tm15 * om15;
  5437. return this;
  5438. };
  5439. /**
  5440. * Check equality between this matrix and a second one
  5441. * @param value defines the second matrix to compare
  5442. * @returns true is the current matrix and the given one values are strictly equal
  5443. */
  5444. Matrix.prototype.equals = function (value) {
  5445. return value &&
  5446. (this.m[0] === value.m[0] && this.m[1] === value.m[1] && this.m[2] === value.m[2] && this.m[3] === value.m[3] &&
  5447. this.m[4] === value.m[4] && this.m[5] === value.m[5] && this.m[6] === value.m[6] && this.m[7] === value.m[7] &&
  5448. this.m[8] === value.m[8] && this.m[9] === value.m[9] && this.m[10] === value.m[10] && this.m[11] === value.m[11] &&
  5449. this.m[12] === value.m[12] && this.m[13] === value.m[13] && this.m[14] === value.m[14] && this.m[15] === value.m[15]);
  5450. };
  5451. /**
  5452. * Clone the current matrix
  5453. * @returns a new matrix from the current matrix
  5454. */
  5455. Matrix.prototype.clone = function () {
  5456. 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]);
  5457. };
  5458. /**
  5459. * Returns the name of the current matrix class
  5460. * @returns the string "Matrix"
  5461. */
  5462. Matrix.prototype.getClassName = function () {
  5463. return "Matrix";
  5464. };
  5465. /**
  5466. * Gets the hash code of the current matrix
  5467. * @returns the hash code
  5468. */
  5469. Matrix.prototype.getHashCode = function () {
  5470. var hash = this.m[0] || 0;
  5471. for (var i = 1; i < 16; i++) {
  5472. hash = (hash * 397) ^ (this.m[i] || 0);
  5473. }
  5474. return hash;
  5475. };
  5476. /**
  5477. * Decomposes the current Matrix into a translation, rotation and scaling components
  5478. * @param scale defines the scale vector3 given as a reference to update
  5479. * @param rotation defines the rotation quaternion given as a reference to update
  5480. * @param translation defines the translation vector3 given as a reference to update
  5481. * @returns true if operation was successful
  5482. */
  5483. Matrix.prototype.decompose = function (scale, rotation, translation) {
  5484. if (translation) {
  5485. translation.x = this.m[12];
  5486. translation.y = this.m[13];
  5487. translation.z = this.m[14];
  5488. }
  5489. scale = scale || MathTmp.Vector3[0];
  5490. scale.x = Math.sqrt(this.m[0] * this.m[0] + this.m[1] * this.m[1] + this.m[2] * this.m[2]);
  5491. scale.y = Math.sqrt(this.m[4] * this.m[4] + this.m[5] * this.m[5] + this.m[6] * this.m[6]);
  5492. scale.z = Math.sqrt(this.m[8] * this.m[8] + this.m[9] * this.m[9] + this.m[10] * this.m[10]);
  5493. if (this.determinant() <= 0) {
  5494. scale.y *= -1;
  5495. }
  5496. if (scale.x === 0 || scale.y === 0 || scale.z === 0) {
  5497. if (rotation) {
  5498. rotation.x = 0;
  5499. rotation.y = 0;
  5500. rotation.z = 0;
  5501. rotation.w = 1;
  5502. }
  5503. return false;
  5504. }
  5505. if (rotation) {
  5506. 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]);
  5507. Quaternion.FromRotationMatrixToRef(MathTmp.Matrix[0], rotation);
  5508. }
  5509. return true;
  5510. };
  5511. /**
  5512. * Gets specific row of the matrix
  5513. * @param index defines the number of the row to get
  5514. * @returns the index-th row of the current matrix as a new Vector4
  5515. */
  5516. Matrix.prototype.getRow = function (index) {
  5517. if (index < 0 || index > 3) {
  5518. return null;
  5519. }
  5520. var i = index * 4;
  5521. return new Vector4(this.m[i + 0], this.m[i + 1], this.m[i + 2], this.m[i + 3]);
  5522. };
  5523. /**
  5524. * Sets the index-th row of the current matrix to the vector4 values
  5525. * @param index defines the number of the row to set
  5526. * @param row defines the target vector4
  5527. * @returns the updated current matrix
  5528. */
  5529. Matrix.prototype.setRow = function (index, row) {
  5530. if (index < 0 || index > 3) {
  5531. return this;
  5532. }
  5533. var i = index * 4;
  5534. this.m[i + 0] = row.x;
  5535. this.m[i + 1] = row.y;
  5536. this.m[i + 2] = row.z;
  5537. this.m[i + 3] = row.w;
  5538. this._markAsUpdated();
  5539. return this;
  5540. };
  5541. /**
  5542. * Compute the transpose of the matrix
  5543. * @returns the new transposed matrix
  5544. */
  5545. Matrix.prototype.transpose = function () {
  5546. return Matrix.Transpose(this);
  5547. };
  5548. /**
  5549. * Compute the transpose of the matrix and store it in a given matrix
  5550. * @param result defines the target matrix
  5551. * @returns the current matrix
  5552. */
  5553. Matrix.prototype.transposeToRef = function (result) {
  5554. Matrix.TransposeToRef(this, result);
  5555. return this;
  5556. };
  5557. /**
  5558. * Sets the index-th row of the current matrix with the given 4 x float values
  5559. * @param index defines the row index
  5560. * @param x defines the x component to set
  5561. * @param y defines the y component to set
  5562. * @param z defines the z component to set
  5563. * @param w defines the w component to set
  5564. * @returns the updated current matrix
  5565. */
  5566. Matrix.prototype.setRowFromFloats = function (index, x, y, z, w) {
  5567. if (index < 0 || index > 3) {
  5568. return this;
  5569. }
  5570. var i = index * 4;
  5571. this.m[i + 0] = x;
  5572. this.m[i + 1] = y;
  5573. this.m[i + 2] = z;
  5574. this.m[i + 3] = w;
  5575. this._markAsUpdated();
  5576. return this;
  5577. };
  5578. /**
  5579. * Compute a new matrix set with the current matrix values multiplied by scale (float)
  5580. * @param scale defines the scale factor
  5581. * @returns a new matrix
  5582. */
  5583. Matrix.prototype.scale = function (scale) {
  5584. var result = new Matrix();
  5585. this.scaleToRef(scale, result);
  5586. return result;
  5587. };
  5588. /**
  5589. * Scale the current matrix values by a factor to a given result matrix
  5590. * @param scale defines the scale factor
  5591. * @param result defines the matrix to store the result
  5592. * @returns the current matrix
  5593. */
  5594. Matrix.prototype.scaleToRef = function (scale, result) {
  5595. for (var index = 0; index < 16; index++) {
  5596. result.m[index] = this.m[index] * scale;
  5597. }
  5598. result._markAsUpdated();
  5599. return this;
  5600. };
  5601. /**
  5602. * Scale the current matrix values by a factor and add the result to a given matrix
  5603. * @param scale defines the scale factor
  5604. * @param result defines the Matrix to store the result
  5605. * @returns the current matrix
  5606. */
  5607. Matrix.prototype.scaleAndAddToRef = function (scale, result) {
  5608. for (var index = 0; index < 16; index++) {
  5609. result.m[index] += this.m[index] * scale;
  5610. }
  5611. result._markAsUpdated();
  5612. return this;
  5613. };
  5614. /**
  5615. * Writes to the given matrix a normal matrix, computed from this one (using values from identity matrix for fourth row and column).
  5616. * @param ref matrix to store the result
  5617. */
  5618. Matrix.prototype.toNormalMatrix = function (ref) {
  5619. this.invertToRef(ref);
  5620. ref.transpose();
  5621. var m = ref.m;
  5622. 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);
  5623. };
  5624. /**
  5625. * Gets only rotation part of the current matrix
  5626. * @returns a new matrix sets to the extracted rotation matrix from the current one
  5627. */
  5628. Matrix.prototype.getRotationMatrix = function () {
  5629. var result = Matrix.Identity();
  5630. this.getRotationMatrixToRef(result);
  5631. return result;
  5632. };
  5633. /**
  5634. * Extracts the rotation matrix from the current one and sets it as the given "result"
  5635. * @param result defines the target matrix to store data to
  5636. * @returns the current matrix
  5637. */
  5638. Matrix.prototype.getRotationMatrixToRef = function (result) {
  5639. var m = this.m;
  5640. var sx = Math.sqrt(m[0] * m[0] + m[1] * m[1] + m[2] * m[2]);
  5641. var sy = Math.sqrt(m[4] * m[4] + m[5] * m[5] + m[6] * m[6]);
  5642. var sz = Math.sqrt(m[8] * m[8] + m[9] * m[9] + m[10] * m[10]);
  5643. if (this.determinant() <= 0) {
  5644. sy *= -1;
  5645. }
  5646. if (sx === 0 || sy === 0 || sz === 0) {
  5647. Matrix.IdentityToRef(result);
  5648. }
  5649. else {
  5650. 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);
  5651. }
  5652. return this;
  5653. };
  5654. // Statics
  5655. /**
  5656. * Creates a matrix from an array
  5657. * @param array defines the source array
  5658. * @param offset defines an offset in the source array
  5659. * @returns a new Matrix set from the starting index of the given array
  5660. */
  5661. Matrix.FromArray = function (array, offset) {
  5662. var result = new Matrix();
  5663. if (!offset) {
  5664. offset = 0;
  5665. }
  5666. Matrix.FromArrayToRef(array, offset, result);
  5667. return result;
  5668. };
  5669. /**
  5670. * Copy the content of an array into a given matrix
  5671. * @param array defines the source array
  5672. * @param offset defines an offset in the source array
  5673. * @param result defines the target matrix
  5674. */
  5675. Matrix.FromArrayToRef = function (array, offset, result) {
  5676. for (var index = 0; index < 16; index++) {
  5677. result.m[index] = array[index + offset];
  5678. }
  5679. result._markAsUpdated();
  5680. };
  5681. /**
  5682. * Stores an array into a matrix after having multiplied each component by a given factor
  5683. * @param array defines the source array
  5684. * @param offset defines the offset in the source array
  5685. * @param scale defines the scaling factor
  5686. * @param result defines the target matrix
  5687. */
  5688. Matrix.FromFloat32ArrayToRefScaled = function (array, offset, scale, result) {
  5689. for (var index = 0; index < 16; index++) {
  5690. result.m[index] = array[index + offset] * scale;
  5691. }
  5692. result._markAsUpdated();
  5693. };
  5694. /**
  5695. * Stores a list of values (16) inside a given matrix
  5696. * @param initialM11 defines 1st value of 1st row
  5697. * @param initialM12 defines 2nd value of 1st row
  5698. * @param initialM13 defines 3rd value of 1st row
  5699. * @param initialM14 defines 4th value of 1st row
  5700. * @param initialM21 defines 1st value of 2nd row
  5701. * @param initialM22 defines 2nd value of 2nd row
  5702. * @param initialM23 defines 3rd value of 2nd row
  5703. * @param initialM24 defines 4th value of 2nd row
  5704. * @param initialM31 defines 1st value of 3rd row
  5705. * @param initialM32 defines 2nd value of 3rd row
  5706. * @param initialM33 defines 3rd value of 3rd row
  5707. * @param initialM34 defines 4th value of 3rd row
  5708. * @param initialM41 defines 1st value of 4th row
  5709. * @param initialM42 defines 2nd value of 4th row
  5710. * @param initialM43 defines 3rd value of 4th row
  5711. * @param initialM44 defines 4th value of 4th row
  5712. * @param result defines the target matrix
  5713. */
  5714. Matrix.FromValuesToRef = function (initialM11, initialM12, initialM13, initialM14, initialM21, initialM22, initialM23, initialM24, initialM31, initialM32, initialM33, initialM34, initialM41, initialM42, initialM43, initialM44, result) {
  5715. result.m[0] = initialM11;
  5716. result.m[1] = initialM12;
  5717. result.m[2] = initialM13;
  5718. result.m[3] = initialM14;
  5719. result.m[4] = initialM21;
  5720. result.m[5] = initialM22;
  5721. result.m[6] = initialM23;
  5722. result.m[7] = initialM24;
  5723. result.m[8] = initialM31;
  5724. result.m[9] = initialM32;
  5725. result.m[10] = initialM33;
  5726. result.m[11] = initialM34;
  5727. result.m[12] = initialM41;
  5728. result.m[13] = initialM42;
  5729. result.m[14] = initialM43;
  5730. result.m[15] = initialM44;
  5731. result._markAsUpdated();
  5732. };
  5733. Object.defineProperty(Matrix, "IdentityReadOnly", {
  5734. /**
  5735. * Gets an identity matrix that must not be updated
  5736. */
  5737. get: function () {
  5738. return Matrix._identityReadOnly;
  5739. },
  5740. enumerable: true,
  5741. configurable: true
  5742. });
  5743. /**
  5744. * Creates new matrix from a list of values (16)
  5745. * @param initialM11 defines 1st value of 1st row
  5746. * @param initialM12 defines 2nd value of 1st row
  5747. * @param initialM13 defines 3rd value of 1st row
  5748. * @param initialM14 defines 4th value of 1st row
  5749. * @param initialM21 defines 1st value of 2nd row
  5750. * @param initialM22 defines 2nd value of 2nd row
  5751. * @param initialM23 defines 3rd value of 2nd row
  5752. * @param initialM24 defines 4th value of 2nd row
  5753. * @param initialM31 defines 1st value of 3rd row
  5754. * @param initialM32 defines 2nd value of 3rd row
  5755. * @param initialM33 defines 3rd value of 3rd row
  5756. * @param initialM34 defines 4th value of 3rd row
  5757. * @param initialM41 defines 1st value of 4th row
  5758. * @param initialM42 defines 2nd value of 4th row
  5759. * @param initialM43 defines 3rd value of 4th row
  5760. * @param initialM44 defines 4th value of 4th row
  5761. * @returns the new matrix
  5762. */
  5763. Matrix.FromValues = function (initialM11, initialM12, initialM13, initialM14, initialM21, initialM22, initialM23, initialM24, initialM31, initialM32, initialM33, initialM34, initialM41, initialM42, initialM43, initialM44) {
  5764. var result = new Matrix();
  5765. result.m[0] = initialM11;
  5766. result.m[1] = initialM12;
  5767. result.m[2] = initialM13;
  5768. result.m[3] = initialM14;
  5769. result.m[4] = initialM21;
  5770. result.m[5] = initialM22;
  5771. result.m[6] = initialM23;
  5772. result.m[7] = initialM24;
  5773. result.m[8] = initialM31;
  5774. result.m[9] = initialM32;
  5775. result.m[10] = initialM33;
  5776. result.m[11] = initialM34;
  5777. result.m[12] = initialM41;
  5778. result.m[13] = initialM42;
  5779. result.m[14] = initialM43;
  5780. result.m[15] = initialM44;
  5781. return result;
  5782. };
  5783. /**
  5784. * Creates a new matrix composed by merging scale (vector3), rotation (quaternion) and translation (vector3)
  5785. * @param scale defines the scale vector3
  5786. * @param rotation defines the rotation quaternion
  5787. * @param translation defines the translation vector3
  5788. * @returns a new matrix
  5789. */
  5790. Matrix.Compose = function (scale, rotation, translation) {
  5791. var result = Matrix.Identity();
  5792. Matrix.ComposeToRef(scale, rotation, translation, result);
  5793. return result;
  5794. };
  5795. /**
  5796. * Sets a matrix to a value composed by merging scale (vector3), rotation (quaternion) and translation (vector3)
  5797. * @param scale defines the scale vector3
  5798. * @param rotation defines the rotation quaternion
  5799. * @param translation defines the translation vector3
  5800. * @param result defines the target matrix
  5801. */
  5802. Matrix.ComposeToRef = function (scale, rotation, translation, result) {
  5803. Matrix.FromValuesToRef(scale.x, 0, 0, 0, 0, scale.y, 0, 0, 0, 0, scale.z, 0, 0, 0, 0, 1, MathTmp.Matrix[1]);
  5804. rotation.toRotationMatrix(MathTmp.Matrix[0]);
  5805. MathTmp.Matrix[1].multiplyToRef(MathTmp.Matrix[0], result);
  5806. result.setTranslation(translation);
  5807. };
  5808. /**
  5809. * Creates a new identity matrix
  5810. * @returns a new identity matrix
  5811. */
  5812. Matrix.Identity = function () {
  5813. 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);
  5814. };
  5815. /**
  5816. * Creates a new identity matrix and stores the result in a given matrix
  5817. * @param result defines the target matrix
  5818. */
  5819. Matrix.IdentityToRef = function (result) {
  5820. 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);
  5821. };
  5822. /**
  5823. * Creates a new zero matrix
  5824. * @returns a new zero matrix
  5825. */
  5826. Matrix.Zero = function () {
  5827. 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);
  5828. };
  5829. /**
  5830. * Creates a new rotation matrix for "angle" radians around the X axis
  5831. * @param angle defines the angle (in radians) to use
  5832. * @return the new matrix
  5833. */
  5834. Matrix.RotationX = function (angle) {
  5835. var result = new Matrix();
  5836. Matrix.RotationXToRef(angle, result);
  5837. return result;
  5838. };
  5839. /**
  5840. * Creates a new matrix as the invert of a given matrix
  5841. * @param source defines the source matrix
  5842. * @returns the new matrix
  5843. */
  5844. Matrix.Invert = function (source) {
  5845. var result = new Matrix();
  5846. source.invertToRef(result);
  5847. return result;
  5848. };
  5849. /**
  5850. * Creates a new rotation matrix for "angle" radians around the X axis and stores it in a given matrix
  5851. * @param angle defines the angle (in radians) to use
  5852. * @param result defines the target matrix
  5853. */
  5854. Matrix.RotationXToRef = function (angle, result) {
  5855. var s = Math.sin(angle);
  5856. var c = Math.cos(angle);
  5857. result.m[0] = 1.0;
  5858. result.m[15] = 1.0;
  5859. result.m[5] = c;
  5860. result.m[10] = c;
  5861. result.m[9] = -s;
  5862. result.m[6] = s;
  5863. result.m[1] = 0.0;
  5864. result.m[2] = 0.0;
  5865. result.m[3] = 0.0;
  5866. result.m[4] = 0.0;
  5867. result.m[7] = 0.0;
  5868. result.m[8] = 0.0;
  5869. result.m[11] = 0.0;
  5870. result.m[12] = 0.0;
  5871. result.m[13] = 0.0;
  5872. result.m[14] = 0.0;
  5873. result._markAsUpdated();
  5874. };
  5875. /**
  5876. * Creates a new rotation matrix for "angle" radians around the Y axis
  5877. * @param angle defines the angle (in radians) to use
  5878. * @return the new matrix
  5879. */
  5880. Matrix.RotationY = function (angle) {
  5881. var result = new Matrix();
  5882. Matrix.RotationYToRef(angle, result);
  5883. return result;
  5884. };
  5885. /**
  5886. * Creates a new rotation matrix for "angle" radians around the Y axis and stores it in a given matrix
  5887. * @param angle defines the angle (in radians) to use
  5888. * @param result defines the target matrix
  5889. */
  5890. Matrix.RotationYToRef = function (angle, result) {
  5891. var s = Math.sin(angle);
  5892. var c = Math.cos(angle);
  5893. result.m[5] = 1.0;
  5894. result.m[15] = 1.0;
  5895. result.m[0] = c;
  5896. result.m[2] = -s;
  5897. result.m[8] = s;
  5898. result.m[10] = c;
  5899. result.m[1] = 0.0;
  5900. result.m[3] = 0.0;
  5901. result.m[4] = 0.0;
  5902. result.m[6] = 0.0;
  5903. result.m[7] = 0.0;
  5904. result.m[9] = 0.0;
  5905. result.m[11] = 0.0;
  5906. result.m[12] = 0.0;
  5907. result.m[13] = 0.0;
  5908. result.m[14] = 0.0;
  5909. result._markAsUpdated();
  5910. };
  5911. /**
  5912. * Creates a new rotation matrix for "angle" radians around the Z axis
  5913. * @param angle defines the angle (in radians) to use
  5914. * @return the new matrix
  5915. */
  5916. Matrix.RotationZ = function (angle) {
  5917. var result = new Matrix();
  5918. Matrix.RotationZToRef(angle, result);
  5919. return result;
  5920. };
  5921. /**
  5922. * Creates a new rotation matrix for "angle" radians around the Z axis and stores it in a given matrix
  5923. * @param angle defines the angle (in radians) to use
  5924. * @param result defines the target matrix
  5925. */
  5926. Matrix.RotationZToRef = function (angle, result) {
  5927. var s = Math.sin(angle);
  5928. var c = Math.cos(angle);
  5929. result.m[10] = 1.0;
  5930. result.m[15] = 1.0;
  5931. result.m[0] = c;
  5932. result.m[1] = s;
  5933. result.m[4] = -s;
  5934. result.m[5] = c;
  5935. result.m[2] = 0.0;
  5936. result.m[3] = 0.0;
  5937. result.m[6] = 0.0;
  5938. result.m[7] = 0.0;
  5939. result.m[8] = 0.0;
  5940. result.m[9] = 0.0;
  5941. result.m[11] = 0.0;
  5942. result.m[12] = 0.0;
  5943. result.m[13] = 0.0;
  5944. result.m[14] = 0.0;
  5945. result._markAsUpdated();
  5946. };
  5947. /**
  5948. * Creates a new rotation matrix for "angle" radians around the given axis
  5949. * @param axis defines the axis to use
  5950. * @param angle defines the angle (in radians) to use
  5951. * @return the new matrix
  5952. */
  5953. Matrix.RotationAxis = function (axis, angle) {
  5954. var result = Matrix.Zero();
  5955. Matrix.RotationAxisToRef(axis, angle, result);
  5956. return result;
  5957. };
  5958. /**
  5959. * Creates a new rotation matrix for "angle" radians around the given axis and stores it in a given matrix
  5960. * @param axis defines the axis to use
  5961. * @param angle defines the angle (in radians) to use
  5962. * @param result defines the target matrix
  5963. */
  5964. Matrix.RotationAxisToRef = function (axis, angle, result) {
  5965. var s = Math.sin(-angle);
  5966. var c = Math.cos(-angle);
  5967. var c1 = 1 - c;
  5968. axis.normalize();
  5969. result.m[0] = (axis.x * axis.x) * c1 + c;
  5970. result.m[1] = (axis.x * axis.y) * c1 - (axis.z * s);
  5971. result.m[2] = (axis.x * axis.z) * c1 + (axis.y * s);
  5972. result.m[3] = 0.0;
  5973. result.m[4] = (axis.y * axis.x) * c1 + (axis.z * s);
  5974. result.m[5] = (axis.y * axis.y) * c1 + c;
  5975. result.m[6] = (axis.y * axis.z) * c1 - (axis.x * s);
  5976. result.m[7] = 0.0;
  5977. result.m[8] = (axis.z * axis.x) * c1 - (axis.y * s);
  5978. result.m[9] = (axis.z * axis.y) * c1 + (axis.x * s);
  5979. result.m[10] = (axis.z * axis.z) * c1 + c;
  5980. result.m[11] = 0.0;
  5981. result.m[15] = 1.0;
  5982. result._markAsUpdated();
  5983. };
  5984. /**
  5985. * Creates a rotation matrix
  5986. * @param yaw defines the yaw angle in radians (Y axis)
  5987. * @param pitch defines the pitch angle in radians (X axis)
  5988. * @param roll defines the roll angle in radians (X axis)
  5989. * @returns the new rotation matrix
  5990. */
  5991. Matrix.RotationYawPitchRoll = function (yaw, pitch, roll) {
  5992. var result = new Matrix();
  5993. Matrix.RotationYawPitchRollToRef(yaw, pitch, roll, result);
  5994. return result;
  5995. };
  5996. /**
  5997. * Creates a rotation matrix and stores it in a given matrix
  5998. * @param yaw defines the yaw angle in radians (Y axis)
  5999. * @param pitch defines the pitch angle in radians (X axis)
  6000. * @param roll defines the roll angle in radians (X axis)
  6001. * @param result defines the target matrix
  6002. */
  6003. Matrix.RotationYawPitchRollToRef = function (yaw, pitch, roll, result) {
  6004. Quaternion.RotationYawPitchRollToRef(yaw, pitch, roll, this._tempQuaternion);
  6005. this._tempQuaternion.toRotationMatrix(result);
  6006. };
  6007. /**
  6008. * Creates a scaling matrix
  6009. * @param x defines the scale factor on X axis
  6010. * @param y defines the scale factor on Y axis
  6011. * @param z defines the scale factor on Z axis
  6012. * @returns the new matrix
  6013. */
  6014. Matrix.Scaling = function (x, y, z) {
  6015. var result = Matrix.Zero();
  6016. Matrix.ScalingToRef(x, y, z, result);
  6017. return result;
  6018. };
  6019. /**
  6020. * Creates a scaling matrix and stores it in a given matrix
  6021. * @param x defines the scale factor on X axis
  6022. * @param y defines the scale factor on Y axis
  6023. * @param z defines the scale factor on Z axis
  6024. * @param result defines the target matrix
  6025. */
  6026. Matrix.ScalingToRef = function (x, y, z, result) {
  6027. result.m[0] = x;
  6028. result.m[1] = 0.0;
  6029. result.m[2] = 0.0;
  6030. result.m[3] = 0.0;
  6031. result.m[4] = 0.0;
  6032. result.m[5] = y;
  6033. result.m[6] = 0.0;
  6034. result.m[7] = 0.0;
  6035. result.m[8] = 0.0;
  6036. result.m[9] = 0.0;
  6037. result.m[10] = z;
  6038. result.m[11] = 0.0;
  6039. result.m[12] = 0.0;
  6040. result.m[13] = 0.0;
  6041. result.m[14] = 0.0;
  6042. result.m[15] = 1.0;
  6043. result._markAsUpdated();
  6044. };
  6045. /**
  6046. * Creates a translation matrix
  6047. * @param x defines the translation on X axis
  6048. * @param y defines the translation on Y axis
  6049. * @param z defines the translationon Z axis
  6050. * @returns the new matrix
  6051. */
  6052. Matrix.Translation = function (x, y, z) {
  6053. var result = Matrix.Identity();
  6054. Matrix.TranslationToRef(x, y, z, result);
  6055. return result;
  6056. };
  6057. /**
  6058. * Creates a translation matrix and stores it in a given matrix
  6059. * @param x defines the translation on X axis
  6060. * @param y defines the translation on Y axis
  6061. * @param z defines the translationon Z axis
  6062. * @param result defines the target matrix
  6063. */
  6064. Matrix.TranslationToRef = function (x, y, z, result) {
  6065. 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);
  6066. };
  6067. /**
  6068. * Returns a new Matrix whose values are the interpolated values for "gradient" (float) between the ones of the matrices "startValue" and "endValue".
  6069. * @param startValue defines the start value
  6070. * @param endValue defines the end value
  6071. * @param gradient defines the gradient factor
  6072. * @returns the new matrix
  6073. */
  6074. Matrix.Lerp = function (startValue, endValue, gradient) {
  6075. var result = Matrix.Zero();
  6076. Matrix.LerpToRef(startValue, endValue, gradient, result);
  6077. return result;
  6078. };
  6079. /**
  6080. * Set the given matrix "result" as the interpolated values for "gradient" (float) between the ones of the matrices "startValue" and "endValue".
  6081. * @param startValue defines the start value
  6082. * @param endValue defines the end value
  6083. * @param gradient defines the gradient factor
  6084. * @param result defines the Matrix object where to store data
  6085. */
  6086. Matrix.LerpToRef = function (startValue, endValue, gradient, result) {
  6087. for (var index = 0; index < 16; index++) {
  6088. result.m[index] = startValue.m[index] * (1.0 - gradient) + endValue.m[index] * gradient;
  6089. }
  6090. result._markAsUpdated();
  6091. };
  6092. /**
  6093. * Builds a new matrix whose values are computed by:
  6094. * * decomposing the the "startValue" and "endValue" matrices into their respective scale, rotation and translation matrices
  6095. * * interpolating for "gradient" (float) the values between each of these decomposed matrices between the start and the end
  6096. * * recomposing a new matrix from these 3 interpolated scale, rotation and translation matrices
  6097. * @param startValue defines the first matrix
  6098. * @param endValue defines the second matrix
  6099. * @param gradient defines the gradient between the two matrices
  6100. * @returns the new matrix
  6101. */
  6102. Matrix.DecomposeLerp = function (startValue, endValue, gradient) {
  6103. var result = Matrix.Zero();
  6104. Matrix.DecomposeLerpToRef(startValue, endValue, gradient, result);
  6105. return result;
  6106. };
  6107. /**
  6108. * Update a matrix to values which are computed by:
  6109. * * decomposing the the "startValue" and "endValue" matrices into their respective scale, rotation and translation matrices
  6110. * * interpolating for "gradient" (float) the values between each of these decomposed matrices between the start and the end
  6111. * * recomposing a new matrix from these 3 interpolated scale, rotation and translation matrices
  6112. * @param startValue defines the first matrix
  6113. * @param endValue defines the second matrix
  6114. * @param gradient defines the gradient between the two matrices
  6115. * @param result defines the target matrix
  6116. */
  6117. Matrix.DecomposeLerpToRef = function (startValue, endValue, gradient, result) {
  6118. var startScale = MathTmp.Vector3[0];
  6119. var startRotation = MathTmp.Quaternion[0];
  6120. var startTranslation = MathTmp.Vector3[1];
  6121. startValue.decompose(startScale, startRotation, startTranslation);
  6122. var endScale = MathTmp.Vector3[2];
  6123. var endRotation = MathTmp.Quaternion[1];
  6124. var endTranslation = MathTmp.Vector3[3];
  6125. endValue.decompose(endScale, endRotation, endTranslation);
  6126. var resultScale = MathTmp.Vector3[4];
  6127. Vector3.LerpToRef(startScale, endScale, gradient, resultScale);
  6128. var resultRotation = MathTmp.Quaternion[2];
  6129. Quaternion.SlerpToRef(startRotation, endRotation, gradient, resultRotation);
  6130. var resultTranslation = MathTmp.Vector3[5];
  6131. Vector3.LerpToRef(startTranslation, endTranslation, gradient, resultTranslation);
  6132. Matrix.ComposeToRef(resultScale, resultRotation, resultTranslation, result);
  6133. };
  6134. /**
  6135. * 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"
  6136. * This function works in left handed mode
  6137. * @param eye defines the final position of the entity
  6138. * @param target defines where the entity should look at
  6139. * @param up defines the up vector for the entity
  6140. * @returns the new matrix
  6141. */
  6142. Matrix.LookAtLH = function (eye, target, up) {
  6143. var result = Matrix.Zero();
  6144. Matrix.LookAtLHToRef(eye, target, up, result);
  6145. return result;
  6146. };
  6147. /**
  6148. * 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".
  6149. * This function works in left handed mode
  6150. * @param eye defines the final position of the entity
  6151. * @param target defines where the entity should look at
  6152. * @param up defines the up vector for the entity
  6153. * @param result defines the target matrix
  6154. */
  6155. Matrix.LookAtLHToRef = function (eye, target, up, result) {
  6156. // Z axis
  6157. target.subtractToRef(eye, this._zAxis);
  6158. this._zAxis.normalize();
  6159. // X axis
  6160. Vector3.CrossToRef(up, this._zAxis, this._xAxis);
  6161. if (this._xAxis.lengthSquared() === 0) {
  6162. this._xAxis.x = 1.0;
  6163. }
  6164. else {
  6165. this._xAxis.normalize();
  6166. }
  6167. // Y axis
  6168. Vector3.CrossToRef(this._zAxis, this._xAxis, this._yAxis);
  6169. this._yAxis.normalize();
  6170. // Eye angles
  6171. var ex = -Vector3.Dot(this._xAxis, eye);
  6172. var ey = -Vector3.Dot(this._yAxis, eye);
  6173. var ez = -Vector3.Dot(this._zAxis, eye);
  6174. 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);
  6175. };
  6176. /**
  6177. * 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"
  6178. * This function works in right handed mode
  6179. * @param eye defines the final position of the entity
  6180. * @param target defines where the entity should look at
  6181. * @param up defines the up vector for the entity
  6182. * @returns the new matrix
  6183. */
  6184. Matrix.LookAtRH = function (eye, target, up) {
  6185. var result = Matrix.Zero();
  6186. Matrix.LookAtRHToRef(eye, target, up, result);
  6187. return result;
  6188. };
  6189. /**
  6190. * 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".
  6191. * This function works in right handed mode
  6192. * @param eye defines the final position of the entity
  6193. * @param target defines where the entity should look at
  6194. * @param up defines the up vector for the entity
  6195. * @param result defines the target matrix
  6196. */
  6197. Matrix.LookAtRHToRef = function (eye, target, up, result) {
  6198. // Z axis
  6199. eye.subtractToRef(target, this._zAxis);
  6200. this._zAxis.normalize();
  6201. // X axis
  6202. Vector3.CrossToRef(up, this._zAxis, this._xAxis);
  6203. if (this._xAxis.lengthSquared() === 0) {
  6204. this._xAxis.x = 1.0;
  6205. }
  6206. else {
  6207. this._xAxis.normalize();
  6208. }
  6209. // Y axis
  6210. Vector3.CrossToRef(this._zAxis, this._xAxis, this._yAxis);
  6211. this._yAxis.normalize();
  6212. // Eye angles
  6213. var ex = -Vector3.Dot(this._xAxis, eye);
  6214. var ey = -Vector3.Dot(this._yAxis, eye);
  6215. var ez = -Vector3.Dot(this._zAxis, eye);
  6216. 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);
  6217. };
  6218. /**
  6219. * Create a left-handed orthographic projection matrix
  6220. * @param width defines the viewport width
  6221. * @param height defines the viewport height
  6222. * @param znear defines the near clip plane
  6223. * @param zfar defines the far clip plane
  6224. * @returns a new matrix as a left-handed orthographic projection matrix
  6225. */
  6226. Matrix.OrthoLH = function (width, height, znear, zfar) {
  6227. var matrix = Matrix.Zero();
  6228. Matrix.OrthoLHToRef(width, height, znear, zfar, matrix);
  6229. return matrix;
  6230. };
  6231. /**
  6232. * Store a left-handed orthographic projection to a given matrix
  6233. * @param width defines the viewport width
  6234. * @param height defines the viewport height
  6235. * @param znear defines the near clip plane
  6236. * @param zfar defines the far clip plane
  6237. * @param result defines the target matrix
  6238. */
  6239. Matrix.OrthoLHToRef = function (width, height, znear, zfar, result) {
  6240. var n = znear;
  6241. var f = zfar;
  6242. var a = 2.0 / width;
  6243. var b = 2.0 / height;
  6244. var c = 2.0 / (f - n);
  6245. var d = -(f + n) / (f - n);
  6246. 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);
  6247. };
  6248. /**
  6249. * Create a left-handed orthographic projection matrix
  6250. * @param left defines the viewport left coordinate
  6251. * @param right defines the viewport right coordinate
  6252. * @param bottom defines the viewport bottom coordinate
  6253. * @param top defines the viewport top coordinate
  6254. * @param znear defines the near clip plane
  6255. * @param zfar defines the far clip plane
  6256. * @returns a new matrix as a left-handed orthographic projection matrix
  6257. */
  6258. Matrix.OrthoOffCenterLH = function (left, right, bottom, top, znear, zfar) {
  6259. var matrix = Matrix.Zero();
  6260. Matrix.OrthoOffCenterLHToRef(left, right, bottom, top, znear, zfar, matrix);
  6261. return matrix;
  6262. };
  6263. /**
  6264. * Stores a left-handed orthographic projection into a given matrix
  6265. * @param left defines the viewport left coordinate
  6266. * @param right defines the viewport right coordinate
  6267. * @param bottom defines the viewport bottom coordinate
  6268. * @param top defines the viewport top coordinate
  6269. * @param znear defines the near clip plane
  6270. * @param zfar defines the far clip plane
  6271. * @param result defines the target matrix
  6272. */
  6273. Matrix.OrthoOffCenterLHToRef = function (left, right, bottom, top, znear, zfar, result) {
  6274. var n = znear;
  6275. var f = zfar;
  6276. var a = 2.0 / (right - left);
  6277. var b = 2.0 / (top - bottom);
  6278. var c = 2.0 / (f - n);
  6279. var d = -(f + n) / (f - n);
  6280. var i0 = (left + right) / (left - right);
  6281. var i1 = (top + bottom) / (bottom - top);
  6282. 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);
  6283. };
  6284. /**
  6285. * Creates a right-handed orthographic projection matrix
  6286. * @param left defines the viewport left coordinate
  6287. * @param right defines the viewport right coordinate
  6288. * @param bottom defines the viewport bottom coordinate
  6289. * @param top defines the viewport top coordinate
  6290. * @param znear defines the near clip plane
  6291. * @param zfar defines the far clip plane
  6292. * @returns a new matrix as a right-handed orthographic projection matrix
  6293. */
  6294. Matrix.OrthoOffCenterRH = function (left, right, bottom, top, znear, zfar) {
  6295. var matrix = Matrix.Zero();
  6296. Matrix.OrthoOffCenterRHToRef(left, right, bottom, top, znear, zfar, matrix);
  6297. return matrix;
  6298. };
  6299. /**
  6300. * Stores a right-handed orthographic projection into a given matrix
  6301. * @param left defines the viewport left coordinate
  6302. * @param right defines the viewport right coordinate
  6303. * @param bottom defines the viewport bottom coordinate
  6304. * @param top defines the viewport top coordinate
  6305. * @param znear defines the near clip plane
  6306. * @param zfar defines the far clip plane
  6307. * @param result defines the target matrix
  6308. */
  6309. Matrix.OrthoOffCenterRHToRef = function (left, right, bottom, top, znear, zfar, result) {
  6310. Matrix.OrthoOffCenterLHToRef(left, right, bottom, top, znear, zfar, result);
  6311. result.m[10] *= -1.0;
  6312. };
  6313. /**
  6314. * Creates a left-handed perspective projection matrix
  6315. * @param width defines the viewport width
  6316. * @param height defines the viewport height
  6317. * @param znear defines the near clip plane
  6318. * @param zfar defines the far clip plane
  6319. * @returns a new matrix as a left-handed perspective projection matrix
  6320. */
  6321. Matrix.PerspectiveLH = function (width, height, znear, zfar) {
  6322. var matrix = Matrix.Zero();
  6323. var n = znear;
  6324. var f = zfar;
  6325. var a = 2.0 * n / width;
  6326. var b = 2.0 * n / height;
  6327. var c = (f + n) / (f - n);
  6328. var d = -2.0 * f * n / (f - n);
  6329. 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);
  6330. return matrix;
  6331. };
  6332. /**
  6333. * Creates a left-handed perspective projection matrix
  6334. * @param fov defines the horizontal field of view
  6335. * @param aspect defines the aspect ratio
  6336. * @param znear defines the near clip plane
  6337. * @param zfar defines the far clip plane
  6338. * @returns a new matrix as a left-handed perspective projection matrix
  6339. */
  6340. Matrix.PerspectiveFovLH = function (fov, aspect, znear, zfar) {
  6341. var matrix = Matrix.Zero();
  6342. Matrix.PerspectiveFovLHToRef(fov, aspect, znear, zfar, matrix);
  6343. return matrix;
  6344. };
  6345. /**
  6346. * Stores a left-handed perspective projection into a given matrix
  6347. * @param fov defines the horizontal field of view
  6348. * @param aspect defines the aspect ratio
  6349. * @param znear defines the near clip plane
  6350. * @param zfar defines the far clip plane
  6351. * @param result defines the target matrix
  6352. * @param isVerticalFovFixed defines it the fov is vertically fixed (default) or horizontally
  6353. */
  6354. Matrix.PerspectiveFovLHToRef = function (fov, aspect, znear, zfar, result, isVerticalFovFixed) {
  6355. if (isVerticalFovFixed === void 0) { isVerticalFovFixed = true; }
  6356. var n = znear;
  6357. var f = zfar;
  6358. var t = 1.0 / (Math.tan(fov * 0.5));
  6359. var a = isVerticalFovFixed ? (t / aspect) : t;
  6360. var b = isVerticalFovFixed ? t : (t * aspect);
  6361. var c = (f + n) / (f - n);
  6362. var d = -2.0 * f * n / (f - n);
  6363. 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);
  6364. };
  6365. /**
  6366. * Creates a right-handed perspective projection matrix
  6367. * @param fov defines the horizontal field of view
  6368. * @param aspect defines the aspect ratio
  6369. * @param znear defines the near clip plane
  6370. * @param zfar defines the far clip plane
  6371. * @returns a new matrix as a right-handed perspective projection matrix
  6372. */
  6373. Matrix.PerspectiveFovRH = function (fov, aspect, znear, zfar) {
  6374. var matrix = Matrix.Zero();
  6375. Matrix.PerspectiveFovRHToRef(fov, aspect, znear, zfar, matrix);
  6376. return matrix;
  6377. };
  6378. /**
  6379. * Stores a right-handed perspective projection into a given matrix
  6380. * @param fov defines the horizontal field of view
  6381. * @param aspect defines the aspect ratio
  6382. * @param znear defines the near clip plane
  6383. * @param zfar defines the far clip plane
  6384. * @param result defines the target matrix
  6385. * @param isVerticalFovFixed defines it the fov is vertically fixed (default) or horizontally
  6386. */
  6387. Matrix.PerspectiveFovRHToRef = function (fov, aspect, znear, zfar, result, isVerticalFovFixed) {
  6388. //alternatively this could be expressed as:
  6389. // m = PerspectiveFovLHToRef
  6390. // m[10] *= -1.0;
  6391. // m[11] *= -1.0;
  6392. if (isVerticalFovFixed === void 0) { isVerticalFovFixed = true; }
  6393. var n = znear;
  6394. var f = zfar;
  6395. var t = 1.0 / (Math.tan(fov * 0.5));
  6396. var a = isVerticalFovFixed ? (t / aspect) : t;
  6397. var b = isVerticalFovFixed ? t : (t * aspect);
  6398. var c = -(f + n) / (f - n);
  6399. var d = -2 * f * n / (f - n);
  6400. 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);
  6401. };
  6402. /**
  6403. * Stores a perspective projection for WebVR info a given matrix
  6404. * @param fov defines the field of view
  6405. * @param znear defines the near clip plane
  6406. * @param zfar defines the far clip plane
  6407. * @param result defines the target matrix
  6408. * @param rightHanded defines if the matrix must be in right-handed mode (false by default)
  6409. */
  6410. Matrix.PerspectiveFovWebVRToRef = function (fov, znear, zfar, result, rightHanded) {
  6411. if (rightHanded === void 0) { rightHanded = false; }
  6412. var rightHandedFactor = rightHanded ? -1 : 1;
  6413. var upTan = Math.tan(fov.upDegrees * Math.PI / 180.0);
  6414. var downTan = Math.tan(fov.downDegrees * Math.PI / 180.0);
  6415. var leftTan = Math.tan(fov.leftDegrees * Math.PI / 180.0);
  6416. var rightTan = Math.tan(fov.rightDegrees * Math.PI / 180.0);
  6417. var xScale = 2.0 / (leftTan + rightTan);
  6418. var yScale = 2.0 / (upTan + downTan);
  6419. result.m[0] = xScale;
  6420. result.m[1] = result.m[2] = result.m[3] = result.m[4] = 0.0;
  6421. result.m[5] = yScale;
  6422. result.m[6] = result.m[7] = 0.0;
  6423. result.m[8] = ((leftTan - rightTan) * xScale * 0.5);
  6424. result.m[9] = -((upTan - downTan) * yScale * 0.5);
  6425. result.m[10] = -zfar / (znear - zfar);
  6426. result.m[11] = 1.0 * rightHandedFactor;
  6427. result.m[12] = result.m[13] = result.m[15] = 0.0;
  6428. result.m[14] = -(2.0 * zfar * znear) / (zfar - znear);
  6429. result._markAsUpdated();
  6430. };
  6431. /**
  6432. * Computes a complete transformation matrix
  6433. * @param viewport defines the viewport to use
  6434. * @param world defines the world matrix
  6435. * @param view defines the view matrix
  6436. * @param projection defines the projection matrix
  6437. * @param zmin defines the near clip plane
  6438. * @param zmax defines the far clip plane
  6439. * @returns the transformation matrix
  6440. */
  6441. Matrix.GetFinalMatrix = function (viewport, world, view, projection, zmin, zmax) {
  6442. var cw = viewport.width;
  6443. var ch = viewport.height;
  6444. var cx = viewport.x;
  6445. var cy = viewport.y;
  6446. 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);
  6447. return world.multiply(view).multiply(projection).multiply(viewportMatrix);
  6448. };
  6449. /**
  6450. * Extracts a 2x2 matrix from a given matrix and store the result in a Float32Array
  6451. * @param matrix defines the matrix to use
  6452. * @returns a new Float32Array array with 4 elements : the 2x2 matrix extracted from the given matrix
  6453. */
  6454. Matrix.GetAsMatrix2x2 = function (matrix) {
  6455. return new Float32Array([
  6456. matrix.m[0], matrix.m[1],
  6457. matrix.m[4], matrix.m[5]
  6458. ]);
  6459. };
  6460. /**
  6461. * Extracts a 3x3 matrix from a given matrix and store the result in a Float32Array
  6462. * @param matrix defines the matrix to use
  6463. * @returns a new Float32Array array with 9 elements : the 3x3 matrix extracted from the given matrix
  6464. */
  6465. Matrix.GetAsMatrix3x3 = function (matrix) {
  6466. return new Float32Array([
  6467. matrix.m[0], matrix.m[1], matrix.m[2],
  6468. matrix.m[4], matrix.m[5], matrix.m[6],
  6469. matrix.m[8], matrix.m[9], matrix.m[10]
  6470. ]);
  6471. };
  6472. /**
  6473. * Compute the transpose of a given matrix
  6474. * @param matrix defines the matrix to transpose
  6475. * @returns the new matrix
  6476. */
  6477. Matrix.Transpose = function (matrix) {
  6478. var result = new Matrix();
  6479. Matrix.TransposeToRef(matrix, result);
  6480. return result;
  6481. };
  6482. /**
  6483. * Compute the transpose of a matrix and store it in a target matrix
  6484. * @param matrix defines the matrix to transpose
  6485. * @param result defines the target matrix
  6486. */
  6487. Matrix.TransposeToRef = function (matrix, result) {
  6488. result.m[0] = matrix.m[0];
  6489. result.m[1] = matrix.m[4];
  6490. result.m[2] = matrix.m[8];
  6491. result.m[3] = matrix.m[12];
  6492. result.m[4] = matrix.m[1];
  6493. result.m[5] = matrix.m[5];
  6494. result.m[6] = matrix.m[9];
  6495. result.m[7] = matrix.m[13];
  6496. result.m[8] = matrix.m[2];
  6497. result.m[9] = matrix.m[6];
  6498. result.m[10] = matrix.m[10];
  6499. result.m[11] = matrix.m[14];
  6500. result.m[12] = matrix.m[3];
  6501. result.m[13] = matrix.m[7];
  6502. result.m[14] = matrix.m[11];
  6503. result.m[15] = matrix.m[15];
  6504. };
  6505. /**
  6506. * Computes a reflection matrix from a plane
  6507. * @param plane defines the reflection plane
  6508. * @returns a new matrix
  6509. */
  6510. Matrix.Reflection = function (plane) {
  6511. var matrix = new Matrix();
  6512. Matrix.ReflectionToRef(plane, matrix);
  6513. return matrix;
  6514. };
  6515. /**
  6516. * Computes a reflection matrix from a plane
  6517. * @param plane defines the reflection plane
  6518. * @param result defines the target matrix
  6519. */
  6520. Matrix.ReflectionToRef = function (plane, result) {
  6521. plane.normalize();
  6522. var x = plane.normal.x;
  6523. var y = plane.normal.y;
  6524. var z = plane.normal.z;
  6525. var temp = -2 * x;
  6526. var temp2 = -2 * y;
  6527. var temp3 = -2 * z;
  6528. result.m[0] = (temp * x) + 1;
  6529. result.m[1] = temp2 * x;
  6530. result.m[2] = temp3 * x;
  6531. result.m[3] = 0.0;
  6532. result.m[4] = temp * y;
  6533. result.m[5] = (temp2 * y) + 1;
  6534. result.m[6] = temp3 * y;
  6535. result.m[7] = 0.0;
  6536. result.m[8] = temp * z;
  6537. result.m[9] = temp2 * z;
  6538. result.m[10] = (temp3 * z) + 1;
  6539. result.m[11] = 0.0;
  6540. result.m[12] = temp * plane.d;
  6541. result.m[13] = temp2 * plane.d;
  6542. result.m[14] = temp3 * plane.d;
  6543. result.m[15] = 1.0;
  6544. result._markAsUpdated();
  6545. };
  6546. /**
  6547. * Sets the given matrix as a rotation matrix composed from the 3 left handed axes
  6548. * @param xaxis defines the value of the 1st axis
  6549. * @param yaxis defines the value of the 2nd axis
  6550. * @param zaxis defines the value of the 3rd axis
  6551. * @param result defines the target matrix
  6552. */
  6553. Matrix.FromXYZAxesToRef = function (xaxis, yaxis, zaxis, result) {
  6554. result.m[0] = xaxis.x;
  6555. result.m[1] = xaxis.y;
  6556. result.m[2] = xaxis.z;
  6557. result.m[3] = 0.0;
  6558. result.m[4] = yaxis.x;
  6559. result.m[5] = yaxis.y;
  6560. result.m[6] = yaxis.z;
  6561. result.m[7] = 0.0;
  6562. result.m[8] = zaxis.x;
  6563. result.m[9] = zaxis.y;
  6564. result.m[10] = zaxis.z;
  6565. result.m[11] = 0.0;
  6566. result.m[12] = 0.0;
  6567. result.m[13] = 0.0;
  6568. result.m[14] = 0.0;
  6569. result.m[15] = 1.0;
  6570. result._markAsUpdated();
  6571. };
  6572. /**
  6573. * Creates a rotation matrix from a quaternion and stores it in a target matrix
  6574. * @param quat defines the quaternion to use
  6575. * @param result defines the target matrix
  6576. */
  6577. Matrix.FromQuaternionToRef = function (quat, result) {
  6578. var xx = quat.x * quat.x;
  6579. var yy = quat.y * quat.y;
  6580. var zz = quat.z * quat.z;
  6581. var xy = quat.x * quat.y;
  6582. var zw = quat.z * quat.w;
  6583. var zx = quat.z * quat.x;
  6584. var yw = quat.y * quat.w;
  6585. var yz = quat.y * quat.z;
  6586. var xw = quat.x * quat.w;
  6587. result.m[0] = 1.0 - (2.0 * (yy + zz));
  6588. result.m[1] = 2.0 * (xy + zw);
  6589. result.m[2] = 2.0 * (zx - yw);
  6590. result.m[3] = 0.0;
  6591. result.m[4] = 2.0 * (xy - zw);
  6592. result.m[5] = 1.0 - (2.0 * (zz + xx));
  6593. result.m[6] = 2.0 * (yz + xw);
  6594. result.m[7] = 0.0;
  6595. result.m[8] = 2.0 * (zx + yw);
  6596. result.m[9] = 2.0 * (yz - xw);
  6597. result.m[10] = 1.0 - (2.0 * (yy + xx));
  6598. result.m[11] = 0.0;
  6599. result.m[12] = 0.0;
  6600. result.m[13] = 0.0;
  6601. result.m[14] = 0.0;
  6602. result.m[15] = 1.0;
  6603. result._markAsUpdated();
  6604. };
  6605. Matrix._tempQuaternion = new Quaternion();
  6606. Matrix._xAxis = Vector3.Zero();
  6607. Matrix._yAxis = Vector3.Zero();
  6608. Matrix._zAxis = Vector3.Zero();
  6609. Matrix._updateFlagSeed = 0;
  6610. Matrix._identityReadOnly = Matrix.Identity();
  6611. return Matrix;
  6612. }());
  6613. BABYLON.Matrix = Matrix;
  6614. var Plane = /** @class */ (function () {
  6615. /**
  6616. * Creates a Plane object according to the given floats a, b, c, d and the plane equation : ax + by + cz + d = 0
  6617. */
  6618. function Plane(a, b, c, d) {
  6619. this.normal = new Vector3(a, b, c);
  6620. this.d = d;
  6621. }
  6622. /**
  6623. * Returns the plane coordinates as a new array of 4 elements [a, b, c, d].
  6624. */
  6625. Plane.prototype.asArray = function () {
  6626. return [this.normal.x, this.normal.y, this.normal.z, this.d];
  6627. };
  6628. // Methods
  6629. /**
  6630. * Returns a new plane copied from the current Plane.
  6631. */
  6632. Plane.prototype.clone = function () {
  6633. return new Plane(this.normal.x, this.normal.y, this.normal.z, this.d);
  6634. };
  6635. /**
  6636. * Returns the string "Plane".
  6637. */
  6638. Plane.prototype.getClassName = function () {
  6639. return "Plane";
  6640. };
  6641. /**
  6642. * Returns the Plane hash code.
  6643. */
  6644. Plane.prototype.getHashCode = function () {
  6645. var hash = this.normal.getHashCode();
  6646. hash = (hash * 397) ^ (this.d || 0);
  6647. return hash;
  6648. };
  6649. /**
  6650. * Normalize the current Plane in place.
  6651. * Returns the updated Plane.
  6652. */
  6653. Plane.prototype.normalize = function () {
  6654. var norm = (Math.sqrt((this.normal.x * this.normal.x) + (this.normal.y * this.normal.y) + (this.normal.z * this.normal.z)));
  6655. var magnitude = 0.0;
  6656. if (norm !== 0) {
  6657. magnitude = 1.0 / norm;
  6658. }
  6659. this.normal.x *= magnitude;
  6660. this.normal.y *= magnitude;
  6661. this.normal.z *= magnitude;
  6662. this.d *= magnitude;
  6663. return this;
  6664. };
  6665. /**
  6666. * Returns a new Plane as the result of the transformation of the current Plane by the given matrix.
  6667. */
  6668. Plane.prototype.transform = function (transformation) {
  6669. var transposedMatrix = Matrix.Transpose(transformation);
  6670. var x = this.normal.x;
  6671. var y = this.normal.y;
  6672. var z = this.normal.z;
  6673. var d = this.d;
  6674. var normalX = (((x * transposedMatrix.m[0]) + (y * transposedMatrix.m[1])) + (z * transposedMatrix.m[2])) + (d * transposedMatrix.m[3]);
  6675. var normalY = (((x * transposedMatrix.m[4]) + (y * transposedMatrix.m[5])) + (z * transposedMatrix.m[6])) + (d * transposedMatrix.m[7]);
  6676. var normalZ = (((x * transposedMatrix.m[8]) + (y * transposedMatrix.m[9])) + (z * transposedMatrix.m[10])) + (d * transposedMatrix.m[11]);
  6677. var finalD = (((x * transposedMatrix.m[12]) + (y * transposedMatrix.m[13])) + (z * transposedMatrix.m[14])) + (d * transposedMatrix.m[15]);
  6678. return new Plane(normalX, normalY, normalZ, finalD);
  6679. };
  6680. /**
  6681. * Returns the dot product (float) of the point coordinates and the plane normal.
  6682. */
  6683. Plane.prototype.dotCoordinate = function (point) {
  6684. return ((((this.normal.x * point.x) + (this.normal.y * point.y)) + (this.normal.z * point.z)) + this.d);
  6685. };
  6686. /**
  6687. * Updates the current Plane from the plane defined by the three given points.
  6688. * Returns the updated Plane.
  6689. */
  6690. Plane.prototype.copyFromPoints = function (point1, point2, point3) {
  6691. var x1 = point2.x - point1.x;
  6692. var y1 = point2.y - point1.y;
  6693. var z1 = point2.z - point1.z;
  6694. var x2 = point3.x - point1.x;
  6695. var y2 = point3.y - point1.y;
  6696. var z2 = point3.z - point1.z;
  6697. var yz = (y1 * z2) - (z1 * y2);
  6698. var xz = (z1 * x2) - (x1 * z2);
  6699. var xy = (x1 * y2) - (y1 * x2);
  6700. var pyth = (Math.sqrt((yz * yz) + (xz * xz) + (xy * xy)));
  6701. var invPyth;
  6702. if (pyth !== 0) {
  6703. invPyth = 1.0 / pyth;
  6704. }
  6705. else {
  6706. invPyth = 0.0;
  6707. }
  6708. this.normal.x = yz * invPyth;
  6709. this.normal.y = xz * invPyth;
  6710. this.normal.z = xy * invPyth;
  6711. this.d = -((this.normal.x * point1.x) + (this.normal.y * point1.y) + (this.normal.z * point1.z));
  6712. return this;
  6713. };
  6714. /**
  6715. * Boolean : True is the vector "direction" is the same side than the plane normal.
  6716. */
  6717. Plane.prototype.isFrontFacingTo = function (direction, epsilon) {
  6718. var dot = Vector3.Dot(this.normal, direction);
  6719. return (dot <= epsilon);
  6720. };
  6721. /**
  6722. * Returns the signed distance (float) from the given point to the Plane.
  6723. */
  6724. Plane.prototype.signedDistanceTo = function (point) {
  6725. return Vector3.Dot(point, this.normal) + this.d;
  6726. };
  6727. // Statics
  6728. /**
  6729. * Returns a new Plane from the given array.
  6730. */
  6731. Plane.FromArray = function (array) {
  6732. return new Plane(array[0], array[1], array[2], array[3]);
  6733. };
  6734. /**
  6735. * Returns a new Plane defined by the three given points.
  6736. */
  6737. Plane.FromPoints = function (point1, point2, point3) {
  6738. var result = new Plane(0.0, 0.0, 0.0, 0.0);
  6739. result.copyFromPoints(point1, point2, point3);
  6740. return result;
  6741. };
  6742. /**
  6743. * Returns a new Plane the normal vector to this plane at the given origin point.
  6744. * Note : the vector "normal" is updated because normalized.
  6745. */
  6746. Plane.FromPositionAndNormal = function (origin, normal) {
  6747. var result = new Plane(0.0, 0.0, 0.0, 0.0);
  6748. normal.normalize();
  6749. result.normal = normal;
  6750. result.d = -(normal.x * origin.x + normal.y * origin.y + normal.z * origin.z);
  6751. return result;
  6752. };
  6753. /**
  6754. * Returns the signed distance between the plane defined by the normal vector at the "origin"" point and the given other point.
  6755. */
  6756. Plane.SignedDistanceToPlaneFromPositionAndNormal = function (origin, normal, point) {
  6757. var d = -(normal.x * origin.x + normal.y * origin.y + normal.z * origin.z);
  6758. return Vector3.Dot(point, normal) + d;
  6759. };
  6760. return Plane;
  6761. }());
  6762. BABYLON.Plane = Plane;
  6763. var Viewport = /** @class */ (function () {
  6764. /**
  6765. * Creates a Viewport object located at (x, y) and sized (width, height).
  6766. */
  6767. function Viewport(x, y, width, height) {
  6768. this.x = x;
  6769. this.y = y;
  6770. this.width = width;
  6771. this.height = height;
  6772. }
  6773. Viewport.prototype.toGlobal = function (renderWidthOrEngine, renderHeight) {
  6774. if (renderWidthOrEngine.getRenderWidth) {
  6775. var engine = renderWidthOrEngine;
  6776. return this.toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
  6777. }
  6778. var renderWidth = renderWidthOrEngine;
  6779. return new Viewport(this.x * renderWidth, this.y * renderHeight, this.width * renderWidth, this.height * renderHeight);
  6780. };
  6781. /**
  6782. * Returns a new Viewport copied from the current one.
  6783. */
  6784. Viewport.prototype.clone = function () {
  6785. return new Viewport(this.x, this.y, this.width, this.height);
  6786. };
  6787. return Viewport;
  6788. }());
  6789. BABYLON.Viewport = Viewport;
  6790. var Frustum = /** @class */ (function () {
  6791. function Frustum() {
  6792. }
  6793. /**
  6794. * Returns a new array of 6 Frustum planes computed by the given transformation matrix.
  6795. */
  6796. Frustum.GetPlanes = function (transform) {
  6797. var frustumPlanes = [];
  6798. for (var index = 0; index < 6; index++) {
  6799. frustumPlanes.push(new Plane(0.0, 0.0, 0.0, 0.0));
  6800. }
  6801. Frustum.GetPlanesToRef(transform, frustumPlanes);
  6802. return frustumPlanes;
  6803. };
  6804. Frustum.GetNearPlaneToRef = function (transform, frustumPlane) {
  6805. frustumPlane.normal.x = transform.m[3] + transform.m[2];
  6806. frustumPlane.normal.y = transform.m[7] + transform.m[6];
  6807. frustumPlane.normal.z = transform.m[11] + transform.m[10];
  6808. frustumPlane.d = transform.m[15] + transform.m[14];
  6809. frustumPlane.normalize();
  6810. };
  6811. Frustum.GetFarPlaneToRef = function (transform, frustumPlane) {
  6812. frustumPlane.normal.x = transform.m[3] - transform.m[2];
  6813. frustumPlane.normal.y = transform.m[7] - transform.m[6];
  6814. frustumPlane.normal.z = transform.m[11] - transform.m[10];
  6815. frustumPlane.d = transform.m[15] - transform.m[14];
  6816. frustumPlane.normalize();
  6817. };
  6818. Frustum.GetLeftPlaneToRef = function (transform, frustumPlane) {
  6819. frustumPlane.normal.x = transform.m[3] + transform.m[0];
  6820. frustumPlane.normal.y = transform.m[7] + transform.m[4];
  6821. frustumPlane.normal.z = transform.m[11] + transform.m[8];
  6822. frustumPlane.d = transform.m[15] + transform.m[12];
  6823. frustumPlane.normalize();
  6824. };
  6825. Frustum.GetRightPlaneToRef = function (transform, frustumPlane) {
  6826. frustumPlane.normal.x = transform.m[3] - transform.m[0];
  6827. frustumPlane.normal.y = transform.m[7] - transform.m[4];
  6828. frustumPlane.normal.z = transform.m[11] - transform.m[8];
  6829. frustumPlane.d = transform.m[15] - transform.m[12];
  6830. frustumPlane.normalize();
  6831. };
  6832. Frustum.GetTopPlaneToRef = function (transform, frustumPlane) {
  6833. frustumPlane.normal.x = transform.m[3] - transform.m[1];
  6834. frustumPlane.normal.y = transform.m[7] - transform.m[5];
  6835. frustumPlane.normal.z = transform.m[11] - transform.m[9];
  6836. frustumPlane.d = transform.m[15] - transform.m[13];
  6837. frustumPlane.normalize();
  6838. };
  6839. Frustum.GetBottomPlaneToRef = function (transform, frustumPlane) {
  6840. frustumPlane.normal.x = transform.m[3] + transform.m[1];
  6841. frustumPlane.normal.y = transform.m[7] + transform.m[5];
  6842. frustumPlane.normal.z = transform.m[11] + transform.m[9];
  6843. frustumPlane.d = transform.m[15] + transform.m[13];
  6844. frustumPlane.normalize();
  6845. };
  6846. /**
  6847. * Sets the given array "frustumPlanes" with the 6 Frustum planes computed by the given transformation matrix.
  6848. */
  6849. Frustum.GetPlanesToRef = function (transform, frustumPlanes) {
  6850. // Near
  6851. Frustum.GetNearPlaneToRef(transform, frustumPlanes[0]);
  6852. // Far
  6853. Frustum.GetFarPlaneToRef(transform, frustumPlanes[1]);
  6854. // Left
  6855. Frustum.GetLeftPlaneToRef(transform, frustumPlanes[2]);
  6856. // Right
  6857. Frustum.GetRightPlaneToRef(transform, frustumPlanes[3]);
  6858. // Top
  6859. Frustum.GetTopPlaneToRef(transform, frustumPlanes[4]);
  6860. // Bottom
  6861. Frustum.GetBottomPlaneToRef(transform, frustumPlanes[5]);
  6862. };
  6863. return Frustum;
  6864. }());
  6865. BABYLON.Frustum = Frustum;
  6866. /** Defines supported spaces */
  6867. var Space;
  6868. (function (Space) {
  6869. /** Local (object) space */
  6870. Space[Space["LOCAL"] = 0] = "LOCAL";
  6871. /** World space */
  6872. Space[Space["WORLD"] = 1] = "WORLD";
  6873. /** Bone space */
  6874. Space[Space["BONE"] = 2] = "BONE";
  6875. })(Space = BABYLON.Space || (BABYLON.Space = {}));
  6876. /** Defines the 3 main axes */
  6877. var Axis = /** @class */ (function () {
  6878. function Axis() {
  6879. }
  6880. /** X axis */
  6881. Axis.X = new Vector3(1.0, 0.0, 0.0);
  6882. /** Y axis */
  6883. Axis.Y = new Vector3(0.0, 1.0, 0.0);
  6884. /** Z axis */
  6885. Axis.Z = new Vector3(0.0, 0.0, 1.0);
  6886. return Axis;
  6887. }());
  6888. BABYLON.Axis = Axis;
  6889. ;
  6890. var BezierCurve = /** @class */ (function () {
  6891. function BezierCurve() {
  6892. }
  6893. /**
  6894. * Returns the cubic Bezier interpolated value (float) at "t" (float) from the given x1, y1, x2, y2 floats.
  6895. */
  6896. BezierCurve.interpolate = function (t, x1, y1, x2, y2) {
  6897. // Extract X (which is equal to time here)
  6898. var f0 = 1 - 3 * x2 + 3 * x1;
  6899. var f1 = 3 * x2 - 6 * x1;
  6900. var f2 = 3 * x1;
  6901. var refinedT = t;
  6902. for (var i = 0; i < 5; i++) {
  6903. var refinedT2 = refinedT * refinedT;
  6904. var refinedT3 = refinedT2 * refinedT;
  6905. var x = f0 * refinedT3 + f1 * refinedT2 + f2 * refinedT;
  6906. var slope = 1.0 / (3.0 * f0 * refinedT2 + 2.0 * f1 * refinedT + f2);
  6907. refinedT -= (x - t) * slope;
  6908. refinedT = Math.min(1, Math.max(0, refinedT));
  6909. }
  6910. // Resolve cubic bezier for the given x
  6911. return 3 * Math.pow(1 - refinedT, 2) * refinedT * y1 +
  6912. 3 * (1 - refinedT) * Math.pow(refinedT, 2) * y2 +
  6913. Math.pow(refinedT, 3);
  6914. };
  6915. return BezierCurve;
  6916. }());
  6917. BABYLON.BezierCurve = BezierCurve;
  6918. /**
  6919. * Defines potential orientation for back face culling
  6920. */
  6921. var Orientation;
  6922. (function (Orientation) {
  6923. /**
  6924. * Clockwise
  6925. */
  6926. Orientation[Orientation["CW"] = 0] = "CW";
  6927. /** Counter clockwise */
  6928. Orientation[Orientation["CCW"] = 1] = "CCW";
  6929. })(Orientation = BABYLON.Orientation || (BABYLON.Orientation = {}));
  6930. /**
  6931. * Defines angle representation
  6932. */
  6933. var Angle = /** @class */ (function () {
  6934. /**
  6935. * Creates an Angle object of "radians" radians (float).
  6936. */
  6937. function Angle(radians) {
  6938. this._radians = radians;
  6939. if (this._radians < 0.0)
  6940. this._radians += (2.0 * Math.PI);
  6941. }
  6942. /**
  6943. * Get value in degrees
  6944. * @returns the Angle value in degrees (float)
  6945. */
  6946. Angle.prototype.degrees = function () {
  6947. return this._radians * 180.0 / Math.PI;
  6948. };
  6949. /**
  6950. * Get value in radians
  6951. * @returns the Angle value in radians (float)
  6952. */
  6953. Angle.prototype.radians = function () {
  6954. return this._radians;
  6955. };
  6956. /**
  6957. * Gets a new Angle object valued with the angle value in radians between the two given vectors
  6958. * @param a defines first vector
  6959. * @param b defines second vector
  6960. * @returns a new Angle
  6961. */
  6962. Angle.BetweenTwoPoints = function (a, b) {
  6963. var delta = b.subtract(a);
  6964. var theta = Math.atan2(delta.y, delta.x);
  6965. return new Angle(theta);
  6966. };
  6967. /**
  6968. * Gets a new Angle object from the given float in radians
  6969. * @param radians defines the angle value in radians
  6970. * @returns a new Angle
  6971. */
  6972. Angle.FromRadians = function (radians) {
  6973. return new Angle(radians);
  6974. };
  6975. /**
  6976. * Gets a new Angle object from the given float in degrees
  6977. * @param degrees defines the angle value in degrees
  6978. * @returns a new Angle
  6979. */
  6980. Angle.FromDegrees = function (degrees) {
  6981. return new Angle(degrees * Math.PI / 180.0);
  6982. };
  6983. return Angle;
  6984. }());
  6985. BABYLON.Angle = Angle;
  6986. var Arc2 = /** @class */ (function () {
  6987. /**
  6988. * Creates an Arc object from the three given points : start, middle and end.
  6989. */
  6990. function Arc2(startPoint, midPoint, endPoint) {
  6991. this.startPoint = startPoint;
  6992. this.midPoint = midPoint;
  6993. this.endPoint = endPoint;
  6994. var temp = Math.pow(midPoint.x, 2) + Math.pow(midPoint.y, 2);
  6995. var startToMid = (Math.pow(startPoint.x, 2) + Math.pow(startPoint.y, 2) - temp) / 2.;
  6996. var midToEnd = (temp - Math.pow(endPoint.x, 2) - Math.pow(endPoint.y, 2)) / 2.;
  6997. var det = (startPoint.x - midPoint.x) * (midPoint.y - endPoint.y) - (midPoint.x - endPoint.x) * (startPoint.y - midPoint.y);
  6998. 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);
  6999. this.radius = this.centerPoint.subtract(this.startPoint).length();
  7000. this.startAngle = Angle.BetweenTwoPoints(this.centerPoint, this.startPoint);
  7001. var a1 = this.startAngle.degrees();
  7002. var a2 = Angle.BetweenTwoPoints(this.centerPoint, this.midPoint).degrees();
  7003. var a3 = Angle.BetweenTwoPoints(this.centerPoint, this.endPoint).degrees();
  7004. // angles correction
  7005. if (a2 - a1 > +180.0)
  7006. a2 -= 360.0;
  7007. if (a2 - a1 < -180.0)
  7008. a2 += 360.0;
  7009. if (a3 - a2 > +180.0)
  7010. a3 -= 360.0;
  7011. if (a3 - a2 < -180.0)
  7012. a3 += 360.0;
  7013. this.orientation = (a2 - a1) < 0 ? Orientation.CW : Orientation.CCW;
  7014. this.angle = Angle.FromDegrees(this.orientation === Orientation.CW ? a1 - a3 : a3 - a1);
  7015. }
  7016. return Arc2;
  7017. }());
  7018. BABYLON.Arc2 = Arc2;
  7019. var Path2 = /** @class */ (function () {
  7020. /**
  7021. * Creates a Path2 object from the starting 2D coordinates x and y.
  7022. */
  7023. function Path2(x, y) {
  7024. this._points = new Array();
  7025. this._length = 0.0;
  7026. this.closed = false;
  7027. this._points.push(new Vector2(x, y));
  7028. }
  7029. /**
  7030. * Adds a new segment until the given coordinates (x, y) to the current Path2.
  7031. * Returns the updated Path2.
  7032. */
  7033. Path2.prototype.addLineTo = function (x, y) {
  7034. if (this.closed) {
  7035. return this;
  7036. }
  7037. var newPoint = new Vector2(x, y);
  7038. var previousPoint = this._points[this._points.length - 1];
  7039. this._points.push(newPoint);
  7040. this._length += newPoint.subtract(previousPoint).length();
  7041. return this;
  7042. };
  7043. /**
  7044. * 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.
  7045. * Returns the updated Path2.
  7046. */
  7047. Path2.prototype.addArcTo = function (midX, midY, endX, endY, numberOfSegments) {
  7048. if (numberOfSegments === void 0) { numberOfSegments = 36; }
  7049. if (this.closed) {
  7050. return this;
  7051. }
  7052. var startPoint = this._points[this._points.length - 1];
  7053. var midPoint = new Vector2(midX, midY);
  7054. var endPoint = new Vector2(endX, endY);
  7055. var arc = new Arc2(startPoint, midPoint, endPoint);
  7056. var increment = arc.angle.radians() / numberOfSegments;
  7057. if (arc.orientation === Orientation.CW)
  7058. increment *= -1;
  7059. var currentAngle = arc.startAngle.radians() + increment;
  7060. for (var i = 0; i < numberOfSegments; i++) {
  7061. var x = Math.cos(currentAngle) * arc.radius + arc.centerPoint.x;
  7062. var y = Math.sin(currentAngle) * arc.radius + arc.centerPoint.y;
  7063. this.addLineTo(x, y);
  7064. currentAngle += increment;
  7065. }
  7066. return this;
  7067. };
  7068. /**
  7069. * Closes the Path2.
  7070. * Returns the Path2.
  7071. */
  7072. Path2.prototype.close = function () {
  7073. this.closed = true;
  7074. return this;
  7075. };
  7076. /**
  7077. * Returns the Path2 total length (float).
  7078. */
  7079. Path2.prototype.length = function () {
  7080. var result = this._length;
  7081. if (!this.closed) {
  7082. var lastPoint = this._points[this._points.length - 1];
  7083. var firstPoint = this._points[0];
  7084. result += (firstPoint.subtract(lastPoint).length());
  7085. }
  7086. return result;
  7087. };
  7088. /**
  7089. * Returns the Path2 internal array of points.
  7090. */
  7091. Path2.prototype.getPoints = function () {
  7092. return this._points;
  7093. };
  7094. /**
  7095. * Returns a new Vector2 located at a percentage of the Path2 total length on this path.
  7096. */
  7097. Path2.prototype.getPointAtLengthPosition = function (normalizedLengthPosition) {
  7098. if (normalizedLengthPosition < 0 || normalizedLengthPosition > 1) {
  7099. return Vector2.Zero();
  7100. }
  7101. var lengthPosition = normalizedLengthPosition * this.length();
  7102. var previousOffset = 0;
  7103. for (var i = 0; i < this._points.length; i++) {
  7104. var j = (i + 1) % this._points.length;
  7105. var a = this._points[i];
  7106. var b = this._points[j];
  7107. var bToA = b.subtract(a);
  7108. var nextOffset = (bToA.length() + previousOffset);
  7109. if (lengthPosition >= previousOffset && lengthPosition <= nextOffset) {
  7110. var dir = bToA.normalize();
  7111. var localOffset = lengthPosition - previousOffset;
  7112. return new Vector2(a.x + (dir.x * localOffset), a.y + (dir.y * localOffset));
  7113. }
  7114. previousOffset = nextOffset;
  7115. }
  7116. return Vector2.Zero();
  7117. };
  7118. /**
  7119. * Returns a new Path2 starting at the coordinates (x, y).
  7120. */
  7121. Path2.StartingAt = function (x, y) {
  7122. return new Path2(x, y);
  7123. };
  7124. return Path2;
  7125. }());
  7126. BABYLON.Path2 = Path2;
  7127. var Path3D = /** @class */ (function () {
  7128. /**
  7129. * new Path3D(path, normal, raw)
  7130. * Creates a Path3D. A Path3D is a logical math object, so not a mesh.
  7131. * please read the description in the tutorial : http://doc.babylonjs.com/tutorials/How_to_use_Path3D
  7132. * path : an array of Vector3, the curve axis of the Path3D
  7133. * normal (optional) : Vector3, the first wanted normal to the curve. Ex (0, 1, 0) for a vertical normal.
  7134. * raw (optional, default false) : boolean, if true the returned Path3D isn't normalized. Useful to depict path acceleration or speed.
  7135. */
  7136. function Path3D(path, firstNormal, raw) {
  7137. if (firstNormal === void 0) { firstNormal = null; }
  7138. this.path = path;
  7139. this._curve = new Array();
  7140. this._distances = new Array();
  7141. this._tangents = new Array();
  7142. this._normals = new Array();
  7143. this._binormals = new Array();
  7144. for (var p = 0; p < path.length; p++) {
  7145. this._curve[p] = path[p].clone(); // hard copy
  7146. }
  7147. this._raw = raw || false;
  7148. this._compute(firstNormal);
  7149. }
  7150. /**
  7151. * Returns the Path3D array of successive Vector3 designing its curve.
  7152. */
  7153. Path3D.prototype.getCurve = function () {
  7154. return this._curve;
  7155. };
  7156. /**
  7157. * Returns an array populated with tangent vectors on each Path3D curve point.
  7158. */
  7159. Path3D.prototype.getTangents = function () {
  7160. return this._tangents;
  7161. };
  7162. /**
  7163. * Returns an array populated with normal vectors on each Path3D curve point.
  7164. */
  7165. Path3D.prototype.getNormals = function () {
  7166. return this._normals;
  7167. };
  7168. /**
  7169. * Returns an array populated with binormal vectors on each Path3D curve point.
  7170. */
  7171. Path3D.prototype.getBinormals = function () {
  7172. return this._binormals;
  7173. };
  7174. /**
  7175. * Returns an array populated with distances (float) of the i-th point from the first curve point.
  7176. */
  7177. Path3D.prototype.getDistances = function () {
  7178. return this._distances;
  7179. };
  7180. /**
  7181. * Forces the Path3D tangent, normal, binormal and distance recomputation.
  7182. * Returns the same object updated.
  7183. */
  7184. Path3D.prototype.update = function (path, firstNormal) {
  7185. if (firstNormal === void 0) { firstNormal = null; }
  7186. for (var p = 0; p < path.length; p++) {
  7187. this._curve[p].x = path[p].x;
  7188. this._curve[p].y = path[p].y;
  7189. this._curve[p].z = path[p].z;
  7190. }
  7191. this._compute(firstNormal);
  7192. return this;
  7193. };
  7194. // private function compute() : computes tangents, normals and binormals
  7195. Path3D.prototype._compute = function (firstNormal) {
  7196. var l = this._curve.length;
  7197. // first and last tangents
  7198. this._tangents[0] = this._getFirstNonNullVector(0);
  7199. if (!this._raw) {
  7200. this._tangents[0].normalize();
  7201. }
  7202. this._tangents[l - 1] = this._curve[l - 1].subtract(this._curve[l - 2]);
  7203. if (!this._raw) {
  7204. this._tangents[l - 1].normalize();
  7205. }
  7206. // normals and binormals at first point : arbitrary vector with _normalVector()
  7207. var tg0 = this._tangents[0];
  7208. var pp0 = this._normalVector(this._curve[0], tg0, firstNormal);
  7209. this._normals[0] = pp0;
  7210. if (!this._raw) {
  7211. this._normals[0].normalize();
  7212. }
  7213. this._binormals[0] = Vector3.Cross(tg0, this._normals[0]);
  7214. if (!this._raw) {
  7215. this._binormals[0].normalize();
  7216. }
  7217. this._distances[0] = 0.0;
  7218. // normals and binormals : next points
  7219. var prev; // previous vector (segment)
  7220. var cur; // current vector (segment)
  7221. var curTang; // current tangent
  7222. // previous normal
  7223. var prevBinor; // previous binormal
  7224. for (var i = 1; i < l; i++) {
  7225. // tangents
  7226. prev = this._getLastNonNullVector(i);
  7227. if (i < l - 1) {
  7228. cur = this._getFirstNonNullVector(i);
  7229. this._tangents[i] = prev.add(cur);
  7230. this._tangents[i].normalize();
  7231. }
  7232. this._distances[i] = this._distances[i - 1] + prev.length();
  7233. // normals and binormals
  7234. // http://www.cs.cmu.edu/afs/andrew/scs/cs/15-462/web/old/asst2camera.html
  7235. curTang = this._tangents[i];
  7236. prevBinor = this._binormals[i - 1];
  7237. this._normals[i] = Vector3.Cross(prevBinor, curTang);
  7238. if (!this._raw) {
  7239. this._normals[i].normalize();
  7240. }
  7241. this._binormals[i] = Vector3.Cross(curTang, this._normals[i]);
  7242. if (!this._raw) {
  7243. this._binormals[i].normalize();
  7244. }
  7245. }
  7246. };
  7247. // private function getFirstNonNullVector(index)
  7248. // returns the first non null vector from index : curve[index + N].subtract(curve[index])
  7249. Path3D.prototype._getFirstNonNullVector = function (index) {
  7250. var i = 1;
  7251. var nNVector = this._curve[index + i].subtract(this._curve[index]);
  7252. while (nNVector.length() === 0 && index + i + 1 < this._curve.length) {
  7253. i++;
  7254. nNVector = this._curve[index + i].subtract(this._curve[index]);
  7255. }
  7256. return nNVector;
  7257. };
  7258. // private function getLastNonNullVector(index)
  7259. // returns the last non null vector from index : curve[index].subtract(curve[index - N])
  7260. Path3D.prototype._getLastNonNullVector = function (index) {
  7261. var i = 1;
  7262. var nLVector = this._curve[index].subtract(this._curve[index - i]);
  7263. while (nLVector.length() === 0 && index > i + 1) {
  7264. i++;
  7265. nLVector = this._curve[index].subtract(this._curve[index - i]);
  7266. }
  7267. return nLVector;
  7268. };
  7269. // private function normalVector(v0, vt, va) :
  7270. // returns an arbitrary point in the plane defined by the point v0 and the vector vt orthogonal to this plane
  7271. // if va is passed, it returns the va projection on the plane orthogonal to vt at the point v0
  7272. Path3D.prototype._normalVector = function (v0, vt, va) {
  7273. var normal0;
  7274. var tgl = vt.length();
  7275. if (tgl === 0.0) {
  7276. tgl = 1.0;
  7277. }
  7278. if (va === undefined || va === null) {
  7279. var point;
  7280. if (!BABYLON.Scalar.WithinEpsilon(Math.abs(vt.y) / tgl, 1.0, BABYLON.Epsilon)) { // search for a point in the plane
  7281. point = new Vector3(0.0, -1.0, 0.0);
  7282. }
  7283. else if (!BABYLON.Scalar.WithinEpsilon(Math.abs(vt.x) / tgl, 1.0, BABYLON.Epsilon)) {
  7284. point = new Vector3(1.0, 0.0, 0.0);
  7285. }
  7286. else if (!BABYLON.Scalar.WithinEpsilon(Math.abs(vt.z) / tgl, 1.0, BABYLON.Epsilon)) {
  7287. point = new Vector3(0.0, 0.0, 1.0);
  7288. }
  7289. else {
  7290. point = Vector3.Zero();
  7291. }
  7292. normal0 = Vector3.Cross(vt, point);
  7293. }
  7294. else {
  7295. normal0 = Vector3.Cross(vt, va);
  7296. Vector3.CrossToRef(normal0, vt, normal0);
  7297. }
  7298. normal0.normalize();
  7299. return normal0;
  7300. };
  7301. return Path3D;
  7302. }());
  7303. BABYLON.Path3D = Path3D;
  7304. var Curve3 = /** @class */ (function () {
  7305. /**
  7306. * A Curve3 object is a logical object, so not a mesh, to handle curves in the 3D geometric space.
  7307. * A Curve3 is designed from a series of successive Vector3.
  7308. * Tuto : http://doc.babylonjs.com/tutorials/How_to_use_Curve3#curve3-object
  7309. */
  7310. function Curve3(points) {
  7311. this._length = 0.0;
  7312. this._points = points;
  7313. this._length = this._computeLength(points);
  7314. }
  7315. /**
  7316. * Returns a Curve3 object along a Quadratic Bezier curve : http://doc.babylonjs.com/tutorials/How_to_use_Curve3#quadratic-bezier-curve
  7317. * @param v0 (Vector3) the origin point of the Quadratic Bezier
  7318. * @param v1 (Vector3) the control point
  7319. * @param v2 (Vector3) the end point of the Quadratic Bezier
  7320. * @param nbPoints (integer) the wanted number of points in the curve
  7321. */
  7322. Curve3.CreateQuadraticBezier = function (v0, v1, v2, nbPoints) {
  7323. nbPoints = nbPoints > 2 ? nbPoints : 3;
  7324. var bez = new Array();
  7325. var equation = function (t, val0, val1, val2) {
  7326. var res = (1.0 - t) * (1.0 - t) * val0 + 2.0 * t * (1.0 - t) * val1 + t * t * val2;
  7327. return res;
  7328. };
  7329. for (var i = 0; i <= nbPoints; i++) {
  7330. 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)));
  7331. }
  7332. return new Curve3(bez);
  7333. };
  7334. /**
  7335. * Returns a Curve3 object along a Cubic Bezier curve : http://doc.babylonjs.com/tutorials/How_to_use_Curve3#cubic-bezier-curve
  7336. * @param v0 (Vector3) the origin point of the Cubic Bezier
  7337. * @param v1 (Vector3) the first control point
  7338. * @param v2 (Vector3) the second control point
  7339. * @param v3 (Vector3) the end point of the Cubic Bezier
  7340. * @param nbPoints (integer) the wanted number of points in the curve
  7341. */
  7342. Curve3.CreateCubicBezier = function (v0, v1, v2, v3, nbPoints) {
  7343. nbPoints = nbPoints > 3 ? nbPoints : 4;
  7344. var bez = new Array();
  7345. var equation = function (t, val0, val1, val2, val3) {
  7346. 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;
  7347. return res;
  7348. };
  7349. for (var i = 0; i <= nbPoints; i++) {
  7350. 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)));
  7351. }
  7352. return new Curve3(bez);
  7353. };
  7354. /**
  7355. * Returns a Curve3 object along a Hermite Spline curve : http://doc.babylonjs.com/tutorials/How_to_use_Curve3#hermite-spline
  7356. * @param p1 (Vector3) the origin point of the Hermite Spline
  7357. * @param t1 (Vector3) the tangent vector at the origin point
  7358. * @param p2 (Vector3) the end point of the Hermite Spline
  7359. * @param t2 (Vector3) the tangent vector at the end point
  7360. * @param nbPoints (integer) the wanted number of points in the curve
  7361. */
  7362. Curve3.CreateHermiteSpline = function (p1, t1, p2, t2, nbPoints) {
  7363. var hermite = new Array();
  7364. var step = 1.0 / nbPoints;
  7365. for (var i = 0; i <= nbPoints; i++) {
  7366. hermite.push(Vector3.Hermite(p1, t1, p2, t2, i * step));
  7367. }
  7368. return new Curve3(hermite);
  7369. };
  7370. /**
  7371. * Returns a Curve3 object along a CatmullRom Spline curve :
  7372. * @param points (array of Vector3) the points the spline must pass through. At least, four points required.
  7373. * @param nbPoints (integer) the wanted number of points between each curve control points.
  7374. */
  7375. Curve3.CreateCatmullRomSpline = function (points, nbPoints) {
  7376. var totalPoints = new Array();
  7377. totalPoints.push(points[0].clone());
  7378. Array.prototype.push.apply(totalPoints, points);
  7379. totalPoints.push(points[points.length - 1].clone());
  7380. var catmullRom = new Array();
  7381. var step = 1.0 / nbPoints;
  7382. var amount = 0.0;
  7383. for (var i = 0; i < totalPoints.length - 3; i++) {
  7384. amount = 0;
  7385. for (var c = 0; c < nbPoints; c++) {
  7386. catmullRom.push(Vector3.CatmullRom(totalPoints[i], totalPoints[i + 1], totalPoints[i + 2], totalPoints[i + 3], amount));
  7387. amount += step;
  7388. }
  7389. }
  7390. i--;
  7391. catmullRom.push(Vector3.CatmullRom(totalPoints[i], totalPoints[i + 1], totalPoints[i + 2], totalPoints[i + 3], amount));
  7392. return new Curve3(catmullRom);
  7393. };
  7394. /**
  7395. * Returns the Curve3 stored array of successive Vector3
  7396. */
  7397. Curve3.prototype.getPoints = function () {
  7398. return this._points;
  7399. };
  7400. /**
  7401. * Returns the computed length (float) of the curve.
  7402. */
  7403. Curve3.prototype.length = function () {
  7404. return this._length;
  7405. };
  7406. /**
  7407. * Returns a new instance of Curve3 object : var curve = curveA.continue(curveB);
  7408. * This new Curve3 is built by translating and sticking the curveB at the end of the curveA.
  7409. * curveA and curveB keep unchanged.
  7410. */
  7411. Curve3.prototype.continue = function (curve) {
  7412. var lastPoint = this._points[this._points.length - 1];
  7413. var continuedPoints = this._points.slice();
  7414. var curvePoints = curve.getPoints();
  7415. for (var i = 1; i < curvePoints.length; i++) {
  7416. continuedPoints.push(curvePoints[i].subtract(curvePoints[0]).add(lastPoint));
  7417. }
  7418. var continuedCurve = new Curve3(continuedPoints);
  7419. return continuedCurve;
  7420. };
  7421. Curve3.prototype._computeLength = function (path) {
  7422. var l = 0;
  7423. for (var i = 1; i < path.length; i++) {
  7424. l += (path[i].subtract(path[i - 1])).length();
  7425. }
  7426. return l;
  7427. };
  7428. return Curve3;
  7429. }());
  7430. BABYLON.Curve3 = Curve3;
  7431. // Vertex formats
  7432. var PositionNormalVertex = /** @class */ (function () {
  7433. function PositionNormalVertex(position, normal) {
  7434. if (position === void 0) { position = Vector3.Zero(); }
  7435. if (normal === void 0) { normal = Vector3.Up(); }
  7436. this.position = position;
  7437. this.normal = normal;
  7438. }
  7439. PositionNormalVertex.prototype.clone = function () {
  7440. return new PositionNormalVertex(this.position.clone(), this.normal.clone());
  7441. };
  7442. return PositionNormalVertex;
  7443. }());
  7444. BABYLON.PositionNormalVertex = PositionNormalVertex;
  7445. var PositionNormalTextureVertex = /** @class */ (function () {
  7446. function PositionNormalTextureVertex(position, normal, uv) {
  7447. if (position === void 0) { position = Vector3.Zero(); }
  7448. if (normal === void 0) { normal = Vector3.Up(); }
  7449. if (uv === void 0) { uv = Vector2.Zero(); }
  7450. this.position = position;
  7451. this.normal = normal;
  7452. this.uv = uv;
  7453. }
  7454. PositionNormalTextureVertex.prototype.clone = function () {
  7455. return new PositionNormalTextureVertex(this.position.clone(), this.normal.clone(), this.uv.clone());
  7456. };
  7457. return PositionNormalTextureVertex;
  7458. }());
  7459. BABYLON.PositionNormalTextureVertex = PositionNormalTextureVertex;
  7460. // Temporary pre-allocated objects for engine internal use
  7461. // usage in any internal function :
  7462. // var tmp = Tmp.Vector3[0]; <= gets access to the first pre-created Vector3
  7463. // There's a Tmp array per object type : int, float, Vector2, Vector3, Vector4, Quaternion, Matrix
  7464. var Tmp = /** @class */ (function () {
  7465. function Tmp() {
  7466. }
  7467. Tmp.Color3 = [Color3.Black(), Color3.Black(), Color3.Black()];
  7468. Tmp.Vector2 = [Vector2.Zero(), Vector2.Zero(), Vector2.Zero()]; // 3 temp Vector2 at once should be enough
  7469. Tmp.Vector3 = [Vector3.Zero(), Vector3.Zero(), Vector3.Zero(),
  7470. Vector3.Zero(), Vector3.Zero(), Vector3.Zero(), Vector3.Zero(), Vector3.Zero(), Vector3.Zero()]; // 9 temp Vector3 at once should be enough
  7471. Tmp.Vector4 = [Vector4.Zero(), Vector4.Zero(), Vector4.Zero()]; // 3 temp Vector4 at once should be enough
  7472. Tmp.Quaternion = [Quaternion.Zero(), Quaternion.Zero()]; // 2 temp Quaternion at once should be enough
  7473. Tmp.Matrix = [Matrix.Zero(), Matrix.Zero(),
  7474. Matrix.Zero(), Matrix.Zero(),
  7475. Matrix.Zero(), Matrix.Zero(),
  7476. Matrix.Zero(), Matrix.Zero()]; // 6 temp Matrices at once should be enough
  7477. return Tmp;
  7478. }());
  7479. BABYLON.Tmp = Tmp;
  7480. // Same as Tmp but not exported to keep it only for math functions to avoid conflicts
  7481. var MathTmp = /** @class */ (function () {
  7482. function MathTmp() {
  7483. }
  7484. MathTmp.Vector3 = [Vector3.Zero(), Vector3.Zero(), Vector3.Zero(), Vector3.Zero(), Vector3.Zero(), Vector3.Zero()];
  7485. MathTmp.Matrix = [Matrix.Zero(), Matrix.Zero()];
  7486. MathTmp.Quaternion = [Quaternion.Zero(), Quaternion.Zero(), Quaternion.Zero()];
  7487. return MathTmp;
  7488. }());
  7489. })(BABYLON || (BABYLON = {}));
  7490. //# sourceMappingURL=babylon.math.js.map
  7491. var BABYLON;
  7492. (function (BABYLON) {
  7493. var Scalar = /** @class */ (function () {
  7494. function Scalar() {
  7495. }
  7496. /**
  7497. * Boolean : true if the absolute difference between a and b is lower than epsilon (default = 1.401298E-45)
  7498. */
  7499. Scalar.WithinEpsilon = function (a, b, epsilon) {
  7500. if (epsilon === void 0) { epsilon = 1.401298E-45; }
  7501. var num = a - b;
  7502. return -epsilon <= num && num <= epsilon;
  7503. };
  7504. /**
  7505. * Returns a string : the upper case translation of the number i to hexadecimal.
  7506. */
  7507. Scalar.ToHex = function (i) {
  7508. var str = i.toString(16);
  7509. if (i <= 15) {
  7510. return ("0" + str).toUpperCase();
  7511. }
  7512. return str.toUpperCase();
  7513. };
  7514. /**
  7515. * Returns -1 if value is negative and +1 is value is positive.
  7516. * Returns the value itself if it's equal to zero.
  7517. */
  7518. Scalar.Sign = function (value) {
  7519. value = +value; // convert to a number
  7520. if (value === 0 || isNaN(value))
  7521. return value;
  7522. return value > 0 ? 1 : -1;
  7523. };
  7524. /**
  7525. * Returns the value itself if it's between min and max.
  7526. * Returns min if the value is lower than min.
  7527. * Returns max if the value is greater than max.
  7528. */
  7529. Scalar.Clamp = function (value, min, max) {
  7530. if (min === void 0) { min = 0; }
  7531. if (max === void 0) { max = 1; }
  7532. return Math.min(max, Math.max(min, value));
  7533. };
  7534. /**
  7535. * Returns the log2 of value.
  7536. */
  7537. Scalar.Log2 = function (value) {
  7538. return Math.log(value) * Math.LOG2E;
  7539. };
  7540. /**
  7541. * Loops the value, so that it is never larger than length and never smaller than 0.
  7542. *
  7543. * This is similar to the modulo operator but it works with floating point numbers.
  7544. * For example, using 3.0 for t and 2.5 for length, the result would be 0.5.
  7545. * With t = 5 and length = 2.5, the result would be 0.0.
  7546. * Note, however, that the behaviour is not defined for negative numbers as it is for the modulo operator
  7547. */
  7548. Scalar.Repeat = function (value, length) {
  7549. return value - Math.floor(value / length) * length;
  7550. };
  7551. /**
  7552. * Normalize the value between 0.0 and 1.0 using min and max values
  7553. */
  7554. Scalar.Normalize = function (value, min, max) {
  7555. return (value - min) / (max - min);
  7556. };
  7557. /**
  7558. * Denormalize the value from 0.0 and 1.0 using min and max values
  7559. */
  7560. Scalar.Denormalize = function (normalized, min, max) {
  7561. return (normalized * (max - min) + min);
  7562. };
  7563. /**
  7564. * Calculates the shortest difference between two given angles given in degrees.
  7565. */
  7566. Scalar.DeltaAngle = function (current, target) {
  7567. var num = Scalar.Repeat(target - current, 360.0);
  7568. if (num > 180.0) {
  7569. num -= 360.0;
  7570. }
  7571. return num;
  7572. };
  7573. /**
  7574. * PingPongs the value t, so that it is never larger than length and never smaller than 0.
  7575. *
  7576. * The returned value will move back and forth between 0 and length
  7577. */
  7578. Scalar.PingPong = function (tx, length) {
  7579. var t = Scalar.Repeat(tx, length * 2.0);
  7580. return length - Math.abs(t - length);
  7581. };
  7582. /**
  7583. * Interpolates between min and max with smoothing at the limits.
  7584. *
  7585. * This function interpolates between min and max in a similar way to Lerp. However, the interpolation will gradually speed up
  7586. * from the start and slow down toward the end. This is useful for creating natural-looking animation, fading and other transitions.
  7587. */
  7588. Scalar.SmoothStep = function (from, to, tx) {
  7589. var t = Scalar.Clamp(tx);
  7590. t = -2.0 * t * t * t + 3.0 * t * t;
  7591. return to * t + from * (1.0 - t);
  7592. };
  7593. /**
  7594. * Moves a value current towards target.
  7595. *
  7596. * This is essentially the same as Mathf.Lerp but instead the function will ensure that the speed never exceeds maxDelta.
  7597. * Negative values of maxDelta pushes the value away from target.
  7598. */
  7599. Scalar.MoveTowards = function (current, target, maxDelta) {
  7600. var result = 0;
  7601. if (Math.abs(target - current) <= maxDelta) {
  7602. result = target;
  7603. }
  7604. else {
  7605. result = current + Scalar.Sign(target - current) * maxDelta;
  7606. }
  7607. return result;
  7608. };
  7609. /**
  7610. * Same as MoveTowards but makes sure the values interpolate correctly when they wrap around 360 degrees.
  7611. *
  7612. * Variables current and target are assumed to be in degrees. For optimization reasons, negative values of maxDelta
  7613. * are not supported and may cause oscillation. To push current away from a target angle, add 180 to that angle instead.
  7614. */
  7615. Scalar.MoveTowardsAngle = function (current, target, maxDelta) {
  7616. var num = Scalar.DeltaAngle(current, target);
  7617. var result = 0;
  7618. if (-maxDelta < num && num < maxDelta) {
  7619. result = target;
  7620. }
  7621. else {
  7622. target = current + num;
  7623. result = Scalar.MoveTowards(current, target, maxDelta);
  7624. }
  7625. return result;
  7626. };
  7627. /**
  7628. * Creates a new scalar with values linearly interpolated of "amount" between the start scalar and the end scalar.
  7629. */
  7630. Scalar.Lerp = function (start, end, amount) {
  7631. return start + ((end - start) * amount);
  7632. };
  7633. /**
  7634. * Same as Lerp but makes sure the values interpolate correctly when they wrap around 360 degrees.
  7635. * The parameter t is clamped to the range [0, 1]. Variables a and b are assumed to be in degrees.
  7636. */
  7637. Scalar.LerpAngle = function (start, end, amount) {
  7638. var num = Scalar.Repeat(end - start, 360.0);
  7639. if (num > 180.0) {
  7640. num -= 360.0;
  7641. }
  7642. return start + num * Scalar.Clamp(amount);
  7643. };
  7644. /**
  7645. * Calculates the linear parameter t that produces the interpolant value within the range [a, b].
  7646. */
  7647. Scalar.InverseLerp = function (a, b, value) {
  7648. var result = 0;
  7649. if (a != b) {
  7650. result = Scalar.Clamp((value - a) / (b - a));
  7651. }
  7652. else {
  7653. result = 0.0;
  7654. }
  7655. return result;
  7656. };
  7657. /**
  7658. * Returns a new scalar located for "amount" (float) on the Hermite spline defined by the scalars "value1", "value3", "tangent1", "tangent2".
  7659. */
  7660. Scalar.Hermite = function (value1, tangent1, value2, tangent2, amount) {
  7661. var squared = amount * amount;
  7662. var cubed = amount * squared;
  7663. var part1 = ((2.0 * cubed) - (3.0 * squared)) + 1.0;
  7664. var part2 = (-2.0 * cubed) + (3.0 * squared);
  7665. var part3 = (cubed - (2.0 * squared)) + amount;
  7666. var part4 = cubed - squared;
  7667. return (((value1 * part1) + (value2 * part2)) + (tangent1 * part3)) + (tangent2 * part4);
  7668. };
  7669. /**
  7670. * Returns a random float number between and min and max values
  7671. */
  7672. Scalar.RandomRange = function (min, max) {
  7673. if (min === max)
  7674. return min;
  7675. return ((Math.random() * (max - min)) + min);
  7676. };
  7677. /**
  7678. * This function returns percentage of a number in a given range.
  7679. *
  7680. * RangeToPercent(40,20,60) will return 0.5 (50%)
  7681. * RangeToPercent(34,0,100) will return 0.34 (34%)
  7682. */
  7683. Scalar.RangeToPercent = function (number, min, max) {
  7684. return ((number - min) / (max - min));
  7685. };
  7686. /**
  7687. * This function returns number that corresponds to the percentage in a given range.
  7688. *
  7689. * PercentToRange(0.34,0,100) will return 34.
  7690. */
  7691. Scalar.PercentToRange = function (percent, min, max) {
  7692. return ((max - min) * percent + min);
  7693. };
  7694. /**
  7695. * Returns the angle converted to equivalent value between -Math.PI and Math.PI radians.
  7696. * @param angle The angle to normalize in radian.
  7697. * @return The converted angle.
  7698. */
  7699. Scalar.NormalizeRadians = function (angle) {
  7700. // More precise but slower version kept for reference.
  7701. // angle = angle % Tools.TwoPi;
  7702. // angle = (angle + Tools.TwoPi) % Tools.TwoPi;
  7703. //if (angle > Math.PI) {
  7704. // angle -= Tools.TwoPi;
  7705. //}
  7706. angle -= (Scalar.TwoPi * Math.floor((angle + Math.PI) / Scalar.TwoPi));
  7707. return angle;
  7708. };
  7709. /**
  7710. * Two pi constants convenient for computation.
  7711. */
  7712. Scalar.TwoPi = Math.PI * 2;
  7713. return Scalar;
  7714. }());
  7715. BABYLON.Scalar = Scalar;
  7716. })(BABYLON || (BABYLON = {}));
  7717. //# sourceMappingURL=babylon.math.scalar.js.map
  7718. //# sourceMappingURL=babylon.mixins.js.map
  7719. // Type definitions for WebGL 2, Editor's Draft Fri Feb 24 16:10:18 2017 -0800
  7720. // Project: https://www.khronos.org/registry/webgl/specs/latest/2.0/
  7721. // Definitions by: Nico Kemnitz <https://github.com/nkemnitz/>
  7722. // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
  7723. //# sourceMappingURL=babylon.webgl2.js.map
  7724. var BABYLON;
  7725. (function (BABYLON) {
  7726. var __decoratorInitialStore = {};
  7727. var __mergedStore = {};
  7728. var _copySource = function (creationFunction, source, instanciate) {
  7729. var destination = creationFunction();
  7730. // Tags
  7731. if (BABYLON.Tags) {
  7732. BABYLON.Tags.AddTagsTo(destination, source.tags);
  7733. }
  7734. var classStore = getMergedStore(destination);
  7735. // Properties
  7736. for (var property in classStore) {
  7737. var propertyDescriptor = classStore[property];
  7738. var sourceProperty = source[property];
  7739. var propertyType = propertyDescriptor.type;
  7740. if (sourceProperty !== undefined && sourceProperty !== null) {
  7741. switch (propertyType) {
  7742. case 0: // Value
  7743. case 6: // Mesh reference
  7744. case 11: // Camera reference
  7745. destination[property] = sourceProperty;
  7746. break;
  7747. case 1: // Texture
  7748. destination[property] = (instanciate || sourceProperty.isRenderTarget) ? sourceProperty : sourceProperty.clone();
  7749. break;
  7750. case 2: // Color3
  7751. case 3: // FresnelParameters
  7752. case 4: // Vector2
  7753. case 5: // Vector3
  7754. case 7: // Color Curves
  7755. case 10: // Quaternion
  7756. destination[property] = instanciate ? sourceProperty : sourceProperty.clone();
  7757. break;
  7758. }
  7759. }
  7760. }
  7761. return destination;
  7762. };
  7763. function getDirectStore(target) {
  7764. var classKey = target.getClassName();
  7765. if (!__decoratorInitialStore[classKey]) {
  7766. __decoratorInitialStore[classKey] = {};
  7767. }
  7768. return __decoratorInitialStore[classKey];
  7769. }
  7770. /**
  7771. * Return the list of properties flagged as serializable
  7772. * @param target: host object
  7773. */
  7774. function getMergedStore(target) {
  7775. var classKey = target.getClassName();
  7776. if (__mergedStore[classKey]) {
  7777. return __mergedStore[classKey];
  7778. }
  7779. __mergedStore[classKey] = {};
  7780. var store = __mergedStore[classKey];
  7781. var currentTarget = target;
  7782. var currentKey = classKey;
  7783. while (currentKey) {
  7784. var initialStore = __decoratorInitialStore[currentKey];
  7785. for (var property in initialStore) {
  7786. store[property] = initialStore[property];
  7787. }
  7788. var parent_1 = void 0;
  7789. var done = false;
  7790. do {
  7791. parent_1 = Object.getPrototypeOf(currentTarget);
  7792. if (!parent_1.getClassName) {
  7793. done = true;
  7794. break;
  7795. }
  7796. if (parent_1.getClassName() !== currentKey) {
  7797. break;
  7798. }
  7799. currentTarget = parent_1;
  7800. } while (parent_1);
  7801. if (done) {
  7802. break;
  7803. }
  7804. currentKey = parent_1.getClassName();
  7805. currentTarget = parent_1;
  7806. }
  7807. return store;
  7808. }
  7809. function generateSerializableMember(type, sourceName) {
  7810. return function (target, propertyKey) {
  7811. var classStore = getDirectStore(target);
  7812. if (!classStore[propertyKey]) {
  7813. classStore[propertyKey] = { type: type, sourceName: sourceName };
  7814. }
  7815. };
  7816. }
  7817. function generateExpandMember(setCallback, targetKey) {
  7818. if (targetKey === void 0) { targetKey = null; }
  7819. return function (target, propertyKey) {
  7820. var key = targetKey || ("_" + propertyKey);
  7821. Object.defineProperty(target, propertyKey, {
  7822. get: function () {
  7823. return this[key];
  7824. },
  7825. set: function (value) {
  7826. if (this[key] === value) {
  7827. return;
  7828. }
  7829. this[key] = value;
  7830. target[setCallback].apply(this);
  7831. },
  7832. enumerable: true,
  7833. configurable: true
  7834. });
  7835. };
  7836. }
  7837. function expandToProperty(callback, targetKey) {
  7838. if (targetKey === void 0) { targetKey = null; }
  7839. return generateExpandMember(callback, targetKey);
  7840. }
  7841. BABYLON.expandToProperty = expandToProperty;
  7842. function serialize(sourceName) {
  7843. return generateSerializableMember(0, sourceName); // value member
  7844. }
  7845. BABYLON.serialize = serialize;
  7846. function serializeAsTexture(sourceName) {
  7847. return generateSerializableMember(1, sourceName); // texture member
  7848. }
  7849. BABYLON.serializeAsTexture = serializeAsTexture;
  7850. function serializeAsColor3(sourceName) {
  7851. return generateSerializableMember(2, sourceName); // color3 member
  7852. }
  7853. BABYLON.serializeAsColor3 = serializeAsColor3;
  7854. function serializeAsFresnelParameters(sourceName) {
  7855. return generateSerializableMember(3, sourceName); // fresnel parameters member
  7856. }
  7857. BABYLON.serializeAsFresnelParameters = serializeAsFresnelParameters;
  7858. function serializeAsVector2(sourceName) {
  7859. return generateSerializableMember(4, sourceName); // vector2 member
  7860. }
  7861. BABYLON.serializeAsVector2 = serializeAsVector2;
  7862. function serializeAsVector3(sourceName) {
  7863. return generateSerializableMember(5, sourceName); // vector3 member
  7864. }
  7865. BABYLON.serializeAsVector3 = serializeAsVector3;
  7866. function serializeAsMeshReference(sourceName) {
  7867. return generateSerializableMember(6, sourceName); // mesh reference member
  7868. }
  7869. BABYLON.serializeAsMeshReference = serializeAsMeshReference;
  7870. function serializeAsColorCurves(sourceName) {
  7871. return generateSerializableMember(7, sourceName); // color curves
  7872. }
  7873. BABYLON.serializeAsColorCurves = serializeAsColorCurves;
  7874. function serializeAsColor4(sourceName) {
  7875. return generateSerializableMember(8, sourceName); // color 4
  7876. }
  7877. BABYLON.serializeAsColor4 = serializeAsColor4;
  7878. function serializeAsImageProcessingConfiguration(sourceName) {
  7879. return generateSerializableMember(9, sourceName); // image processing
  7880. }
  7881. BABYLON.serializeAsImageProcessingConfiguration = serializeAsImageProcessingConfiguration;
  7882. function serializeAsQuaternion(sourceName) {
  7883. return generateSerializableMember(10, sourceName); // quaternion member
  7884. }
  7885. BABYLON.serializeAsQuaternion = serializeAsQuaternion;
  7886. /**
  7887. * Decorator used to define property that can be serialized as reference to a camera
  7888. * @param sourceName defines the name of the property to decorate
  7889. */
  7890. function serializeAsCameraReference(sourceName) {
  7891. return generateSerializableMember(11, sourceName); // camera reference member
  7892. }
  7893. BABYLON.serializeAsCameraReference = serializeAsCameraReference;
  7894. var SerializationHelper = /** @class */ (function () {
  7895. function SerializationHelper() {
  7896. }
  7897. SerializationHelper.Serialize = function (entity, serializationObject) {
  7898. if (!serializationObject) {
  7899. serializationObject = {};
  7900. }
  7901. // Tags
  7902. if (BABYLON.Tags) {
  7903. serializationObject.tags = BABYLON.Tags.GetTags(entity);
  7904. }
  7905. var serializedProperties = getMergedStore(entity);
  7906. // Properties
  7907. for (var property in serializedProperties) {
  7908. var propertyDescriptor = serializedProperties[property];
  7909. var targetPropertyName = propertyDescriptor.sourceName || property;
  7910. var propertyType = propertyDescriptor.type;
  7911. var sourceProperty = entity[property];
  7912. if (sourceProperty !== undefined && sourceProperty !== null) {
  7913. switch (propertyType) {
  7914. case 0: // Value
  7915. serializationObject[targetPropertyName] = sourceProperty;
  7916. break;
  7917. case 1: // Texture
  7918. serializationObject[targetPropertyName] = sourceProperty.serialize();
  7919. break;
  7920. case 2: // Color3
  7921. serializationObject[targetPropertyName] = sourceProperty.asArray();
  7922. break;
  7923. case 3: // FresnelParameters
  7924. serializationObject[targetPropertyName] = sourceProperty.serialize();
  7925. break;
  7926. case 4: // Vector2
  7927. serializationObject[targetPropertyName] = sourceProperty.asArray();
  7928. break;
  7929. case 5: // Vector3
  7930. serializationObject[targetPropertyName] = sourceProperty.asArray();
  7931. break;
  7932. case 6: // Mesh reference
  7933. serializationObject[targetPropertyName] = sourceProperty.id;
  7934. break;
  7935. case 7: // Color Curves
  7936. serializationObject[targetPropertyName] = sourceProperty.serialize();
  7937. break;
  7938. case 8: // Color 4
  7939. serializationObject[targetPropertyName] = sourceProperty.asArray();
  7940. break;
  7941. case 9: // Image Processing
  7942. serializationObject[targetPropertyName] = sourceProperty.serialize();
  7943. break;
  7944. case 10: // Quaternion
  7945. serializationObject[targetPropertyName] = sourceProperty.asArray();
  7946. break;
  7947. case 11: // Camera reference
  7948. serializationObject[targetPropertyName] = sourceProperty.id;
  7949. break;
  7950. }
  7951. }
  7952. }
  7953. return serializationObject;
  7954. };
  7955. SerializationHelper.Parse = function (creationFunction, source, scene, rootUrl) {
  7956. if (rootUrl === void 0) { rootUrl = null; }
  7957. var destination = creationFunction();
  7958. if (!rootUrl) {
  7959. rootUrl = "";
  7960. }
  7961. // Tags
  7962. if (BABYLON.Tags) {
  7963. BABYLON.Tags.AddTagsTo(destination, source.tags);
  7964. }
  7965. var classStore = getMergedStore(destination);
  7966. // Properties
  7967. for (var property in classStore) {
  7968. var propertyDescriptor = classStore[property];
  7969. var sourceProperty = source[propertyDescriptor.sourceName || property];
  7970. var propertyType = propertyDescriptor.type;
  7971. if (sourceProperty !== undefined && sourceProperty !== null) {
  7972. var dest = destination;
  7973. switch (propertyType) {
  7974. case 0: // Value
  7975. dest[property] = sourceProperty;
  7976. break;
  7977. case 1: // Texture
  7978. if (scene) {
  7979. dest[property] = BABYLON.Texture.Parse(sourceProperty, scene, rootUrl);
  7980. }
  7981. break;
  7982. case 2: // Color3
  7983. dest[property] = BABYLON.Color3.FromArray(sourceProperty);
  7984. break;
  7985. case 3: // FresnelParameters
  7986. dest[property] = BABYLON.FresnelParameters.Parse(sourceProperty);
  7987. break;
  7988. case 4: // Vector2
  7989. dest[property] = BABYLON.Vector2.FromArray(sourceProperty);
  7990. break;
  7991. case 5: // Vector3
  7992. dest[property] = BABYLON.Vector3.FromArray(sourceProperty);
  7993. break;
  7994. case 6: // Mesh reference
  7995. if (scene) {
  7996. dest[property] = scene.getLastMeshByID(sourceProperty);
  7997. }
  7998. break;
  7999. case 7: // Color Curves
  8000. dest[property] = BABYLON.ColorCurves.Parse(sourceProperty);
  8001. break;
  8002. case 8: // Color 4
  8003. dest[property] = BABYLON.Color4.FromArray(sourceProperty);
  8004. break;
  8005. case 9: // Image Processing
  8006. dest[property] = BABYLON.ImageProcessingConfiguration.Parse(sourceProperty);
  8007. break;
  8008. case 10: // Quaternion
  8009. dest[property] = BABYLON.Quaternion.FromArray(sourceProperty);
  8010. break;
  8011. case 11: // Camera reference
  8012. if (scene) {
  8013. dest[property] = scene.getCameraByID(sourceProperty);
  8014. }
  8015. break;
  8016. }
  8017. }
  8018. }
  8019. return destination;
  8020. };
  8021. SerializationHelper.Clone = function (creationFunction, source) {
  8022. return _copySource(creationFunction, source, false);
  8023. };
  8024. SerializationHelper.Instanciate = function (creationFunction, source) {
  8025. return _copySource(creationFunction, source, true);
  8026. };
  8027. return SerializationHelper;
  8028. }());
  8029. BABYLON.SerializationHelper = SerializationHelper;
  8030. })(BABYLON || (BABYLON = {}));
  8031. //# sourceMappingURL=babylon.decorators.js.map
  8032. var BABYLON;
  8033. (function (BABYLON) {
  8034. /**
  8035. * Wrapper class for promise with external resolve and reject.
  8036. */
  8037. var Deferred = /** @class */ (function () {
  8038. /**
  8039. * Constructor for this deferred object.
  8040. */
  8041. function Deferred() {
  8042. var _this = this;
  8043. this.promise = new Promise(function (resolve, reject) {
  8044. _this._resolve = resolve;
  8045. _this._reject = reject;
  8046. });
  8047. }
  8048. Object.defineProperty(Deferred.prototype, "resolve", {
  8049. /**
  8050. * The resolve method of the promise associated with this deferred object.
  8051. */
  8052. get: function () {
  8053. return this._resolve;
  8054. },
  8055. enumerable: true,
  8056. configurable: true
  8057. });
  8058. Object.defineProperty(Deferred.prototype, "reject", {
  8059. /**
  8060. * The reject method of the promise associated with this deferred object.
  8061. */
  8062. get: function () {
  8063. return this._reject;
  8064. },
  8065. enumerable: true,
  8066. configurable: true
  8067. });
  8068. return Deferred;
  8069. }());
  8070. BABYLON.Deferred = Deferred;
  8071. })(BABYLON || (BABYLON = {}));
  8072. //# sourceMappingURL=babylon.deferred.js.map
  8073. var BABYLON;
  8074. (function (BABYLON) {
  8075. /**
  8076. * A class serves as a medium between the observable and its observers
  8077. */
  8078. var EventState = /** @class */ (function () {
  8079. /**
  8080. * Create a new EventState
  8081. * @param mask defines the mask associated with this state
  8082. * @param skipNextObservers defines a flag which will instruct the observable to skip following observers when set to true
  8083. * @param target defines the original target of the state
  8084. * @param currentTarget defines the current target of the state
  8085. */
  8086. function EventState(mask, skipNextObservers, target, currentTarget) {
  8087. if (skipNextObservers === void 0) { skipNextObservers = false; }
  8088. this.initalize(mask, skipNextObservers, target, currentTarget);
  8089. }
  8090. /**
  8091. * Initialize the current event state
  8092. * @param mask defines the mask associated with this state
  8093. * @param skipNextObservers defines a flag which will instruct the observable to skip following observers when set to true
  8094. * @param target defines the original target of the state
  8095. * @param currentTarget defines the current target of the state
  8096. * @returns the current event state
  8097. */
  8098. EventState.prototype.initalize = function (mask, skipNextObservers, target, currentTarget) {
  8099. if (skipNextObservers === void 0) { skipNextObservers = false; }
  8100. this.mask = mask;
  8101. this.skipNextObservers = skipNextObservers;
  8102. this.target = target;
  8103. this.currentTarget = currentTarget;
  8104. return this;
  8105. };
  8106. return EventState;
  8107. }());
  8108. BABYLON.EventState = EventState;
  8109. /**
  8110. * Represent an Observer registered to a given Observable object.
  8111. */
  8112. var Observer = /** @class */ (function () {
  8113. /**
  8114. * Creates a new observer
  8115. * @param callback defines the callback to call when the observer is notified
  8116. * @param mask defines the mask of the observer (used to filter notifications)
  8117. * @param scope defines the current scope used to restore the JS context
  8118. */
  8119. function Observer(
  8120. /**
  8121. * Defines the callback to call when the observer is notified
  8122. */
  8123. callback,
  8124. /**
  8125. * Defines the mask of the observer (used to filter notifications)
  8126. */
  8127. mask,
  8128. /**
  8129. * Defines the current scope used to restore the JS context
  8130. */
  8131. scope) {
  8132. if (scope === void 0) { scope = null; }
  8133. this.callback = callback;
  8134. this.mask = mask;
  8135. this.scope = scope;
  8136. /** @hidden */
  8137. this._willBeUnregistered = false;
  8138. /**
  8139. * Gets or sets a property defining that the observer as to be unregistered after the next notification
  8140. */
  8141. this.unregisterOnNextCall = false;
  8142. }
  8143. return Observer;
  8144. }());
  8145. BABYLON.Observer = Observer;
  8146. /**
  8147. * Represent a list of observers registered to multiple Observables object.
  8148. */
  8149. var MultiObserver = /** @class */ (function () {
  8150. function MultiObserver() {
  8151. }
  8152. /**
  8153. * Release associated resources
  8154. */
  8155. MultiObserver.prototype.dispose = function () {
  8156. if (this._observers && this._observables) {
  8157. for (var index = 0; index < this._observers.length; index++) {
  8158. this._observables[index].remove(this._observers[index]);
  8159. }
  8160. }
  8161. this._observers = null;
  8162. this._observables = null;
  8163. };
  8164. /**
  8165. * Raise a callback when one of the observable will notify
  8166. * @param observables defines a list of observables to watch
  8167. * @param callback defines the callback to call on notification
  8168. * @param mask defines the mask used to filter notifications
  8169. * @param scope defines the current scope used to restore the JS context
  8170. * @returns the new MultiObserver
  8171. */
  8172. MultiObserver.Watch = function (observables, callback, mask, scope) {
  8173. if (mask === void 0) { mask = -1; }
  8174. if (scope === void 0) { scope = null; }
  8175. var result = new MultiObserver();
  8176. result._observers = new Array();
  8177. result._observables = observables;
  8178. for (var _i = 0, observables_1 = observables; _i < observables_1.length; _i++) {
  8179. var observable = observables_1[_i];
  8180. var observer = observable.add(callback, mask, false, scope);
  8181. if (observer) {
  8182. result._observers.push(observer);
  8183. }
  8184. }
  8185. return result;
  8186. };
  8187. return MultiObserver;
  8188. }());
  8189. BABYLON.MultiObserver = MultiObserver;
  8190. /**
  8191. * The Observable class is a simple implementation of the Observable pattern.
  8192. *
  8193. * 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.
  8194. * This enable a more fine grained execution without having to rely on multiple different Observable objects.
  8195. * 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).
  8196. * 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.
  8197. */
  8198. var Observable = /** @class */ (function () {
  8199. /**
  8200. * Creates a new observable
  8201. * @param onObserverAdded defines a callback to call when a new observer is added
  8202. */
  8203. function Observable(onObserverAdded) {
  8204. this._observers = new Array();
  8205. this._eventState = new EventState(0);
  8206. if (onObserverAdded) {
  8207. this._onObserverAdded = onObserverAdded;
  8208. }
  8209. }
  8210. /**
  8211. * Create a new Observer with the specified callback
  8212. * @param callback the callback that will be executed for that Observer
  8213. * @param mask the mask used to filter observers
  8214. * @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.
  8215. * @param scope optional scope for the callback to be called from
  8216. * @param unregisterOnFirstCall defines if the observer as to be unregistered after the next notification
  8217. * @returns the new observer created for the callback
  8218. */
  8219. Observable.prototype.add = function (callback, mask, insertFirst, scope, unregisterOnFirstCall) {
  8220. if (mask === void 0) { mask = -1; }
  8221. if (insertFirst === void 0) { insertFirst = false; }
  8222. if (scope === void 0) { scope = null; }
  8223. if (unregisterOnFirstCall === void 0) { unregisterOnFirstCall = false; }
  8224. if (!callback) {
  8225. return null;
  8226. }
  8227. var observer = new Observer(callback, mask, scope);
  8228. observer.unregisterOnNextCall = unregisterOnFirstCall;
  8229. if (insertFirst) {
  8230. this._observers.unshift(observer);
  8231. }
  8232. else {
  8233. this._observers.push(observer);
  8234. }
  8235. if (this._onObserverAdded) {
  8236. this._onObserverAdded(observer);
  8237. }
  8238. return observer;
  8239. };
  8240. /**
  8241. * Remove an Observer from the Observable object
  8242. * @param observer the instance of the Observer to remove
  8243. * @returns false if it doesn't belong to this Observable
  8244. */
  8245. Observable.prototype.remove = function (observer) {
  8246. if (!observer) {
  8247. return false;
  8248. }
  8249. var index = this._observers.indexOf(observer);
  8250. if (index !== -1) {
  8251. this._observers.splice(index, 1);
  8252. return true;
  8253. }
  8254. return false;
  8255. };
  8256. /**
  8257. * Remove a callback from the Observable object
  8258. * @param callback the callback to remove
  8259. * @param scope optional scope. If used only the callbacks with this scope will be removed
  8260. * @returns false if it doesn't belong to this Observable
  8261. */
  8262. Observable.prototype.removeCallback = function (callback, scope) {
  8263. for (var index = 0; index < this._observers.length; index++) {
  8264. if (this._observers[index].callback === callback && (!scope || scope === this._observers[index].scope)) {
  8265. this._observers.splice(index, 1);
  8266. return true;
  8267. }
  8268. }
  8269. return false;
  8270. };
  8271. Observable.prototype._deferUnregister = function (observer) {
  8272. var _this = this;
  8273. observer.unregisterOnNextCall = false;
  8274. observer._willBeUnregistered = true;
  8275. BABYLON.Tools.SetImmediate(function () {
  8276. _this.remove(observer);
  8277. });
  8278. };
  8279. /**
  8280. * Notify all Observers by calling their respective callback with the given data
  8281. * Will return true if all observers were executed, false if an observer set skipNextObservers to true, then prevent the subsequent ones to execute
  8282. * @param eventData defines the data to send to all observers
  8283. * @param mask defines the mask of the current notification (observers with incompatible mask (ie mask & observer.mask === 0) will not be notified)
  8284. * @param target defines the original target of the state
  8285. * @param currentTarget defines the current target of the state
  8286. * @returns false if the complete observer chain was not processed (because one observer set the skipNextObservers to true)
  8287. */
  8288. Observable.prototype.notifyObservers = function (eventData, mask, target, currentTarget) {
  8289. if (mask === void 0) { mask = -1; }
  8290. if (!this._observers.length) {
  8291. return true;
  8292. }
  8293. var state = this._eventState;
  8294. state.mask = mask;
  8295. state.target = target;
  8296. state.currentTarget = currentTarget;
  8297. state.skipNextObservers = false;
  8298. state.lastReturnValue = eventData;
  8299. for (var _i = 0, _a = this._observers; _i < _a.length; _i++) {
  8300. var obs = _a[_i];
  8301. if (obs._willBeUnregistered) {
  8302. continue;
  8303. }
  8304. if (obs.mask & mask) {
  8305. if (obs.scope) {
  8306. state.lastReturnValue = obs.callback.apply(obs.scope, [eventData, state]);
  8307. }
  8308. else {
  8309. state.lastReturnValue = obs.callback(eventData, state);
  8310. }
  8311. if (obs.unregisterOnNextCall) {
  8312. this._deferUnregister(obs);
  8313. }
  8314. }
  8315. if (state.skipNextObservers) {
  8316. return false;
  8317. }
  8318. }
  8319. return true;
  8320. };
  8321. /**
  8322. * Calling this will execute each callback, expecting it to be a promise or return a value.
  8323. * If at any point in the chain one function fails, the promise will fail and the execution will not continue.
  8324. * This is useful when a chain of events (sometimes async events) is needed to initialize a certain object
  8325. * and it is crucial that all callbacks will be executed.
  8326. * The order of the callbacks is kept, callbacks are not executed parallel.
  8327. *
  8328. * @param eventData The data to be sent to each callback
  8329. * @param mask is used to filter observers defaults to -1
  8330. * @param target defines the callback target (see EventState)
  8331. * @param currentTarget defines he current object in the bubbling phase
  8332. * @returns {Promise<T>} will return a Promise than resolves when all callbacks executed successfully.
  8333. */
  8334. Observable.prototype.notifyObserversWithPromise = function (eventData, mask, target, currentTarget) {
  8335. var _this = this;
  8336. if (mask === void 0) { mask = -1; }
  8337. // create an empty promise
  8338. var p = Promise.resolve(eventData);
  8339. // no observers? return this promise.
  8340. if (!this._observers.length) {
  8341. return p;
  8342. }
  8343. var state = this._eventState;
  8344. state.mask = mask;
  8345. state.target = target;
  8346. state.currentTarget = currentTarget;
  8347. state.skipNextObservers = false;
  8348. // execute one callback after another (not using Promise.all, the order is important)
  8349. this._observers.forEach(function (obs) {
  8350. if (state.skipNextObservers) {
  8351. return;
  8352. }
  8353. if (obs._willBeUnregistered) {
  8354. return;
  8355. }
  8356. if (obs.mask & mask) {
  8357. if (obs.scope) {
  8358. p = p.then(function (lastReturnedValue) {
  8359. state.lastReturnValue = lastReturnedValue;
  8360. return obs.callback.apply(obs.scope, [eventData, state]);
  8361. });
  8362. }
  8363. else {
  8364. p = p.then(function (lastReturnedValue) {
  8365. state.lastReturnValue = lastReturnedValue;
  8366. return obs.callback(eventData, state);
  8367. });
  8368. }
  8369. if (obs.unregisterOnNextCall) {
  8370. _this._deferUnregister(obs);
  8371. }
  8372. }
  8373. });
  8374. // return the eventData
  8375. return p.then(function () { return eventData; });
  8376. };
  8377. /**
  8378. * Notify a specific observer
  8379. * @param observer defines the observer to notify
  8380. * @param eventData defines the data to be sent to each callback
  8381. * @param mask is used to filter observers defaults to -1
  8382. */
  8383. Observable.prototype.notifyObserver = function (observer, eventData, mask) {
  8384. if (mask === void 0) { mask = -1; }
  8385. var state = this._eventState;
  8386. state.mask = mask;
  8387. state.skipNextObservers = false;
  8388. observer.callback(eventData, state);
  8389. };
  8390. /**
  8391. * Gets a boolean indicating if the observable has at least one observer
  8392. * @returns true is the Observable has at least one Observer registered
  8393. */
  8394. Observable.prototype.hasObservers = function () {
  8395. return this._observers.length > 0;
  8396. };
  8397. /**
  8398. * Clear the list of observers
  8399. */
  8400. Observable.prototype.clear = function () {
  8401. this._observers = new Array();
  8402. this._onObserverAdded = null;
  8403. };
  8404. /**
  8405. * Clone the current observable
  8406. * @returns a new observable
  8407. */
  8408. Observable.prototype.clone = function () {
  8409. var result = new Observable();
  8410. result._observers = this._observers.slice(0);
  8411. return result;
  8412. };
  8413. /**
  8414. * Does this observable handles observer registered with a given mask
  8415. * @param mask defines the mask to be tested
  8416. * @return whether or not one observer registered with the given mask is handeled
  8417. **/
  8418. Observable.prototype.hasSpecificMask = function (mask) {
  8419. if (mask === void 0) { mask = -1; }
  8420. for (var _i = 0, _a = this._observers; _i < _a.length; _i++) {
  8421. var obs = _a[_i];
  8422. if (obs.mask & mask || obs.mask === mask) {
  8423. return true;
  8424. }
  8425. }
  8426. return false;
  8427. };
  8428. return Observable;
  8429. }());
  8430. BABYLON.Observable = Observable;
  8431. })(BABYLON || (BABYLON = {}));
  8432. //# sourceMappingURL=babylon.observable.js.map
  8433. var BABYLON;
  8434. (function (BABYLON) {
  8435. var SmartArray = /** @class */ (function () {
  8436. function SmartArray(capacity) {
  8437. this.length = 0;
  8438. this.data = new Array(capacity);
  8439. this._id = SmartArray._GlobalId++;
  8440. }
  8441. SmartArray.prototype.push = function (value) {
  8442. this.data[this.length++] = value;
  8443. if (this.length > this.data.length) {
  8444. this.data.length *= 2;
  8445. }
  8446. };
  8447. SmartArray.prototype.forEach = function (func) {
  8448. for (var index = 0; index < this.length; index++) {
  8449. func(this.data[index]);
  8450. }
  8451. };
  8452. SmartArray.prototype.sort = function (compareFn) {
  8453. this.data.sort(compareFn);
  8454. };
  8455. SmartArray.prototype.reset = function () {
  8456. this.length = 0;
  8457. };
  8458. SmartArray.prototype.dispose = function () {
  8459. this.reset();
  8460. if (this.data) {
  8461. this.data.length = 0;
  8462. this.data = [];
  8463. }
  8464. };
  8465. SmartArray.prototype.concat = function (array) {
  8466. if (array.length === 0) {
  8467. return;
  8468. }
  8469. if (this.length + array.length > this.data.length) {
  8470. this.data.length = (this.length + array.length) * 2;
  8471. }
  8472. for (var index = 0; index < array.length; index++) {
  8473. this.data[this.length++] = (array.data || array)[index];
  8474. }
  8475. };
  8476. SmartArray.prototype.indexOf = function (value) {
  8477. var position = this.data.indexOf(value);
  8478. if (position >= this.length) {
  8479. return -1;
  8480. }
  8481. return position;
  8482. };
  8483. SmartArray.prototype.contains = function (value) {
  8484. return this.data.indexOf(value) !== -1;
  8485. };
  8486. // Statics
  8487. SmartArray._GlobalId = 0;
  8488. return SmartArray;
  8489. }());
  8490. BABYLON.SmartArray = SmartArray;
  8491. var SmartArrayNoDuplicate = /** @class */ (function (_super) {
  8492. __extends(SmartArrayNoDuplicate, _super);
  8493. function SmartArrayNoDuplicate() {
  8494. var _this = _super !== null && _super.apply(this, arguments) || this;
  8495. _this._duplicateId = 0;
  8496. return _this;
  8497. }
  8498. SmartArrayNoDuplicate.prototype.push = function (value) {
  8499. _super.prototype.push.call(this, value);
  8500. if (!value.__smartArrayFlags) {
  8501. value.__smartArrayFlags = {};
  8502. }
  8503. value.__smartArrayFlags[this._id] = this._duplicateId;
  8504. };
  8505. SmartArrayNoDuplicate.prototype.pushNoDuplicate = function (value) {
  8506. if (value.__smartArrayFlags && value.__smartArrayFlags[this._id] === this._duplicateId) {
  8507. return false;
  8508. }
  8509. this.push(value);
  8510. return true;
  8511. };
  8512. SmartArrayNoDuplicate.prototype.reset = function () {
  8513. _super.prototype.reset.call(this);
  8514. this._duplicateId++;
  8515. };
  8516. SmartArrayNoDuplicate.prototype.concatWithNoDuplicate = function (array) {
  8517. if (array.length === 0) {
  8518. return;
  8519. }
  8520. if (this.length + array.length > this.data.length) {
  8521. this.data.length = (this.length + array.length) * 2;
  8522. }
  8523. for (var index = 0; index < array.length; index++) {
  8524. var item = (array.data || array)[index];
  8525. this.pushNoDuplicate(item);
  8526. }
  8527. };
  8528. return SmartArrayNoDuplicate;
  8529. }(SmartArray));
  8530. BABYLON.SmartArrayNoDuplicate = SmartArrayNoDuplicate;
  8531. })(BABYLON || (BABYLON = {}));
  8532. //# sourceMappingURL=babylon.smartArray.js.map
  8533. var BABYLON;
  8534. (function (BABYLON) {
  8535. // See https://stackoverflow.com/questions/12915412/how-do-i-extend-a-host-object-e-g-error-in-typescript
  8536. // and https://github.com/Microsoft/TypeScript/wiki/Breaking-Changes#extending-built-ins-like-error-array-and-map-may-no-longer-work
  8537. var LoadFileError = /** @class */ (function (_super) {
  8538. __extends(LoadFileError, _super);
  8539. function LoadFileError(message, request) {
  8540. var _this = _super.call(this, message) || this;
  8541. _this.request = request;
  8542. _this.name = "LoadFileError";
  8543. LoadFileError._setPrototypeOf(_this, LoadFileError.prototype);
  8544. return _this;
  8545. }
  8546. // Polyfill for Object.setPrototypeOf if necessary.
  8547. LoadFileError._setPrototypeOf = Object.setPrototypeOf || (function (o, proto) { o.__proto__ = proto; return o; });
  8548. return LoadFileError;
  8549. }(Error));
  8550. BABYLON.LoadFileError = LoadFileError;
  8551. var RetryStrategy = /** @class */ (function () {
  8552. function RetryStrategy() {
  8553. }
  8554. RetryStrategy.ExponentialBackoff = function (maxRetries, baseInterval) {
  8555. if (maxRetries === void 0) { maxRetries = 3; }
  8556. if (baseInterval === void 0) { baseInterval = 500; }
  8557. return function (url, request, retryIndex) {
  8558. if (request.status !== 0 || retryIndex >= maxRetries || url.indexOf("file:") !== -1) {
  8559. return -1;
  8560. }
  8561. return Math.pow(2, retryIndex) * baseInterval;
  8562. };
  8563. };
  8564. return RetryStrategy;
  8565. }());
  8566. BABYLON.RetryStrategy = RetryStrategy;
  8567. // Screenshots
  8568. var screenshotCanvas;
  8569. var cloneValue = function (source, destinationObject) {
  8570. if (!source)
  8571. return null;
  8572. if (source instanceof BABYLON.Mesh) {
  8573. return null;
  8574. }
  8575. if (source instanceof BABYLON.SubMesh) {
  8576. return source.clone(destinationObject);
  8577. }
  8578. else if (source.clone) {
  8579. return source.clone();
  8580. }
  8581. return null;
  8582. };
  8583. var Tools = /** @class */ (function () {
  8584. function Tools() {
  8585. }
  8586. /**
  8587. * Interpolates between a and b via alpha
  8588. * @param a The lower value (returned when alpha = 0)
  8589. * @param b The upper value (returned when alpha = 1)
  8590. * @param alpha The interpolation-factor
  8591. * @return The mixed value
  8592. */
  8593. Tools.Mix = function (a, b, alpha) {
  8594. return a * (1 - alpha) + b * alpha;
  8595. };
  8596. Tools.Instantiate = function (className) {
  8597. if (Tools.RegisteredExternalClasses && Tools.RegisteredExternalClasses[className]) {
  8598. return Tools.RegisteredExternalClasses[className];
  8599. }
  8600. var arr = className.split(".");
  8601. var fn = (window || this);
  8602. for (var i = 0, len = arr.length; i < len; i++) {
  8603. fn = fn[arr[i]];
  8604. }
  8605. if (typeof fn !== "function") {
  8606. return null;
  8607. }
  8608. return fn;
  8609. };
  8610. /**
  8611. * Provides a slice function that will work even on IE
  8612. * @param data defines the array to slice
  8613. * @param start defines the start of the data (optional)
  8614. * @param end defines the end of the data (optional)
  8615. * @returns the new sliced array
  8616. */
  8617. Tools.Slice = function (data, start, end) {
  8618. if (data.slice) {
  8619. return data.slice(start, end);
  8620. }
  8621. return Array.prototype.slice.call(data, start, end);
  8622. };
  8623. Tools.SetImmediate = function (action) {
  8624. if (window.setImmediate) {
  8625. window.setImmediate(action);
  8626. }
  8627. else {
  8628. setTimeout(action, 1);
  8629. }
  8630. };
  8631. Tools.IsExponentOfTwo = function (value) {
  8632. var count = 1;
  8633. do {
  8634. count *= 2;
  8635. } while (count < value);
  8636. return count === value;
  8637. };
  8638. /**
  8639. * Returns the nearest 32-bit single precision float representation of a Number
  8640. * @param value A Number. If the parameter is of a different type, it will get converted
  8641. * to a number or to NaN if it cannot be converted
  8642. * @returns number
  8643. */
  8644. Tools.FloatRound = function (value) {
  8645. if (Math.fround) {
  8646. return Math.fround(value);
  8647. }
  8648. return (Tools._tmpFloatArray[0] = value);
  8649. };
  8650. /**
  8651. * Find the next highest power of two.
  8652. * @param x Number to start search from.
  8653. * @return Next highest power of two.
  8654. */
  8655. Tools.CeilingPOT = function (x) {
  8656. x--;
  8657. x |= x >> 1;
  8658. x |= x >> 2;
  8659. x |= x >> 4;
  8660. x |= x >> 8;
  8661. x |= x >> 16;
  8662. x++;
  8663. return x;
  8664. };
  8665. /**
  8666. * Find the next lowest power of two.
  8667. * @param x Number to start search from.
  8668. * @return Next lowest power of two.
  8669. */
  8670. Tools.FloorPOT = function (x) {
  8671. x = x | (x >> 1);
  8672. x = x | (x >> 2);
  8673. x = x | (x >> 4);
  8674. x = x | (x >> 8);
  8675. x = x | (x >> 16);
  8676. return x - (x >> 1);
  8677. };
  8678. /**
  8679. * Find the nearest power of two.
  8680. * @param x Number to start search from.
  8681. * @return Next nearest power of two.
  8682. */
  8683. Tools.NearestPOT = function (x) {
  8684. var c = Tools.CeilingPOT(x);
  8685. var f = Tools.FloorPOT(x);
  8686. return (c - x) > (x - f) ? f : c;
  8687. };
  8688. Tools.GetExponentOfTwo = function (value, max, mode) {
  8689. if (mode === void 0) { mode = BABYLON.Engine.SCALEMODE_NEAREST; }
  8690. var pot;
  8691. switch (mode) {
  8692. case BABYLON.Engine.SCALEMODE_FLOOR:
  8693. pot = Tools.FloorPOT(value);
  8694. break;
  8695. case BABYLON.Engine.SCALEMODE_NEAREST:
  8696. pot = Tools.NearestPOT(value);
  8697. break;
  8698. case BABYLON.Engine.SCALEMODE_CEILING:
  8699. default:
  8700. pot = Tools.CeilingPOT(value);
  8701. break;
  8702. }
  8703. return Math.min(pot, max);
  8704. };
  8705. Tools.GetFilename = function (path) {
  8706. var index = path.lastIndexOf("/");
  8707. if (index < 0)
  8708. return path;
  8709. return path.substring(index + 1);
  8710. };
  8711. /**
  8712. * Extracts the "folder" part of a path (everything before the filename).
  8713. * @param uri The URI to extract the info from
  8714. * @param returnUnchangedIfNoSlash Do not touch the URI if no slashes are present
  8715. * @returns The "folder" part of the path
  8716. */
  8717. Tools.GetFolderPath = function (uri, returnUnchangedIfNoSlash) {
  8718. if (returnUnchangedIfNoSlash === void 0) { returnUnchangedIfNoSlash = false; }
  8719. var index = uri.lastIndexOf("/");
  8720. if (index < 0) {
  8721. if (returnUnchangedIfNoSlash) {
  8722. return uri;
  8723. }
  8724. return "";
  8725. }
  8726. return uri.substring(0, index + 1);
  8727. };
  8728. Tools.GetDOMTextContent = function (element) {
  8729. var result = "";
  8730. var child = element.firstChild;
  8731. while (child) {
  8732. if (child.nodeType === 3) {
  8733. result += child.textContent;
  8734. }
  8735. child = child.nextSibling;
  8736. }
  8737. return result;
  8738. };
  8739. Tools.ToDegrees = function (angle) {
  8740. return angle * 180 / Math.PI;
  8741. };
  8742. Tools.ToRadians = function (angle) {
  8743. return angle * Math.PI / 180;
  8744. };
  8745. Tools.EncodeArrayBufferTobase64 = function (buffer) {
  8746. var keyStr = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=";
  8747. var output = "";
  8748. var chr1, chr2, chr3, enc1, enc2, enc3, enc4;
  8749. var i = 0;
  8750. var bytes = new Uint8Array(buffer);
  8751. while (i < bytes.length) {
  8752. chr1 = bytes[i++];
  8753. chr2 = i < bytes.length ? bytes[i++] : Number.NaN; // Not sure if the index
  8754. chr3 = i < bytes.length ? bytes[i++] : Number.NaN; // checks are needed here
  8755. enc1 = chr1 >> 2;
  8756. enc2 = ((chr1 & 3) << 4) | (chr2 >> 4);
  8757. enc3 = ((chr2 & 15) << 2) | (chr3 >> 6);
  8758. enc4 = chr3 & 63;
  8759. if (isNaN(chr2)) {
  8760. enc3 = enc4 = 64;
  8761. }
  8762. else if (isNaN(chr3)) {
  8763. enc4 = 64;
  8764. }
  8765. output += keyStr.charAt(enc1) + keyStr.charAt(enc2) +
  8766. keyStr.charAt(enc3) + keyStr.charAt(enc4);
  8767. }
  8768. return "data:image/png;base64," + output;
  8769. };
  8770. Tools.ExtractMinAndMaxIndexed = function (positions, indices, indexStart, indexCount, bias) {
  8771. if (bias === void 0) { bias = null; }
  8772. var minimum = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  8773. var maximum = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  8774. for (var index = indexStart; index < indexStart + indexCount; index++) {
  8775. var current = new BABYLON.Vector3(positions[indices[index] * 3], positions[indices[index] * 3 + 1], positions[indices[index] * 3 + 2]);
  8776. minimum = BABYLON.Vector3.Minimize(current, minimum);
  8777. maximum = BABYLON.Vector3.Maximize(current, maximum);
  8778. }
  8779. if (bias) {
  8780. minimum.x -= minimum.x * bias.x + bias.y;
  8781. minimum.y -= minimum.y * bias.x + bias.y;
  8782. minimum.z -= minimum.z * bias.x + bias.y;
  8783. maximum.x += maximum.x * bias.x + bias.y;
  8784. maximum.y += maximum.y * bias.x + bias.y;
  8785. maximum.z += maximum.z * bias.x + bias.y;
  8786. }
  8787. return {
  8788. minimum: minimum,
  8789. maximum: maximum
  8790. };
  8791. };
  8792. Tools.ExtractMinAndMax = function (positions, start, count, bias, stride) {
  8793. if (bias === void 0) { bias = null; }
  8794. var minimum = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  8795. var maximum = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  8796. if (!stride) {
  8797. stride = 3;
  8798. }
  8799. for (var index = start; index < start + count; index++) {
  8800. var current = new BABYLON.Vector3(positions[index * stride], positions[index * stride + 1], positions[index * stride + 2]);
  8801. minimum = BABYLON.Vector3.Minimize(current, minimum);
  8802. maximum = BABYLON.Vector3.Maximize(current, maximum);
  8803. }
  8804. if (bias) {
  8805. minimum.x -= minimum.x * bias.x + bias.y;
  8806. minimum.y -= minimum.y * bias.x + bias.y;
  8807. minimum.z -= minimum.z * bias.x + bias.y;
  8808. maximum.x += maximum.x * bias.x + bias.y;
  8809. maximum.y += maximum.y * bias.x + bias.y;
  8810. maximum.z += maximum.z * bias.x + bias.y;
  8811. }
  8812. return {
  8813. minimum: minimum,
  8814. maximum: maximum
  8815. };
  8816. };
  8817. Tools.Vector2ArrayFeeder = function (array) {
  8818. return function (index) {
  8819. var isFloatArray = (array.BYTES_PER_ELEMENT !== undefined);
  8820. var length = isFloatArray ? array.length / 2 : array.length;
  8821. if (index >= length) {
  8822. return null;
  8823. }
  8824. if (isFloatArray) {
  8825. var fa = array;
  8826. return new BABYLON.Vector2(fa[index * 2 + 0], fa[index * 2 + 1]);
  8827. }
  8828. var a = array;
  8829. return a[index];
  8830. };
  8831. };
  8832. Tools.ExtractMinAndMaxVector2 = function (feeder, bias) {
  8833. if (bias === void 0) { bias = null; }
  8834. var minimum = new BABYLON.Vector2(Number.MAX_VALUE, Number.MAX_VALUE);
  8835. var maximum = new BABYLON.Vector2(-Number.MAX_VALUE, -Number.MAX_VALUE);
  8836. var i = 0;
  8837. var cur = feeder(i++);
  8838. while (cur) {
  8839. minimum = BABYLON.Vector2.Minimize(cur, minimum);
  8840. maximum = BABYLON.Vector2.Maximize(cur, maximum);
  8841. cur = feeder(i++);
  8842. }
  8843. if (bias) {
  8844. minimum.x -= minimum.x * bias.x + bias.y;
  8845. minimum.y -= minimum.y * bias.x + bias.y;
  8846. maximum.x += maximum.x * bias.x + bias.y;
  8847. maximum.y += maximum.y * bias.x + bias.y;
  8848. }
  8849. return {
  8850. minimum: minimum,
  8851. maximum: maximum
  8852. };
  8853. };
  8854. Tools.MakeArray = function (obj, allowsNullUndefined) {
  8855. if (allowsNullUndefined !== true && (obj === undefined || obj == null))
  8856. return null;
  8857. return Array.isArray(obj) ? obj : [obj];
  8858. };
  8859. // Misc.
  8860. Tools.GetPointerPrefix = function () {
  8861. var eventPrefix = "pointer";
  8862. // Check if pointer events are supported
  8863. if (Tools.IsWindowObjectExist() && !window.PointerEvent && !navigator.pointerEnabled) {
  8864. eventPrefix = "mouse";
  8865. }
  8866. return eventPrefix;
  8867. };
  8868. /**
  8869. * @param func - the function to be called
  8870. * @param requester - the object that will request the next frame. Falls back to window.
  8871. */
  8872. Tools.QueueNewFrame = function (func, requester) {
  8873. if (!Tools.IsWindowObjectExist()) {
  8874. return setTimeout(func, 16);
  8875. }
  8876. if (!requester) {
  8877. requester = window;
  8878. }
  8879. if (requester.requestAnimationFrame) {
  8880. return requester.requestAnimationFrame(func);
  8881. }
  8882. else if (requester.msRequestAnimationFrame) {
  8883. return requester.msRequestAnimationFrame(func);
  8884. }
  8885. else if (requester.webkitRequestAnimationFrame) {
  8886. return requester.webkitRequestAnimationFrame(func);
  8887. }
  8888. else if (requester.mozRequestAnimationFrame) {
  8889. return requester.mozRequestAnimationFrame(func);
  8890. }
  8891. else if (requester.oRequestAnimationFrame) {
  8892. return requester.oRequestAnimationFrame(func);
  8893. }
  8894. else {
  8895. return window.setTimeout(func, 16);
  8896. }
  8897. };
  8898. Tools.RequestFullscreen = function (element) {
  8899. var requestFunction = element.requestFullscreen || element.msRequestFullscreen || element.webkitRequestFullscreen || element.mozRequestFullScreen;
  8900. if (!requestFunction)
  8901. return;
  8902. requestFunction.call(element);
  8903. };
  8904. Tools.ExitFullscreen = function () {
  8905. if (document.exitFullscreen) {
  8906. document.exitFullscreen();
  8907. }
  8908. else if (document.mozCancelFullScreen) {
  8909. document.mozCancelFullScreen();
  8910. }
  8911. else if (document.webkitCancelFullScreen) {
  8912. document.webkitCancelFullScreen();
  8913. }
  8914. else if (document.msCancelFullScreen) {
  8915. document.msCancelFullScreen();
  8916. }
  8917. };
  8918. Tools.SetCorsBehavior = function (url, element) {
  8919. if (url && url.indexOf("data:") === 0) {
  8920. return;
  8921. }
  8922. if (Tools.CorsBehavior) {
  8923. if (typeof (Tools.CorsBehavior) === 'string' || Tools.CorsBehavior instanceof String) {
  8924. element.crossOrigin = Tools.CorsBehavior;
  8925. }
  8926. else {
  8927. var result = Tools.CorsBehavior(url);
  8928. if (result) {
  8929. element.crossOrigin = result;
  8930. }
  8931. }
  8932. }
  8933. };
  8934. // External files
  8935. Tools.CleanUrl = function (url) {
  8936. url = url.replace(/#/mg, "%23");
  8937. return url;
  8938. };
  8939. Tools.LoadImage = function (url, onLoad, onError, database) {
  8940. if (url instanceof ArrayBuffer) {
  8941. url = Tools.EncodeArrayBufferTobase64(url);
  8942. }
  8943. url = Tools.CleanUrl(url);
  8944. url = Tools.PreprocessUrl(url);
  8945. var img = new Image();
  8946. Tools.SetCorsBehavior(url, img);
  8947. var loadHandler = function () {
  8948. img.removeEventListener("load", loadHandler);
  8949. img.removeEventListener("error", errorHandler);
  8950. onLoad(img);
  8951. };
  8952. var errorHandler = function (err) {
  8953. img.removeEventListener("load", loadHandler);
  8954. img.removeEventListener("error", errorHandler);
  8955. Tools.Error("Error while trying to load image: " + url);
  8956. if (onError) {
  8957. onError("Error while trying to load image: " + url, err);
  8958. }
  8959. };
  8960. img.addEventListener("load", loadHandler);
  8961. img.addEventListener("error", errorHandler);
  8962. var noIndexedDB = function () {
  8963. img.src = url;
  8964. };
  8965. var loadFromIndexedDB = function () {
  8966. if (database) {
  8967. database.loadImageFromDB(url, img);
  8968. }
  8969. };
  8970. //ANY database to do!
  8971. if (url.substr(0, 5) !== "data:" && database && database.enableTexturesOffline && BABYLON.Database.IsUASupportingBlobStorage) {
  8972. database.openAsync(loadFromIndexedDB, noIndexedDB);
  8973. }
  8974. else {
  8975. if (url.indexOf("file:") !== -1) {
  8976. var textureName = decodeURIComponent(url.substring(5).toLowerCase());
  8977. if (BABYLON.FilesInput.FilesToLoad[textureName]) {
  8978. try {
  8979. var blobURL;
  8980. try {
  8981. blobURL = URL.createObjectURL(BABYLON.FilesInput.FilesToLoad[textureName], { oneTimeOnly: true });
  8982. }
  8983. catch (ex) {
  8984. // Chrome doesn't support oneTimeOnly parameter
  8985. blobURL = URL.createObjectURL(BABYLON.FilesInput.FilesToLoad[textureName]);
  8986. }
  8987. img.src = blobURL;
  8988. }
  8989. catch (e) {
  8990. img.src = "";
  8991. }
  8992. return img;
  8993. }
  8994. }
  8995. noIndexedDB();
  8996. }
  8997. return img;
  8998. };
  8999. Tools.LoadFile = function (url, onSuccess, onProgress, database, useArrayBuffer, onError) {
  9000. url = Tools.CleanUrl(url);
  9001. url = Tools.PreprocessUrl(url);
  9002. // If file and file input are set
  9003. if (url.indexOf("file:") !== -1) {
  9004. var fileName = decodeURIComponent(url.substring(5).toLowerCase());
  9005. if (BABYLON.FilesInput.FilesToLoad[fileName]) {
  9006. return Tools.ReadFile(BABYLON.FilesInput.FilesToLoad[fileName], onSuccess, onProgress, useArrayBuffer);
  9007. }
  9008. }
  9009. var loadUrl = Tools.BaseUrl + url;
  9010. var aborted = false;
  9011. var fileRequest = {
  9012. onCompleteObservable: new BABYLON.Observable(),
  9013. abort: function () { return aborted = true; },
  9014. };
  9015. var requestFile = function () {
  9016. var request = new XMLHttpRequest();
  9017. var retryHandle = null;
  9018. fileRequest.abort = function () {
  9019. aborted = true;
  9020. if (request.readyState !== (XMLHttpRequest.DONE || 4)) {
  9021. request.abort();
  9022. }
  9023. if (retryHandle !== null) {
  9024. clearTimeout(retryHandle);
  9025. retryHandle = null;
  9026. }
  9027. };
  9028. var retryLoop = function (retryIndex) {
  9029. request.open('GET', loadUrl, true);
  9030. if (useArrayBuffer) {
  9031. request.responseType = "arraybuffer";
  9032. }
  9033. if (onProgress) {
  9034. request.addEventListener("progress", onProgress);
  9035. }
  9036. var onLoadEnd = function () {
  9037. request.removeEventListener("loadend", onLoadEnd);
  9038. fileRequest.onCompleteObservable.notifyObservers(fileRequest);
  9039. fileRequest.onCompleteObservable.clear();
  9040. };
  9041. request.addEventListener("loadend", onLoadEnd);
  9042. var onReadyStateChange = function () {
  9043. if (aborted) {
  9044. return;
  9045. }
  9046. // In case of undefined state in some browsers.
  9047. if (request.readyState === (XMLHttpRequest.DONE || 4)) {
  9048. // Some browsers have issues where onreadystatechange can be called multiple times with the same value.
  9049. request.removeEventListener("readystatechange", onReadyStateChange);
  9050. if (request.status >= 200 && request.status < 300 || (!Tools.IsWindowObjectExist() && (request.status === 0))) {
  9051. onSuccess(!useArrayBuffer ? request.responseText : request.response, request.responseURL);
  9052. return;
  9053. }
  9054. var retryStrategy = Tools.DefaultRetryStrategy;
  9055. if (retryStrategy) {
  9056. var waitTime = retryStrategy(loadUrl, request, retryIndex);
  9057. if (waitTime !== -1) {
  9058. // Prevent the request from completing for retry.
  9059. request.removeEventListener("loadend", onLoadEnd);
  9060. request = new XMLHttpRequest();
  9061. retryHandle = setTimeout(function () { return retryLoop(retryIndex + 1); }, waitTime);
  9062. return;
  9063. }
  9064. }
  9065. var e = new LoadFileError("Error status: " + request.status + " " + request.statusText + " - Unable to load " + loadUrl, request);
  9066. if (onError) {
  9067. onError(request, e);
  9068. }
  9069. else {
  9070. throw e;
  9071. }
  9072. }
  9073. };
  9074. request.addEventListener("readystatechange", onReadyStateChange);
  9075. request.send();
  9076. };
  9077. retryLoop(0);
  9078. };
  9079. // Caching all files
  9080. if (database && database.enableSceneOffline) {
  9081. var noIndexedDB_1 = function () {
  9082. if (!aborted) {
  9083. requestFile();
  9084. }
  9085. };
  9086. var loadFromIndexedDB = function () {
  9087. // TODO: database needs to support aborting and should return a IFileRequest
  9088. if (aborted) {
  9089. return;
  9090. }
  9091. if (database) {
  9092. database.loadFileFromDB(url, function (data) {
  9093. if (!aborted) {
  9094. onSuccess(data);
  9095. }
  9096. fileRequest.onCompleteObservable.notifyObservers(fileRequest);
  9097. }, onProgress ? function (event) {
  9098. if (!aborted) {
  9099. onProgress(event);
  9100. }
  9101. } : undefined, noIndexedDB_1, useArrayBuffer);
  9102. }
  9103. };
  9104. database.openAsync(loadFromIndexedDB, noIndexedDB_1);
  9105. }
  9106. else {
  9107. requestFile();
  9108. }
  9109. return fileRequest;
  9110. };
  9111. /**
  9112. * Load a script (identified by an url). When the url returns, the
  9113. * content of this file is added into a new script element, attached to the DOM (body element)
  9114. */
  9115. Tools.LoadScript = function (scriptUrl, onSuccess, onError) {
  9116. var head = document.getElementsByTagName('head')[0];
  9117. var script = document.createElement('script');
  9118. script.type = 'text/javascript';
  9119. script.src = scriptUrl;
  9120. script.onload = function () {
  9121. if (onSuccess) {
  9122. onSuccess();
  9123. }
  9124. };
  9125. script.onerror = function (e) {
  9126. if (onError) {
  9127. onError("Unable to load script '" + scriptUrl + "'", e);
  9128. }
  9129. };
  9130. head.appendChild(script);
  9131. };
  9132. Tools.ReadFileAsDataURL = function (fileToLoad, callback, progressCallback) {
  9133. var reader = new FileReader();
  9134. var request = {
  9135. onCompleteObservable: new BABYLON.Observable(),
  9136. abort: function () { return reader.abort(); },
  9137. };
  9138. reader.onloadend = function (e) {
  9139. request.onCompleteObservable.notifyObservers(request);
  9140. };
  9141. reader.onload = function (e) {
  9142. //target doesn't have result from ts 1.3
  9143. callback(e.target['result']);
  9144. };
  9145. reader.onprogress = progressCallback;
  9146. reader.readAsDataURL(fileToLoad);
  9147. return request;
  9148. };
  9149. Tools.ReadFile = function (fileToLoad, callback, progressCallBack, useArrayBuffer) {
  9150. var reader = new FileReader();
  9151. var request = {
  9152. onCompleteObservable: new BABYLON.Observable(),
  9153. abort: function () { return reader.abort(); },
  9154. };
  9155. reader.onloadend = function (e) { return request.onCompleteObservable.notifyObservers(request); };
  9156. reader.onerror = function (e) {
  9157. Tools.Log("Error while reading file: " + fileToLoad.name);
  9158. callback(JSON.stringify({ autoClear: true, clearColor: [1, 0, 0], ambientColor: [0, 0, 0], gravity: [0, -9.807, 0], meshes: [], cameras: [], lights: [] }));
  9159. };
  9160. reader.onload = function (e) {
  9161. //target doesn't have result from ts 1.3
  9162. callback(e.target['result']);
  9163. };
  9164. if (progressCallBack) {
  9165. reader.onprogress = progressCallBack;
  9166. }
  9167. if (!useArrayBuffer) {
  9168. // Asynchronous read
  9169. reader.readAsText(fileToLoad);
  9170. }
  9171. else {
  9172. reader.readAsArrayBuffer(fileToLoad);
  9173. }
  9174. return request;
  9175. };
  9176. //returns a downloadable url to a file content.
  9177. Tools.FileAsURL = function (content) {
  9178. var fileBlob = new Blob([content]);
  9179. var url = window.URL || window.webkitURL;
  9180. var link = url.createObjectURL(fileBlob);
  9181. return link;
  9182. };
  9183. // Misc.
  9184. Tools.Format = function (value, decimals) {
  9185. if (decimals === void 0) { decimals = 2; }
  9186. return value.toFixed(decimals);
  9187. };
  9188. Tools.CheckExtends = function (v, min, max) {
  9189. if (v.x < min.x)
  9190. min.x = v.x;
  9191. if (v.y < min.y)
  9192. min.y = v.y;
  9193. if (v.z < min.z)
  9194. min.z = v.z;
  9195. if (v.x > max.x)
  9196. max.x = v.x;
  9197. if (v.y > max.y)
  9198. max.y = v.y;
  9199. if (v.z > max.z)
  9200. max.z = v.z;
  9201. };
  9202. Tools.DeepCopy = function (source, destination, doNotCopyList, mustCopyList) {
  9203. for (var prop in source) {
  9204. if (prop[0] === "_" && (!mustCopyList || mustCopyList.indexOf(prop) === -1)) {
  9205. continue;
  9206. }
  9207. if (doNotCopyList && doNotCopyList.indexOf(prop) !== -1) {
  9208. continue;
  9209. }
  9210. var sourceValue = source[prop];
  9211. var typeOfSourceValue = typeof sourceValue;
  9212. if (typeOfSourceValue === "function") {
  9213. continue;
  9214. }
  9215. try {
  9216. if (typeOfSourceValue === "object") {
  9217. if (sourceValue instanceof Array) {
  9218. destination[prop] = [];
  9219. if (sourceValue.length > 0) {
  9220. if (typeof sourceValue[0] == "object") {
  9221. for (var index = 0; index < sourceValue.length; index++) {
  9222. var clonedValue = cloneValue(sourceValue[index], destination);
  9223. if (destination[prop].indexOf(clonedValue) === -1) { // Test if auto inject was not done
  9224. destination[prop].push(clonedValue);
  9225. }
  9226. }
  9227. }
  9228. else {
  9229. destination[prop] = sourceValue.slice(0);
  9230. }
  9231. }
  9232. }
  9233. else {
  9234. destination[prop] = cloneValue(sourceValue, destination);
  9235. }
  9236. }
  9237. else {
  9238. destination[prop] = sourceValue;
  9239. }
  9240. }
  9241. catch (e) {
  9242. // Just ignore error (it could be because of a read-only property)
  9243. }
  9244. }
  9245. };
  9246. Tools.IsEmpty = function (obj) {
  9247. for (var i in obj) {
  9248. if (obj.hasOwnProperty(i)) {
  9249. return false;
  9250. }
  9251. }
  9252. return true;
  9253. };
  9254. Tools.RegisterTopRootEvents = function (events) {
  9255. for (var index = 0; index < events.length; index++) {
  9256. var event = events[index];
  9257. window.addEventListener(event.name, event.handler, false);
  9258. try {
  9259. if (window.parent) {
  9260. window.parent.addEventListener(event.name, event.handler, false);
  9261. }
  9262. }
  9263. catch (e) {
  9264. // Silently fails...
  9265. }
  9266. }
  9267. };
  9268. Tools.UnregisterTopRootEvents = function (events) {
  9269. for (var index = 0; index < events.length; index++) {
  9270. var event = events[index];
  9271. window.removeEventListener(event.name, event.handler);
  9272. try {
  9273. if (window.parent) {
  9274. window.parent.removeEventListener(event.name, event.handler);
  9275. }
  9276. }
  9277. catch (e) {
  9278. // Silently fails...
  9279. }
  9280. }
  9281. };
  9282. Tools.DumpFramebuffer = function (width, height, engine, successCallback, mimeType, fileName) {
  9283. if (mimeType === void 0) { mimeType = "image/png"; }
  9284. // Read the contents of the framebuffer
  9285. var numberOfChannelsByLine = width * 4;
  9286. var halfHeight = height / 2;
  9287. //Reading datas from WebGL
  9288. var data = engine.readPixels(0, 0, width, height);
  9289. //To flip image on Y axis.
  9290. for (var i = 0; i < halfHeight; i++) {
  9291. for (var j = 0; j < numberOfChannelsByLine; j++) {
  9292. var currentCell = j + i * numberOfChannelsByLine;
  9293. var targetLine = height - i - 1;
  9294. var targetCell = j + targetLine * numberOfChannelsByLine;
  9295. var temp = data[currentCell];
  9296. data[currentCell] = data[targetCell];
  9297. data[targetCell] = temp;
  9298. }
  9299. }
  9300. // Create a 2D canvas to store the result
  9301. if (!screenshotCanvas) {
  9302. screenshotCanvas = document.createElement('canvas');
  9303. }
  9304. screenshotCanvas.width = width;
  9305. screenshotCanvas.height = height;
  9306. var context = screenshotCanvas.getContext('2d');
  9307. if (context) {
  9308. // Copy the pixels to a 2D canvas
  9309. var imageData = context.createImageData(width, height);
  9310. var castData = (imageData.data);
  9311. castData.set(data);
  9312. context.putImageData(imageData, 0, 0);
  9313. Tools.EncodeScreenshotCanvasData(successCallback, mimeType, fileName);
  9314. }
  9315. };
  9316. Tools.EncodeScreenshotCanvasData = function (successCallback, mimeType, fileName) {
  9317. if (mimeType === void 0) { mimeType = "image/png"; }
  9318. var base64Image = screenshotCanvas.toDataURL(mimeType);
  9319. if (successCallback) {
  9320. successCallback(base64Image);
  9321. }
  9322. else {
  9323. // We need HTMLCanvasElement.toBlob for HD screenshots
  9324. if (!screenshotCanvas.toBlob) {
  9325. // low performance polyfill based on toDataURL (https://developer.mozilla.org/en-US/docs/Web/API/HTMLCanvasElement/toBlob)
  9326. screenshotCanvas.toBlob = function (callback, type, quality) {
  9327. var _this = this;
  9328. setTimeout(function () {
  9329. var binStr = atob(_this.toDataURL(type, quality).split(',')[1]), len = binStr.length, arr = new Uint8Array(len);
  9330. for (var i = 0; i < len; i++) {
  9331. arr[i] = binStr.charCodeAt(i);
  9332. }
  9333. callback(new Blob([arr], { type: type || 'image/png' }));
  9334. });
  9335. };
  9336. }
  9337. screenshotCanvas.toBlob(function (blob) {
  9338. var url = URL.createObjectURL(blob);
  9339. //Creating a link if the browser have the download attribute on the a tag, to automatically start download generated image.
  9340. if (("download" in document.createElement("a"))) {
  9341. var a = window.document.createElement("a");
  9342. a.href = url;
  9343. if (fileName) {
  9344. a.setAttribute("download", fileName);
  9345. }
  9346. else {
  9347. var date = new Date();
  9348. var stringDate = (date.getFullYear() + "-" + (date.getMonth() + 1)).slice(-2) + "-" + date.getDate() + "_" + date.getHours() + "-" + ('0' + date.getMinutes()).slice(-2);
  9349. a.setAttribute("download", "screenshot_" + stringDate + ".png");
  9350. }
  9351. window.document.body.appendChild(a);
  9352. a.addEventListener("click", function () {
  9353. if (a.parentElement) {
  9354. a.parentElement.removeChild(a);
  9355. }
  9356. });
  9357. a.click();
  9358. }
  9359. else {
  9360. var newWindow = window.open("");
  9361. if (!newWindow)
  9362. return;
  9363. var img = newWindow.document.createElement("img");
  9364. img.onload = function () {
  9365. // no longer need to read the blob so it's revoked
  9366. URL.revokeObjectURL(url);
  9367. };
  9368. img.src = url;
  9369. newWindow.document.body.appendChild(img);
  9370. }
  9371. });
  9372. }
  9373. };
  9374. Tools.CreateScreenshot = function (engine, camera, size, successCallback, mimeType) {
  9375. if (mimeType === void 0) { mimeType = "image/png"; }
  9376. var width;
  9377. var height;
  9378. // If a precision value is specified
  9379. if (size.precision) {
  9380. width = Math.round(engine.getRenderWidth() * size.precision);
  9381. height = Math.round(width / engine.getAspectRatio(camera));
  9382. }
  9383. else if (size.width && size.height) {
  9384. width = size.width;
  9385. height = size.height;
  9386. }
  9387. //If passing only width, computing height to keep display canvas ratio.
  9388. else if (size.width && !size.height) {
  9389. width = size.width;
  9390. height = Math.round(width / engine.getAspectRatio(camera));
  9391. }
  9392. //If passing only height, computing width to keep display canvas ratio.
  9393. else if (size.height && !size.width) {
  9394. height = size.height;
  9395. width = Math.round(height * engine.getAspectRatio(camera));
  9396. }
  9397. //Assuming here that "size" parameter is a number
  9398. else if (!isNaN(size)) {
  9399. height = size;
  9400. width = size;
  9401. }
  9402. else {
  9403. Tools.Error("Invalid 'size' parameter !");
  9404. return;
  9405. }
  9406. if (!screenshotCanvas) {
  9407. screenshotCanvas = document.createElement('canvas');
  9408. }
  9409. screenshotCanvas.width = width;
  9410. screenshotCanvas.height = height;
  9411. var renderContext = screenshotCanvas.getContext("2d");
  9412. var ratio = engine.getRenderWidth() / engine.getRenderHeight();
  9413. var newWidth = width;
  9414. var newHeight = newWidth / ratio;
  9415. if (newHeight > height) {
  9416. newHeight = height;
  9417. newWidth = newHeight * ratio;
  9418. }
  9419. var offsetX = Math.max(0, width - newWidth) / 2;
  9420. var offsetY = Math.max(0, height - newHeight) / 2;
  9421. var renderingCanvas = engine.getRenderingCanvas();
  9422. if (renderContext && renderingCanvas) {
  9423. renderContext.drawImage(renderingCanvas, offsetX, offsetY, newWidth, newHeight);
  9424. }
  9425. Tools.EncodeScreenshotCanvasData(successCallback, mimeType);
  9426. };
  9427. /**
  9428. * Generates an image screenshot from the specified camera.
  9429. *
  9430. * @param engine The engine to use for rendering
  9431. * @param camera The camera to use for rendering
  9432. * @param size This parameter can be set to a single number or to an object with the
  9433. * following (optional) properties: precision, width, height. If a single number is passed,
  9434. * it will be used for both width and height. If an object is passed, the screenshot size
  9435. * will be derived from the parameters. The precision property is a multiplier allowing
  9436. * rendering at a higher or lower resolution.
  9437. * @param successCallback The callback receives a single parameter which contains the
  9438. * screenshot as a string of base64-encoded characters. This string can be assigned to the
  9439. * src parameter of an <img> to display it.
  9440. * @param mimeType The MIME type of the screenshot image (default: image/png).
  9441. * Check your browser for supported MIME types.
  9442. * @param samples Texture samples (default: 1)
  9443. * @param antialiasing Whether antialiasing should be turned on or not (default: false)
  9444. * @param fileName A name for for the downloaded file.
  9445. * @constructor
  9446. */
  9447. Tools.CreateScreenshotUsingRenderTarget = function (engine, camera, size, successCallback, mimeType, samples, antialiasing, fileName) {
  9448. if (mimeType === void 0) { mimeType = "image/png"; }
  9449. if (samples === void 0) { samples = 1; }
  9450. if (antialiasing === void 0) { antialiasing = false; }
  9451. var width;
  9452. var height;
  9453. //If a precision value is specified
  9454. if (size.precision) {
  9455. width = Math.round(engine.getRenderWidth() * size.precision);
  9456. height = Math.round(width / engine.getAspectRatio(camera));
  9457. size = { width: width, height: height };
  9458. }
  9459. else if (size.width && size.height) {
  9460. width = size.width;
  9461. height = size.height;
  9462. }
  9463. //If passing only width, computing height to keep display canvas ratio.
  9464. else if (size.width && !size.height) {
  9465. width = size.width;
  9466. height = Math.round(width / engine.getAspectRatio(camera));
  9467. size = { width: width, height: height };
  9468. }
  9469. //If passing only height, computing width to keep display canvas ratio.
  9470. else if (size.height && !size.width) {
  9471. height = size.height;
  9472. width = Math.round(height * engine.getAspectRatio(camera));
  9473. size = { width: width, height: height };
  9474. }
  9475. //Assuming here that "size" parameter is a number
  9476. else if (!isNaN(size)) {
  9477. height = size;
  9478. width = size;
  9479. }
  9480. else {
  9481. Tools.Error("Invalid 'size' parameter !");
  9482. return;
  9483. }
  9484. var scene = camera.getScene();
  9485. var previousCamera = null;
  9486. if (scene.activeCamera !== camera) {
  9487. previousCamera = scene.activeCamera;
  9488. scene.activeCamera = camera;
  9489. }
  9490. //At this point size can be a number, or an object (according to engine.prototype.createRenderTargetTexture method)
  9491. var texture = new BABYLON.RenderTargetTexture("screenShot", size, scene, false, false, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT, false, BABYLON.Texture.NEAREST_SAMPLINGMODE);
  9492. texture.renderList = null;
  9493. texture.samples = samples;
  9494. if (antialiasing) {
  9495. texture.addPostProcess(new BABYLON.FxaaPostProcess('antialiasing', 1.0, scene.activeCamera));
  9496. }
  9497. texture.onAfterRenderObservable.add(function () {
  9498. Tools.DumpFramebuffer(width, height, engine, successCallback, mimeType, fileName);
  9499. });
  9500. scene.incrementRenderId();
  9501. scene.resetCachedMaterial();
  9502. texture.render(true);
  9503. texture.dispose();
  9504. if (previousCamera) {
  9505. scene.activeCamera = previousCamera;
  9506. }
  9507. camera.getProjectionMatrix(true); // Force cache refresh;
  9508. };
  9509. // XHR response validator for local file scenario
  9510. Tools.ValidateXHRData = function (xhr, dataType) {
  9511. // 1 for text (.babylon, manifest and shaders), 2 for TGA, 4 for DDS, 7 for all
  9512. if (dataType === void 0) { dataType = 7; }
  9513. try {
  9514. if (dataType & 1) {
  9515. if (xhr.responseText && xhr.responseText.length > 0) {
  9516. return true;
  9517. }
  9518. else if (dataType === 1) {
  9519. return false;
  9520. }
  9521. }
  9522. if (dataType & 2) {
  9523. // Check header width and height since there is no "TGA" magic number
  9524. var tgaHeader = BABYLON.TGATools.GetTGAHeader(xhr.response);
  9525. if (tgaHeader.width && tgaHeader.height && tgaHeader.width > 0 && tgaHeader.height > 0) {
  9526. return true;
  9527. }
  9528. else if (dataType === 2) {
  9529. return false;
  9530. }
  9531. }
  9532. if (dataType & 4) {
  9533. // Check for the "DDS" magic number
  9534. var ddsHeader = new Uint8Array(xhr.response, 0, 3);
  9535. if (ddsHeader[0] === 68 && ddsHeader[1] === 68 && ddsHeader[2] === 83) {
  9536. return true;
  9537. }
  9538. else {
  9539. return false;
  9540. }
  9541. }
  9542. }
  9543. catch (e) {
  9544. // Global protection
  9545. }
  9546. return false;
  9547. };
  9548. /**
  9549. * Implementation from http://stackoverflow.com/questions/105034/how-to-create-a-guid-uuid-in-javascript/2117523#answer-2117523
  9550. * Be aware Math.random() could cause collisions, but:
  9551. * "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"
  9552. */
  9553. Tools.RandomId = function () {
  9554. return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function (c) {
  9555. var r = Math.random() * 16 | 0, v = c === 'x' ? r : (r & 0x3 | 0x8);
  9556. return v.toString(16);
  9557. });
  9558. };
  9559. /**
  9560. * Test if the given uri is a base64 string.
  9561. * @param uri The uri to test
  9562. * @return True if the uri is a base64 string or false otherwise.
  9563. */
  9564. Tools.IsBase64 = function (uri) {
  9565. return uri.length < 5 ? false : uri.substr(0, 5) === "data:";
  9566. };
  9567. /**
  9568. * Decode the given base64 uri.
  9569. * @param uri The uri to decode
  9570. * @return The decoded base64 data.
  9571. */
  9572. Tools.DecodeBase64 = function (uri) {
  9573. var decodedString = atob(uri.split(",")[1]);
  9574. var bufferLength = decodedString.length;
  9575. var bufferView = new Uint8Array(new ArrayBuffer(bufferLength));
  9576. for (var i = 0; i < bufferLength; i++) {
  9577. bufferView[i] = decodedString.charCodeAt(i);
  9578. }
  9579. return bufferView.buffer;
  9580. };
  9581. Object.defineProperty(Tools, "NoneLogLevel", {
  9582. get: function () {
  9583. return Tools._NoneLogLevel;
  9584. },
  9585. enumerable: true,
  9586. configurable: true
  9587. });
  9588. Object.defineProperty(Tools, "MessageLogLevel", {
  9589. get: function () {
  9590. return Tools._MessageLogLevel;
  9591. },
  9592. enumerable: true,
  9593. configurable: true
  9594. });
  9595. Object.defineProperty(Tools, "WarningLogLevel", {
  9596. get: function () {
  9597. return Tools._WarningLogLevel;
  9598. },
  9599. enumerable: true,
  9600. configurable: true
  9601. });
  9602. Object.defineProperty(Tools, "ErrorLogLevel", {
  9603. get: function () {
  9604. return Tools._ErrorLogLevel;
  9605. },
  9606. enumerable: true,
  9607. configurable: true
  9608. });
  9609. Object.defineProperty(Tools, "AllLogLevel", {
  9610. get: function () {
  9611. return Tools._MessageLogLevel | Tools._WarningLogLevel | Tools._ErrorLogLevel;
  9612. },
  9613. enumerable: true,
  9614. configurable: true
  9615. });
  9616. Tools._AddLogEntry = function (entry) {
  9617. Tools._LogCache = entry + Tools._LogCache;
  9618. if (Tools.OnNewCacheEntry) {
  9619. Tools.OnNewCacheEntry(entry);
  9620. }
  9621. };
  9622. Tools._FormatMessage = function (message) {
  9623. var padStr = function (i) { return (i < 10) ? "0" + i : "" + i; };
  9624. var date = new Date();
  9625. return "[" + padStr(date.getHours()) + ":" + padStr(date.getMinutes()) + ":" + padStr(date.getSeconds()) + "]: " + message;
  9626. };
  9627. Tools._LogDisabled = function (message) {
  9628. // nothing to do
  9629. };
  9630. Tools._LogEnabled = function (message) {
  9631. var formattedMessage = Tools._FormatMessage(message);
  9632. console.log("BJS - " + formattedMessage);
  9633. var entry = "<div style='color:white'>" + formattedMessage + "</div><br>";
  9634. Tools._AddLogEntry(entry);
  9635. };
  9636. Tools._WarnDisabled = function (message) {
  9637. // nothing to do
  9638. };
  9639. Tools._WarnEnabled = function (message) {
  9640. var formattedMessage = Tools._FormatMessage(message);
  9641. console.warn("BJS - " + formattedMessage);
  9642. var entry = "<div style='color:orange'>" + formattedMessage + "</div><br>";
  9643. Tools._AddLogEntry(entry);
  9644. };
  9645. Tools._ErrorDisabled = function (message) {
  9646. // nothing to do
  9647. };
  9648. Tools._ErrorEnabled = function (message) {
  9649. Tools.errorsCount++;
  9650. var formattedMessage = Tools._FormatMessage(message);
  9651. console.error("BJS - " + formattedMessage);
  9652. var entry = "<div style='color:red'>" + formattedMessage + "</div><br>";
  9653. Tools._AddLogEntry(entry);
  9654. };
  9655. Object.defineProperty(Tools, "LogCache", {
  9656. get: function () {
  9657. return Tools._LogCache;
  9658. },
  9659. enumerable: true,
  9660. configurable: true
  9661. });
  9662. Tools.ClearLogCache = function () {
  9663. Tools._LogCache = "";
  9664. Tools.errorsCount = 0;
  9665. };
  9666. Object.defineProperty(Tools, "LogLevels", {
  9667. set: function (level) {
  9668. if ((level & Tools.MessageLogLevel) === Tools.MessageLogLevel) {
  9669. Tools.Log = Tools._LogEnabled;
  9670. }
  9671. else {
  9672. Tools.Log = Tools._LogDisabled;
  9673. }
  9674. if ((level & Tools.WarningLogLevel) === Tools.WarningLogLevel) {
  9675. Tools.Warn = Tools._WarnEnabled;
  9676. }
  9677. else {
  9678. Tools.Warn = Tools._WarnDisabled;
  9679. }
  9680. if ((level & Tools.ErrorLogLevel) === Tools.ErrorLogLevel) {
  9681. Tools.Error = Tools._ErrorEnabled;
  9682. }
  9683. else {
  9684. Tools.Error = Tools._ErrorDisabled;
  9685. }
  9686. },
  9687. enumerable: true,
  9688. configurable: true
  9689. });
  9690. Tools.IsWindowObjectExist = function () {
  9691. return (typeof window) !== "undefined";
  9692. };
  9693. Object.defineProperty(Tools, "PerformanceNoneLogLevel", {
  9694. get: function () {
  9695. return Tools._PerformanceNoneLogLevel;
  9696. },
  9697. enumerable: true,
  9698. configurable: true
  9699. });
  9700. Object.defineProperty(Tools, "PerformanceUserMarkLogLevel", {
  9701. get: function () {
  9702. return Tools._PerformanceUserMarkLogLevel;
  9703. },
  9704. enumerable: true,
  9705. configurable: true
  9706. });
  9707. Object.defineProperty(Tools, "PerformanceConsoleLogLevel", {
  9708. get: function () {
  9709. return Tools._PerformanceConsoleLogLevel;
  9710. },
  9711. enumerable: true,
  9712. configurable: true
  9713. });
  9714. Object.defineProperty(Tools, "PerformanceLogLevel", {
  9715. set: function (level) {
  9716. if ((level & Tools.PerformanceUserMarkLogLevel) === Tools.PerformanceUserMarkLogLevel) {
  9717. Tools.StartPerformanceCounter = Tools._StartUserMark;
  9718. Tools.EndPerformanceCounter = Tools._EndUserMark;
  9719. return;
  9720. }
  9721. if ((level & Tools.PerformanceConsoleLogLevel) === Tools.PerformanceConsoleLogLevel) {
  9722. Tools.StartPerformanceCounter = Tools._StartPerformanceConsole;
  9723. Tools.EndPerformanceCounter = Tools._EndPerformanceConsole;
  9724. return;
  9725. }
  9726. Tools.StartPerformanceCounter = Tools._StartPerformanceCounterDisabled;
  9727. Tools.EndPerformanceCounter = Tools._EndPerformanceCounterDisabled;
  9728. },
  9729. enumerable: true,
  9730. configurable: true
  9731. });
  9732. Tools._StartPerformanceCounterDisabled = function (counterName, condition) {
  9733. };
  9734. Tools._EndPerformanceCounterDisabled = function (counterName, condition) {
  9735. };
  9736. Tools._StartUserMark = function (counterName, condition) {
  9737. if (condition === void 0) { condition = true; }
  9738. if (!Tools._performance) {
  9739. if (!Tools.IsWindowObjectExist()) {
  9740. return;
  9741. }
  9742. Tools._performance = window.performance;
  9743. }
  9744. if (!condition || !Tools._performance.mark) {
  9745. return;
  9746. }
  9747. Tools._performance.mark(counterName + "-Begin");
  9748. };
  9749. Tools._EndUserMark = function (counterName, condition) {
  9750. if (condition === void 0) { condition = true; }
  9751. if (!condition || !Tools._performance.mark) {
  9752. return;
  9753. }
  9754. Tools._performance.mark(counterName + "-End");
  9755. Tools._performance.measure(counterName, counterName + "-Begin", counterName + "-End");
  9756. };
  9757. Tools._StartPerformanceConsole = function (counterName, condition) {
  9758. if (condition === void 0) { condition = true; }
  9759. if (!condition) {
  9760. return;
  9761. }
  9762. Tools._StartUserMark(counterName, condition);
  9763. if (console.time) {
  9764. console.time(counterName);
  9765. }
  9766. };
  9767. Tools._EndPerformanceConsole = function (counterName, condition) {
  9768. if (condition === void 0) { condition = true; }
  9769. if (!condition) {
  9770. return;
  9771. }
  9772. Tools._EndUserMark(counterName, condition);
  9773. if (console.time) {
  9774. console.timeEnd(counterName);
  9775. }
  9776. };
  9777. Object.defineProperty(Tools, "Now", {
  9778. get: function () {
  9779. if (Tools.IsWindowObjectExist() && window.performance && window.performance.now) {
  9780. return window.performance.now();
  9781. }
  9782. return Date.now();
  9783. },
  9784. enumerable: true,
  9785. configurable: true
  9786. });
  9787. /**
  9788. * This method will return the name of the class used to create the instance of the given object.
  9789. * It will works only on Javascript basic data types (number, string, ...) and instance of class declared with the @className decorator.
  9790. * @param object the object to get the class name from
  9791. * @return the name of the class, will be "object" for a custom data type not using the @className decorator
  9792. */
  9793. Tools.GetClassName = function (object, isType) {
  9794. if (isType === void 0) { isType = false; }
  9795. var name = null;
  9796. if (!isType && object.getClassName) {
  9797. name = object.getClassName();
  9798. }
  9799. else {
  9800. if (object instanceof Object) {
  9801. var classObj = isType ? object : Object.getPrototypeOf(object);
  9802. name = classObj.constructor["__bjsclassName__"];
  9803. }
  9804. if (!name) {
  9805. name = typeof object;
  9806. }
  9807. }
  9808. return name;
  9809. };
  9810. Tools.First = function (array, predicate) {
  9811. for (var _i = 0, array_1 = array; _i < array_1.length; _i++) {
  9812. var el = array_1[_i];
  9813. if (predicate(el)) {
  9814. return el;
  9815. }
  9816. }
  9817. return null;
  9818. };
  9819. /**
  9820. * This method will return the name of the full name of the class, including its owning module (if any).
  9821. * 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).
  9822. * @param object the object to get the class name from
  9823. * @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.
  9824. */
  9825. Tools.getFullClassName = function (object, isType) {
  9826. if (isType === void 0) { isType = false; }
  9827. var className = null;
  9828. var moduleName = null;
  9829. if (!isType && object.getClassName) {
  9830. className = object.getClassName();
  9831. }
  9832. else {
  9833. if (object instanceof Object) {
  9834. var classObj = isType ? object : Object.getPrototypeOf(object);
  9835. className = classObj.constructor["__bjsclassName__"];
  9836. moduleName = classObj.constructor["__bjsmoduleName__"];
  9837. }
  9838. if (!className) {
  9839. className = typeof object;
  9840. }
  9841. }
  9842. if (!className) {
  9843. return null;
  9844. }
  9845. return ((moduleName != null) ? (moduleName + ".") : "") + className;
  9846. };
  9847. /**
  9848. * 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.
  9849. * @param array
  9850. */
  9851. Tools.arrayOrStringFeeder = function (array) {
  9852. return function (index) {
  9853. if (index >= array.length) {
  9854. return null;
  9855. }
  9856. var val = array.charCodeAt ? array.charCodeAt(index) : array[index];
  9857. if (val && val.getHashCode) {
  9858. val = val.getHashCode();
  9859. }
  9860. if (typeof val === "string") {
  9861. return Tools.hashCodeFromStream(Tools.arrayOrStringFeeder(val));
  9862. }
  9863. return val;
  9864. };
  9865. };
  9866. /**
  9867. * Compute the hashCode of a stream of number
  9868. * To compute the HashCode on a string or an Array of data types implementing the getHashCode() method, use the arrayOrStringFeeder method.
  9869. * @param feeder a callback that will be called until it returns null, each valid returned values will be used to compute the hash code.
  9870. * @return the hash code computed
  9871. */
  9872. Tools.hashCodeFromStream = function (feeder) {
  9873. // Based from here: http://stackoverflow.com/a/7616484/802124
  9874. var hash = 0;
  9875. var index = 0;
  9876. var chr = feeder(index++);
  9877. while (chr != null) {
  9878. hash = ((hash << 5) - hash) + chr;
  9879. hash |= 0; // Convert to 32bit integer
  9880. chr = feeder(index++);
  9881. }
  9882. return hash;
  9883. };
  9884. /**
  9885. * Returns a promise that resolves after the given amount of time.
  9886. * @param delay Number of milliseconds to delay
  9887. * @returns Promise that resolves after the given amount of time
  9888. */
  9889. Tools.DelayAsync = function (delay) {
  9890. return new Promise(function (resolve) {
  9891. setTimeout(function () {
  9892. resolve();
  9893. }, delay);
  9894. });
  9895. };
  9896. Tools.BaseUrl = "";
  9897. Tools.DefaultRetryStrategy = RetryStrategy.ExponentialBackoff();
  9898. /**
  9899. * Default behaviour for cors in the application.
  9900. * It can be a string if the expected behavior is identical in the entire app.
  9901. * Or a callback to be able to set it per url or on a group of them (in case of Video source for instance)
  9902. */
  9903. Tools.CorsBehavior = "anonymous";
  9904. Tools.UseFallbackTexture = true;
  9905. /**
  9906. * Use this object to register external classes like custom textures or material
  9907. * to allow the laoders to instantiate them
  9908. */
  9909. Tools.RegisteredExternalClasses = {};
  9910. // Used in case of a texture loading problem
  9911. 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";
  9912. Tools._tmpFloatArray = new Float32Array(1);
  9913. Tools.PreprocessUrl = function (url) {
  9914. return url;
  9915. };
  9916. // Logs
  9917. Tools._NoneLogLevel = 0;
  9918. Tools._MessageLogLevel = 1;
  9919. Tools._WarningLogLevel = 2;
  9920. Tools._ErrorLogLevel = 4;
  9921. Tools._LogCache = "";
  9922. Tools.errorsCount = 0;
  9923. Tools.Log = Tools._LogEnabled;
  9924. Tools.Warn = Tools._WarnEnabled;
  9925. Tools.Error = Tools._ErrorEnabled;
  9926. // Performances
  9927. Tools._PerformanceNoneLogLevel = 0;
  9928. Tools._PerformanceUserMarkLogLevel = 1;
  9929. Tools._PerformanceConsoleLogLevel = 2;
  9930. Tools.StartPerformanceCounter = Tools._StartPerformanceCounterDisabled;
  9931. Tools.EndPerformanceCounter = Tools._EndPerformanceCounterDisabled;
  9932. return Tools;
  9933. }());
  9934. BABYLON.Tools = Tools;
  9935. /**
  9936. * This class is used to track a performance counter which is number based.
  9937. * The user has access to many properties which give statistics of different nature
  9938. *
  9939. * The implementer can track two kinds of Performance Counter: time and count
  9940. * 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.
  9941. * 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.
  9942. */
  9943. var PerfCounter = /** @class */ (function () {
  9944. function PerfCounter() {
  9945. this._startMonitoringTime = 0;
  9946. this._min = 0;
  9947. this._max = 0;
  9948. this._average = 0;
  9949. this._lastSecAverage = 0;
  9950. this._current = 0;
  9951. this._totalValueCount = 0;
  9952. this._totalAccumulated = 0;
  9953. this._lastSecAccumulated = 0;
  9954. this._lastSecTime = 0;
  9955. this._lastSecValueCount = 0;
  9956. }
  9957. Object.defineProperty(PerfCounter.prototype, "min", {
  9958. /**
  9959. * Returns the smallest value ever
  9960. */
  9961. get: function () {
  9962. return this._min;
  9963. },
  9964. enumerable: true,
  9965. configurable: true
  9966. });
  9967. Object.defineProperty(PerfCounter.prototype, "max", {
  9968. /**
  9969. * Returns the biggest value ever
  9970. */
  9971. get: function () {
  9972. return this._max;
  9973. },
  9974. enumerable: true,
  9975. configurable: true
  9976. });
  9977. Object.defineProperty(PerfCounter.prototype, "average", {
  9978. /**
  9979. * Returns the average value since the performance counter is running
  9980. */
  9981. get: function () {
  9982. return this._average;
  9983. },
  9984. enumerable: true,
  9985. configurable: true
  9986. });
  9987. Object.defineProperty(PerfCounter.prototype, "lastSecAverage", {
  9988. /**
  9989. * Returns the average value of the last second the counter was monitored
  9990. */
  9991. get: function () {
  9992. return this._lastSecAverage;
  9993. },
  9994. enumerable: true,
  9995. configurable: true
  9996. });
  9997. Object.defineProperty(PerfCounter.prototype, "current", {
  9998. /**
  9999. * Returns the current value
  10000. */
  10001. get: function () {
  10002. return this._current;
  10003. },
  10004. enumerable: true,
  10005. configurable: true
  10006. });
  10007. Object.defineProperty(PerfCounter.prototype, "total", {
  10008. get: function () {
  10009. return this._totalAccumulated;
  10010. },
  10011. enumerable: true,
  10012. configurable: true
  10013. });
  10014. Object.defineProperty(PerfCounter.prototype, "count", {
  10015. get: function () {
  10016. return this._totalValueCount;
  10017. },
  10018. enumerable: true,
  10019. configurable: true
  10020. });
  10021. /**
  10022. * Call this method to start monitoring a new frame.
  10023. * 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.
  10024. */
  10025. PerfCounter.prototype.fetchNewFrame = function () {
  10026. this._totalValueCount++;
  10027. this._current = 0;
  10028. this._lastSecValueCount++;
  10029. };
  10030. /**
  10031. * Call this method to monitor a count of something (e.g. mesh drawn in viewport count)
  10032. * @param newCount the count value to add to the monitored count
  10033. * @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.
  10034. */
  10035. PerfCounter.prototype.addCount = function (newCount, fetchResult) {
  10036. if (!PerfCounter.Enabled) {
  10037. return;
  10038. }
  10039. this._current += newCount;
  10040. if (fetchResult) {
  10041. this._fetchResult();
  10042. }
  10043. };
  10044. /**
  10045. * Start monitoring this performance counter
  10046. */
  10047. PerfCounter.prototype.beginMonitoring = function () {
  10048. if (!PerfCounter.Enabled) {
  10049. return;
  10050. }
  10051. this._startMonitoringTime = Tools.Now;
  10052. };
  10053. /**
  10054. * Compute the time lapsed since the previous beginMonitoring() call.
  10055. * @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
  10056. */
  10057. PerfCounter.prototype.endMonitoring = function (newFrame) {
  10058. if (newFrame === void 0) { newFrame = true; }
  10059. if (!PerfCounter.Enabled) {
  10060. return;
  10061. }
  10062. if (newFrame) {
  10063. this.fetchNewFrame();
  10064. }
  10065. var currentTime = Tools.Now;
  10066. this._current = currentTime - this._startMonitoringTime;
  10067. if (newFrame) {
  10068. this._fetchResult();
  10069. }
  10070. };
  10071. PerfCounter.prototype._fetchResult = function () {
  10072. this._totalAccumulated += this._current;
  10073. this._lastSecAccumulated += this._current;
  10074. // Min/Max update
  10075. this._min = Math.min(this._min, this._current);
  10076. this._max = Math.max(this._max, this._current);
  10077. this._average = this._totalAccumulated / this._totalValueCount;
  10078. // Reset last sec?
  10079. var now = Tools.Now;
  10080. if ((now - this._lastSecTime) > 1000) {
  10081. this._lastSecAverage = this._lastSecAccumulated / this._lastSecValueCount;
  10082. this._lastSecTime = now;
  10083. this._lastSecAccumulated = 0;
  10084. this._lastSecValueCount = 0;
  10085. }
  10086. };
  10087. PerfCounter.Enabled = true;
  10088. return PerfCounter;
  10089. }());
  10090. BABYLON.PerfCounter = PerfCounter;
  10091. /**
  10092. * Use this className as a decorator on a given class definition to add it a name and optionally its module.
  10093. * You can then use the Tools.getClassName(obj) on an instance to retrieve its class name.
  10094. * This method is the only way to get it done in all cases, even if the .js file declaring the class is minified
  10095. * @param name The name of the class, case should be preserved
  10096. * @param module The name of the Module hosting the class, optional, but strongly recommended to specify if possible. Case should be preserved.
  10097. */
  10098. function className(name, module) {
  10099. return function (target) {
  10100. target["__bjsclassName__"] = name;
  10101. target["__bjsmoduleName__"] = (module != null) ? module : null;
  10102. };
  10103. }
  10104. BABYLON.className = className;
  10105. /**
  10106. * An implementation of a loop for asynchronous functions.
  10107. */
  10108. var AsyncLoop = /** @class */ (function () {
  10109. /**
  10110. * Constroctor.
  10111. * @param iterations the number of iterations.
  10112. * @param _fn the function to run each iteration
  10113. * @param _successCallback the callback that will be called upon succesful execution
  10114. * @param offset starting offset.
  10115. */
  10116. function AsyncLoop(iterations, _fn, _successCallback, offset) {
  10117. if (offset === void 0) { offset = 0; }
  10118. this.iterations = iterations;
  10119. this._fn = _fn;
  10120. this._successCallback = _successCallback;
  10121. this.index = offset - 1;
  10122. this._done = false;
  10123. }
  10124. /**
  10125. * Execute the next iteration. Must be called after the last iteration was finished.
  10126. */
  10127. AsyncLoop.prototype.executeNext = function () {
  10128. if (!this._done) {
  10129. if (this.index + 1 < this.iterations) {
  10130. ++this.index;
  10131. this._fn(this);
  10132. }
  10133. else {
  10134. this.breakLoop();
  10135. }
  10136. }
  10137. };
  10138. /**
  10139. * Break the loop and run the success callback.
  10140. */
  10141. AsyncLoop.prototype.breakLoop = function () {
  10142. this._done = true;
  10143. this._successCallback();
  10144. };
  10145. /**
  10146. * Helper function
  10147. */
  10148. AsyncLoop.Run = function (iterations, _fn, _successCallback, offset) {
  10149. if (offset === void 0) { offset = 0; }
  10150. var loop = new AsyncLoop(iterations, _fn, _successCallback, offset);
  10151. loop.executeNext();
  10152. return loop;
  10153. };
  10154. /**
  10155. * A for-loop that will run a given number of iterations synchronous and the rest async.
  10156. * @param iterations total number of iterations
  10157. * @param syncedIterations number of synchronous iterations in each async iteration.
  10158. * @param fn the function to call each iteration.
  10159. * @param callback a success call back that will be called when iterating stops.
  10160. * @param breakFunction a break condition (optional)
  10161. * @param timeout timeout settings for the setTimeout function. default - 0.
  10162. * @constructor
  10163. */
  10164. AsyncLoop.SyncAsyncForLoop = function (iterations, syncedIterations, fn, callback, breakFunction, timeout) {
  10165. if (timeout === void 0) { timeout = 0; }
  10166. AsyncLoop.Run(Math.ceil(iterations / syncedIterations), function (loop) {
  10167. if (breakFunction && breakFunction())
  10168. loop.breakLoop();
  10169. else {
  10170. setTimeout(function () {
  10171. for (var i = 0; i < syncedIterations; ++i) {
  10172. var iteration = (loop.index * syncedIterations) + i;
  10173. if (iteration >= iterations)
  10174. break;
  10175. fn(iteration);
  10176. if (breakFunction && breakFunction()) {
  10177. loop.breakLoop();
  10178. break;
  10179. }
  10180. }
  10181. loop.executeNext();
  10182. }, timeout);
  10183. }
  10184. }, callback);
  10185. };
  10186. return AsyncLoop;
  10187. }());
  10188. BABYLON.AsyncLoop = AsyncLoop;
  10189. })(BABYLON || (BABYLON = {}));
  10190. //# sourceMappingURL=babylon.tools.js.map
  10191. var BABYLON;
  10192. (function (BABYLON) {
  10193. var PromiseStates;
  10194. (function (PromiseStates) {
  10195. PromiseStates[PromiseStates["Pending"] = 0] = "Pending";
  10196. PromiseStates[PromiseStates["Fulfilled"] = 1] = "Fulfilled";
  10197. PromiseStates[PromiseStates["Rejected"] = 2] = "Rejected";
  10198. })(PromiseStates || (PromiseStates = {}));
  10199. var FulFillmentAgregator = /** @class */ (function () {
  10200. function FulFillmentAgregator() {
  10201. this.count = 0;
  10202. this.target = 0;
  10203. this.results = [];
  10204. }
  10205. return FulFillmentAgregator;
  10206. }());
  10207. var InternalPromise = /** @class */ (function () {
  10208. function InternalPromise(resolver) {
  10209. var _this = this;
  10210. this._state = PromiseStates.Pending;
  10211. this._children = new Array();
  10212. this._rejectWasConsumed = false;
  10213. if (!resolver) {
  10214. return;
  10215. }
  10216. try {
  10217. resolver(function (value) {
  10218. _this._resolve(value);
  10219. }, function (reason) {
  10220. _this._reject(reason);
  10221. });
  10222. }
  10223. catch (e) {
  10224. this._reject(e);
  10225. }
  10226. }
  10227. Object.defineProperty(InternalPromise.prototype, "_result", {
  10228. get: function () {
  10229. return this._resultValue;
  10230. },
  10231. set: function (value) {
  10232. this._resultValue = value;
  10233. if (this._parent && this._parent._result === undefined) {
  10234. this._parent._result = value;
  10235. }
  10236. },
  10237. enumerable: true,
  10238. configurable: true
  10239. });
  10240. InternalPromise.prototype.catch = function (onRejected) {
  10241. return this.then(undefined, onRejected);
  10242. };
  10243. InternalPromise.prototype.then = function (onFulfilled, onRejected) {
  10244. var _this = this;
  10245. var newPromise = new InternalPromise();
  10246. newPromise._onFulfilled = onFulfilled;
  10247. newPromise._onRejected = onRejected;
  10248. // Composition
  10249. this._children.push(newPromise);
  10250. newPromise._parent = this;
  10251. if (this._state !== PromiseStates.Pending) {
  10252. BABYLON.Tools.SetImmediate(function () {
  10253. if (_this._state === PromiseStates.Fulfilled || _this._rejectWasConsumed) {
  10254. var returnedValue = newPromise._resolve(_this._result);
  10255. if (returnedValue !== undefined && returnedValue !== null) {
  10256. if (returnedValue._state !== undefined) {
  10257. var returnedPromise = returnedValue;
  10258. newPromise._children.push(returnedPromise);
  10259. returnedPromise._parent = newPromise;
  10260. newPromise = returnedPromise;
  10261. }
  10262. else {
  10263. newPromise._result = returnedValue;
  10264. }
  10265. }
  10266. }
  10267. else {
  10268. newPromise._reject(_this._reason);
  10269. }
  10270. });
  10271. }
  10272. return newPromise;
  10273. };
  10274. InternalPromise.prototype._moveChildren = function (children) {
  10275. var _this = this;
  10276. (_a = this._children).push.apply(_a, children.splice(0, children.length));
  10277. this._children.forEach(function (child) {
  10278. child._parent = _this;
  10279. });
  10280. if (this._state === PromiseStates.Fulfilled) {
  10281. for (var _i = 0, _b = this._children; _i < _b.length; _i++) {
  10282. var child = _b[_i];
  10283. child._resolve(this._result);
  10284. }
  10285. }
  10286. else if (this._state === PromiseStates.Rejected) {
  10287. for (var _c = 0, _d = this._children; _c < _d.length; _c++) {
  10288. var child = _d[_c];
  10289. child._reject(this._reason);
  10290. }
  10291. }
  10292. var _a;
  10293. };
  10294. InternalPromise.prototype._resolve = function (value) {
  10295. try {
  10296. this._state = PromiseStates.Fulfilled;
  10297. var returnedValue = null;
  10298. if (this._onFulfilled) {
  10299. returnedValue = this._onFulfilled(value);
  10300. }
  10301. if (returnedValue !== undefined && returnedValue !== null) {
  10302. if (returnedValue._state !== undefined) {
  10303. // Transmit children
  10304. var returnedPromise = returnedValue;
  10305. returnedPromise._parent = this;
  10306. returnedPromise._moveChildren(this._children);
  10307. value = returnedPromise._result;
  10308. }
  10309. else {
  10310. value = returnedValue;
  10311. }
  10312. }
  10313. this._result = value;
  10314. for (var _i = 0, _a = this._children; _i < _a.length; _i++) {
  10315. var child = _a[_i];
  10316. child._resolve(value);
  10317. }
  10318. this._children.length = 0;
  10319. delete this._onFulfilled;
  10320. delete this._onRejected;
  10321. }
  10322. catch (e) {
  10323. this._reject(e, true);
  10324. }
  10325. };
  10326. InternalPromise.prototype._reject = function (reason, onLocalThrow) {
  10327. if (onLocalThrow === void 0) { onLocalThrow = false; }
  10328. this._state = PromiseStates.Rejected;
  10329. this._reason = reason;
  10330. if (this._onRejected && !onLocalThrow) {
  10331. try {
  10332. this._onRejected(reason);
  10333. this._rejectWasConsumed = true;
  10334. }
  10335. catch (e) {
  10336. reason = e;
  10337. }
  10338. }
  10339. for (var _i = 0, _a = this._children; _i < _a.length; _i++) {
  10340. var child = _a[_i];
  10341. if (this._rejectWasConsumed) {
  10342. child._resolve(null);
  10343. }
  10344. else {
  10345. child._reject(reason);
  10346. }
  10347. }
  10348. this._children.length = 0;
  10349. delete this._onFulfilled;
  10350. delete this._onRejected;
  10351. };
  10352. InternalPromise.resolve = function (value) {
  10353. var newPromise = new InternalPromise();
  10354. newPromise._resolve(value);
  10355. return newPromise;
  10356. };
  10357. InternalPromise._RegisterForFulfillment = function (promise, agregator, index) {
  10358. promise.then(function (value) {
  10359. agregator.results[index] = value;
  10360. agregator.count++;
  10361. if (agregator.count === agregator.target) {
  10362. agregator.rootPromise._resolve(agregator.results);
  10363. }
  10364. return null;
  10365. }, function (reason) {
  10366. if (agregator.rootPromise._state !== PromiseStates.Rejected) {
  10367. agregator.rootPromise._reject(reason);
  10368. }
  10369. });
  10370. };
  10371. InternalPromise.all = function (promises) {
  10372. var newPromise = new InternalPromise();
  10373. var agregator = new FulFillmentAgregator();
  10374. agregator.target = promises.length;
  10375. agregator.rootPromise = newPromise;
  10376. if (promises.length) {
  10377. for (var index = 0; index < promises.length; index++) {
  10378. InternalPromise._RegisterForFulfillment(promises[index], agregator, index);
  10379. }
  10380. }
  10381. else {
  10382. newPromise._resolve([]);
  10383. }
  10384. return newPromise;
  10385. };
  10386. InternalPromise.race = function (promises) {
  10387. var newPromise = new InternalPromise();
  10388. if (promises.length) {
  10389. for (var _i = 0, promises_1 = promises; _i < promises_1.length; _i++) {
  10390. var promise = promises_1[_i];
  10391. promise.then(function (value) {
  10392. if (newPromise) {
  10393. newPromise._resolve(value);
  10394. newPromise = null;
  10395. }
  10396. return null;
  10397. }, function (reason) {
  10398. if (newPromise) {
  10399. newPromise._reject(reason);
  10400. newPromise = null;
  10401. }
  10402. });
  10403. }
  10404. }
  10405. return newPromise;
  10406. };
  10407. return InternalPromise;
  10408. }());
  10409. /**
  10410. * Helper class that provides a small promise polyfill
  10411. */
  10412. var PromisePolyfill = /** @class */ (function () {
  10413. function PromisePolyfill() {
  10414. }
  10415. /**
  10416. * Static function used to check if the polyfill is required
  10417. * If this is the case then the function will inject the polyfill to window.Promise
  10418. * @param force defines a boolean used to force the injection (mostly for testing purposes)
  10419. */
  10420. PromisePolyfill.Apply = function (force) {
  10421. if (force === void 0) { force = false; }
  10422. if (force || typeof Promise === 'undefined') {
  10423. var root = window;
  10424. root.Promise = InternalPromise;
  10425. }
  10426. };
  10427. return PromisePolyfill;
  10428. }());
  10429. BABYLON.PromisePolyfill = PromisePolyfill;
  10430. })(BABYLON || (BABYLON = {}));
  10431. //# sourceMappingURL=babylon.promise.js.map
  10432. /// <reference path="../../../dist/preview release/babylon.d.ts" />
  10433. var BABYLON;
  10434. (function (BABYLON) {
  10435. /**
  10436. * Helper class to push actions to a pool of workers.
  10437. */
  10438. var WorkerPool = /** @class */ (function () {
  10439. /**
  10440. * Constructor
  10441. * @param workers Array of workers to use for actions
  10442. */
  10443. function WorkerPool(workers) {
  10444. this._pendingActions = new Array();
  10445. this._workerInfos = workers.map(function (worker) { return ({
  10446. worker: worker,
  10447. active: false
  10448. }); });
  10449. }
  10450. /**
  10451. * Terminates all workers and clears any pending actions.
  10452. */
  10453. WorkerPool.prototype.dispose = function () {
  10454. for (var _i = 0, _a = this._workerInfos; _i < _a.length; _i++) {
  10455. var workerInfo = _a[_i];
  10456. workerInfo.worker.terminate();
  10457. }
  10458. delete this._workerInfos;
  10459. delete this._pendingActions;
  10460. };
  10461. /**
  10462. * Pushes an action to the worker pool. If all the workers are active, the action will be
  10463. * pended until a worker has completed its action.
  10464. * @param action The action to perform. Call onComplete when the action is complete.
  10465. */
  10466. WorkerPool.prototype.push = function (action) {
  10467. for (var _i = 0, _a = this._workerInfos; _i < _a.length; _i++) {
  10468. var workerInfo = _a[_i];
  10469. if (!workerInfo.active) {
  10470. this._execute(workerInfo, action);
  10471. return;
  10472. }
  10473. }
  10474. this._pendingActions.push(action);
  10475. };
  10476. WorkerPool.prototype._execute = function (workerInfo, action) {
  10477. var _this = this;
  10478. workerInfo.active = true;
  10479. action(workerInfo.worker, function () {
  10480. workerInfo.active = false;
  10481. var nextAction = _this._pendingActions.shift();
  10482. if (nextAction) {
  10483. _this._execute(workerInfo, nextAction);
  10484. }
  10485. });
  10486. };
  10487. return WorkerPool;
  10488. }());
  10489. BABYLON.WorkerPool = WorkerPool;
  10490. })(BABYLON || (BABYLON = {}));
  10491. //# sourceMappingURL=babylon.workerPool.js.map
  10492. var BABYLON;
  10493. (function (BABYLON) {
  10494. /**
  10495. * @hidden
  10496. **/
  10497. var _AlphaState = /** @class */ (function () {
  10498. /**
  10499. * Initializes the state.
  10500. */
  10501. function _AlphaState() {
  10502. this._isAlphaBlendDirty = false;
  10503. this._isBlendFunctionParametersDirty = false;
  10504. this._isBlendEquationParametersDirty = false;
  10505. this._isBlendConstantsDirty = false;
  10506. this._alphaBlend = false;
  10507. this._blendFunctionParameters = new Array(4);
  10508. this._blendEquationParameters = new Array(2);
  10509. this._blendConstants = new Array(4);
  10510. this.reset();
  10511. }
  10512. Object.defineProperty(_AlphaState.prototype, "isDirty", {
  10513. get: function () {
  10514. return this._isAlphaBlendDirty || this._isBlendFunctionParametersDirty;
  10515. },
  10516. enumerable: true,
  10517. configurable: true
  10518. });
  10519. Object.defineProperty(_AlphaState.prototype, "alphaBlend", {
  10520. get: function () {
  10521. return this._alphaBlend;
  10522. },
  10523. set: function (value) {
  10524. if (this._alphaBlend === value) {
  10525. return;
  10526. }
  10527. this._alphaBlend = value;
  10528. this._isAlphaBlendDirty = true;
  10529. },
  10530. enumerable: true,
  10531. configurable: true
  10532. });
  10533. _AlphaState.prototype.setAlphaBlendConstants = function (r, g, b, a) {
  10534. if (this._blendConstants[0] === r &&
  10535. this._blendConstants[1] === g &&
  10536. this._blendConstants[2] === b &&
  10537. this._blendConstants[3] === a) {
  10538. return;
  10539. }
  10540. this._blendConstants[0] = r;
  10541. this._blendConstants[1] = g;
  10542. this._blendConstants[2] = b;
  10543. this._blendConstants[3] = a;
  10544. this._isBlendConstantsDirty = true;
  10545. };
  10546. _AlphaState.prototype.setAlphaBlendFunctionParameters = function (value0, value1, value2, value3) {
  10547. if (this._blendFunctionParameters[0] === value0 &&
  10548. this._blendFunctionParameters[1] === value1 &&
  10549. this._blendFunctionParameters[2] === value2 &&
  10550. this._blendFunctionParameters[3] === value3) {
  10551. return;
  10552. }
  10553. this._blendFunctionParameters[0] = value0;
  10554. this._blendFunctionParameters[1] = value1;
  10555. this._blendFunctionParameters[2] = value2;
  10556. this._blendFunctionParameters[3] = value3;
  10557. this._isBlendFunctionParametersDirty = true;
  10558. };
  10559. _AlphaState.prototype.setAlphaEquationParameters = function (rgb, alpha) {
  10560. if (this._blendEquationParameters[0] === rgb &&
  10561. this._blendEquationParameters[1] === alpha) {
  10562. return;
  10563. }
  10564. this._blendEquationParameters[0] = rgb;
  10565. this._blendEquationParameters[1] = alpha;
  10566. this._isBlendEquationParametersDirty = true;
  10567. };
  10568. _AlphaState.prototype.reset = function () {
  10569. this._alphaBlend = false;
  10570. this._blendFunctionParameters[0] = null;
  10571. this._blendFunctionParameters[1] = null;
  10572. this._blendFunctionParameters[2] = null;
  10573. this._blendFunctionParameters[3] = null;
  10574. this._blendEquationParameters[0] = null;
  10575. this._blendEquationParameters[1] = null;
  10576. this._blendConstants[0] = null;
  10577. this._blendConstants[1] = null;
  10578. this._blendConstants[2] = null;
  10579. this._blendConstants[3] = null;
  10580. this._isAlphaBlendDirty = true;
  10581. this._isBlendFunctionParametersDirty = false;
  10582. this._isBlendEquationParametersDirty = false;
  10583. this._isBlendConstantsDirty = false;
  10584. };
  10585. _AlphaState.prototype.apply = function (gl) {
  10586. if (!this.isDirty) {
  10587. return;
  10588. }
  10589. // Alpha blend
  10590. if (this._isAlphaBlendDirty) {
  10591. if (this._alphaBlend) {
  10592. gl.enable(gl.BLEND);
  10593. }
  10594. else {
  10595. gl.disable(gl.BLEND);
  10596. }
  10597. this._isAlphaBlendDirty = false;
  10598. }
  10599. // Alpha function
  10600. if (this._isBlendFunctionParametersDirty) {
  10601. gl.blendFuncSeparate(this._blendFunctionParameters[0], this._blendFunctionParameters[1], this._blendFunctionParameters[2], this._blendFunctionParameters[3]);
  10602. this._isBlendFunctionParametersDirty = false;
  10603. }
  10604. // Alpha equation
  10605. if (this._isBlendEquationParametersDirty) {
  10606. gl.blendEquationSeparate(this._isBlendEquationParametersDirty[0], this._isBlendEquationParametersDirty[1]);
  10607. this._isBlendEquationParametersDirty = false;
  10608. }
  10609. // Constants
  10610. if (this._isBlendConstantsDirty) {
  10611. gl.blendColor(this._blendConstants[0], this._blendConstants[1], this._blendConstants[2], this._blendConstants[3]);
  10612. this._isBlendConstantsDirty = false;
  10613. }
  10614. };
  10615. return _AlphaState;
  10616. }());
  10617. BABYLON._AlphaState = _AlphaState;
  10618. })(BABYLON || (BABYLON = {}));
  10619. //# sourceMappingURL=babylon.alphaCullingState.js.map
  10620. var BABYLON;
  10621. (function (BABYLON) {
  10622. /**
  10623. * @hidden
  10624. **/
  10625. var _DepthCullingState = /** @class */ (function () {
  10626. /**
  10627. * Initializes the state.
  10628. */
  10629. function _DepthCullingState() {
  10630. this._isDepthTestDirty = false;
  10631. this._isDepthMaskDirty = false;
  10632. this._isDepthFuncDirty = false;
  10633. this._isCullFaceDirty = false;
  10634. this._isCullDirty = false;
  10635. this._isZOffsetDirty = false;
  10636. this._isFrontFaceDirty = false;
  10637. this.reset();
  10638. }
  10639. Object.defineProperty(_DepthCullingState.prototype, "isDirty", {
  10640. get: function () {
  10641. return this._isDepthFuncDirty || this._isDepthTestDirty || this._isDepthMaskDirty || this._isCullFaceDirty || this._isCullDirty || this._isZOffsetDirty || this._isFrontFaceDirty;
  10642. },
  10643. enumerable: true,
  10644. configurable: true
  10645. });
  10646. Object.defineProperty(_DepthCullingState.prototype, "zOffset", {
  10647. get: function () {
  10648. return this._zOffset;
  10649. },
  10650. set: function (value) {
  10651. if (this._zOffset === value) {
  10652. return;
  10653. }
  10654. this._zOffset = value;
  10655. this._isZOffsetDirty = true;
  10656. },
  10657. enumerable: true,
  10658. configurable: true
  10659. });
  10660. Object.defineProperty(_DepthCullingState.prototype, "cullFace", {
  10661. get: function () {
  10662. return this._cullFace;
  10663. },
  10664. set: function (value) {
  10665. if (this._cullFace === value) {
  10666. return;
  10667. }
  10668. this._cullFace = value;
  10669. this._isCullFaceDirty = true;
  10670. },
  10671. enumerable: true,
  10672. configurable: true
  10673. });
  10674. Object.defineProperty(_DepthCullingState.prototype, "cull", {
  10675. get: function () {
  10676. return this._cull;
  10677. },
  10678. set: function (value) {
  10679. if (this._cull === value) {
  10680. return;
  10681. }
  10682. this._cull = value;
  10683. this._isCullDirty = true;
  10684. },
  10685. enumerable: true,
  10686. configurable: true
  10687. });
  10688. Object.defineProperty(_DepthCullingState.prototype, "depthFunc", {
  10689. get: function () {
  10690. return this._depthFunc;
  10691. },
  10692. set: function (value) {
  10693. if (this._depthFunc === value) {
  10694. return;
  10695. }
  10696. this._depthFunc = value;
  10697. this._isDepthFuncDirty = true;
  10698. },
  10699. enumerable: true,
  10700. configurable: true
  10701. });
  10702. Object.defineProperty(_DepthCullingState.prototype, "depthMask", {
  10703. get: function () {
  10704. return this._depthMask;
  10705. },
  10706. set: function (value) {
  10707. if (this._depthMask === value) {
  10708. return;
  10709. }
  10710. this._depthMask = value;
  10711. this._isDepthMaskDirty = true;
  10712. },
  10713. enumerable: true,
  10714. configurable: true
  10715. });
  10716. Object.defineProperty(_DepthCullingState.prototype, "depthTest", {
  10717. get: function () {
  10718. return this._depthTest;
  10719. },
  10720. set: function (value) {
  10721. if (this._depthTest === value) {
  10722. return;
  10723. }
  10724. this._depthTest = value;
  10725. this._isDepthTestDirty = true;
  10726. },
  10727. enumerable: true,
  10728. configurable: true
  10729. });
  10730. Object.defineProperty(_DepthCullingState.prototype, "frontFace", {
  10731. get: function () {
  10732. return this._frontFace;
  10733. },
  10734. set: function (value) {
  10735. if (this._frontFace === value) {
  10736. return;
  10737. }
  10738. this._frontFace = value;
  10739. this._isFrontFaceDirty = true;
  10740. },
  10741. enumerable: true,
  10742. configurable: true
  10743. });
  10744. _DepthCullingState.prototype.reset = function () {
  10745. this._depthMask = true;
  10746. this._depthTest = true;
  10747. this._depthFunc = null;
  10748. this._cullFace = null;
  10749. this._cull = null;
  10750. this._zOffset = 0;
  10751. this._frontFace = null;
  10752. this._isDepthTestDirty = true;
  10753. this._isDepthMaskDirty = true;
  10754. this._isDepthFuncDirty = false;
  10755. this._isCullFaceDirty = false;
  10756. this._isCullDirty = false;
  10757. this._isZOffsetDirty = false;
  10758. this._isFrontFaceDirty = false;
  10759. };
  10760. _DepthCullingState.prototype.apply = function (gl) {
  10761. if (!this.isDirty) {
  10762. return;
  10763. }
  10764. // Cull
  10765. if (this._isCullDirty) {
  10766. if (this.cull) {
  10767. gl.enable(gl.CULL_FACE);
  10768. }
  10769. else {
  10770. gl.disable(gl.CULL_FACE);
  10771. }
  10772. this._isCullDirty = false;
  10773. }
  10774. // Cull face
  10775. if (this._isCullFaceDirty) {
  10776. gl.cullFace(this.cullFace);
  10777. this._isCullFaceDirty = false;
  10778. }
  10779. // Depth mask
  10780. if (this._isDepthMaskDirty) {
  10781. gl.depthMask(this.depthMask);
  10782. this._isDepthMaskDirty = false;
  10783. }
  10784. // Depth test
  10785. if (this._isDepthTestDirty) {
  10786. if (this.depthTest) {
  10787. gl.enable(gl.DEPTH_TEST);
  10788. }
  10789. else {
  10790. gl.disable(gl.DEPTH_TEST);
  10791. }
  10792. this._isDepthTestDirty = false;
  10793. }
  10794. // Depth func
  10795. if (this._isDepthFuncDirty) {
  10796. gl.depthFunc(this.depthFunc);
  10797. this._isDepthFuncDirty = false;
  10798. }
  10799. // zOffset
  10800. if (this._isZOffsetDirty) {
  10801. if (this.zOffset) {
  10802. gl.enable(gl.POLYGON_OFFSET_FILL);
  10803. gl.polygonOffset(this.zOffset, 0);
  10804. }
  10805. else {
  10806. gl.disable(gl.POLYGON_OFFSET_FILL);
  10807. }
  10808. this._isZOffsetDirty = false;
  10809. }
  10810. // Front face
  10811. if (this._isFrontFaceDirty) {
  10812. gl.frontFace(this.frontFace);
  10813. this._isFrontFaceDirty = false;
  10814. }
  10815. };
  10816. return _DepthCullingState;
  10817. }());
  10818. BABYLON._DepthCullingState = _DepthCullingState;
  10819. })(BABYLON || (BABYLON = {}));
  10820. //# sourceMappingURL=babylon.depthCullingState.js.map
  10821. var BABYLON;
  10822. (function (BABYLON) {
  10823. /**
  10824. * @hidden
  10825. **/
  10826. var _StencilState = /** @class */ (function () {
  10827. function _StencilState() {
  10828. this._isStencilTestDirty = false;
  10829. this._isStencilMaskDirty = false;
  10830. this._isStencilFuncDirty = false;
  10831. this._isStencilOpDirty = false;
  10832. this.reset();
  10833. }
  10834. Object.defineProperty(_StencilState.prototype, "isDirty", {
  10835. get: function () {
  10836. return this._isStencilTestDirty || this._isStencilMaskDirty || this._isStencilFuncDirty || this._isStencilOpDirty;
  10837. },
  10838. enumerable: true,
  10839. configurable: true
  10840. });
  10841. Object.defineProperty(_StencilState.prototype, "stencilFunc", {
  10842. get: function () {
  10843. return this._stencilFunc;
  10844. },
  10845. set: function (value) {
  10846. if (this._stencilFunc === value) {
  10847. return;
  10848. }
  10849. this._stencilFunc = value;
  10850. this._isStencilFuncDirty = true;
  10851. },
  10852. enumerable: true,
  10853. configurable: true
  10854. });
  10855. Object.defineProperty(_StencilState.prototype, "stencilFuncRef", {
  10856. get: function () {
  10857. return this._stencilFuncRef;
  10858. },
  10859. set: function (value) {
  10860. if (this._stencilFuncRef === value) {
  10861. return;
  10862. }
  10863. this._stencilFuncRef = value;
  10864. this._isStencilFuncDirty = true;
  10865. },
  10866. enumerable: true,
  10867. configurable: true
  10868. });
  10869. Object.defineProperty(_StencilState.prototype, "stencilFuncMask", {
  10870. get: function () {
  10871. return this._stencilFuncMask;
  10872. },
  10873. set: function (value) {
  10874. if (this._stencilFuncMask === value) {
  10875. return;
  10876. }
  10877. this._stencilFuncMask = value;
  10878. this._isStencilFuncDirty = true;
  10879. },
  10880. enumerable: true,
  10881. configurable: true
  10882. });
  10883. Object.defineProperty(_StencilState.prototype, "stencilOpStencilFail", {
  10884. get: function () {
  10885. return this._stencilOpStencilFail;
  10886. },
  10887. set: function (value) {
  10888. if (this._stencilOpStencilFail === value) {
  10889. return;
  10890. }
  10891. this._stencilOpStencilFail = value;
  10892. this._isStencilOpDirty = true;
  10893. },
  10894. enumerable: true,
  10895. configurable: true
  10896. });
  10897. Object.defineProperty(_StencilState.prototype, "stencilOpDepthFail", {
  10898. get: function () {
  10899. return this._stencilOpDepthFail;
  10900. },
  10901. set: function (value) {
  10902. if (this._stencilOpDepthFail === value) {
  10903. return;
  10904. }
  10905. this._stencilOpDepthFail = value;
  10906. this._isStencilOpDirty = true;
  10907. },
  10908. enumerable: true,
  10909. configurable: true
  10910. });
  10911. Object.defineProperty(_StencilState.prototype, "stencilOpStencilDepthPass", {
  10912. get: function () {
  10913. return this._stencilOpStencilDepthPass;
  10914. },
  10915. set: function (value) {
  10916. if (this._stencilOpStencilDepthPass === value) {
  10917. return;
  10918. }
  10919. this._stencilOpStencilDepthPass = value;
  10920. this._isStencilOpDirty = true;
  10921. },
  10922. enumerable: true,
  10923. configurable: true
  10924. });
  10925. Object.defineProperty(_StencilState.prototype, "stencilMask", {
  10926. get: function () {
  10927. return this._stencilMask;
  10928. },
  10929. set: function (value) {
  10930. if (this._stencilMask === value) {
  10931. return;
  10932. }
  10933. this._stencilMask = value;
  10934. this._isStencilMaskDirty = true;
  10935. },
  10936. enumerable: true,
  10937. configurable: true
  10938. });
  10939. Object.defineProperty(_StencilState.prototype, "stencilTest", {
  10940. get: function () {
  10941. return this._stencilTest;
  10942. },
  10943. set: function (value) {
  10944. if (this._stencilTest === value) {
  10945. return;
  10946. }
  10947. this._stencilTest = value;
  10948. this._isStencilTestDirty = true;
  10949. },
  10950. enumerable: true,
  10951. configurable: true
  10952. });
  10953. _StencilState.prototype.reset = function () {
  10954. this._stencilTest = false;
  10955. this._stencilMask = 0xFF;
  10956. this._stencilFunc = BABYLON.Engine.ALWAYS;
  10957. this._stencilFuncRef = 1;
  10958. this._stencilFuncMask = 0xFF;
  10959. this._stencilOpStencilFail = BABYLON.Engine.KEEP;
  10960. this._stencilOpDepthFail = BABYLON.Engine.KEEP;
  10961. this._stencilOpStencilDepthPass = BABYLON.Engine.REPLACE;
  10962. this._isStencilTestDirty = true;
  10963. this._isStencilMaskDirty = true;
  10964. this._isStencilFuncDirty = true;
  10965. this._isStencilOpDirty = true;
  10966. };
  10967. _StencilState.prototype.apply = function (gl) {
  10968. if (!this.isDirty) {
  10969. return;
  10970. }
  10971. // Stencil test
  10972. if (this._isStencilTestDirty) {
  10973. if (this.stencilTest) {
  10974. gl.enable(gl.STENCIL_TEST);
  10975. }
  10976. else {
  10977. gl.disable(gl.STENCIL_TEST);
  10978. }
  10979. this._isStencilTestDirty = false;
  10980. }
  10981. // Stencil mask
  10982. if (this._isStencilMaskDirty) {
  10983. gl.stencilMask(this.stencilMask);
  10984. this._isStencilMaskDirty = false;
  10985. }
  10986. // Stencil func
  10987. if (this._isStencilFuncDirty) {
  10988. gl.stencilFunc(this.stencilFunc, this.stencilFuncRef, this.stencilFuncMask);
  10989. this._isStencilFuncDirty = false;
  10990. }
  10991. // Stencil op
  10992. if (this._isStencilOpDirty) {
  10993. gl.stencilOp(this.stencilOpStencilFail, this.stencilOpDepthFail, this.stencilOpStencilDepthPass);
  10994. this._isStencilOpDirty = false;
  10995. }
  10996. };
  10997. return _StencilState;
  10998. }());
  10999. BABYLON._StencilState = _StencilState;
  11000. })(BABYLON || (BABYLON = {}));
  11001. //# sourceMappingURL=babylon.stencilState.js.map
  11002. var __assign = (this && this.__assign) || Object.assign || function(t) {
  11003. for (var s, i = 1, n = arguments.length; i < n; i++) {
  11004. s = arguments[i];
  11005. for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
  11006. t[p] = s[p];
  11007. }
  11008. return t;
  11009. };
  11010. var BABYLON;
  11011. (function (BABYLON) {
  11012. var compileShader = function (gl, source, type, defines, shaderVersion) {
  11013. return compileRawShader(gl, shaderVersion + (defines ? defines + "\n" : "") + source, type);
  11014. };
  11015. var compileRawShader = function (gl, source, type) {
  11016. var shader = gl.createShader(type === "vertex" ? gl.VERTEX_SHADER : gl.FRAGMENT_SHADER);
  11017. gl.shaderSource(shader, source);
  11018. gl.compileShader(shader);
  11019. if (!gl.getShaderParameter(shader, gl.COMPILE_STATUS)) {
  11020. var log = gl.getShaderInfoLog(shader);
  11021. if (log) {
  11022. throw new Error(log);
  11023. }
  11024. }
  11025. if (!shader) {
  11026. throw new Error("Something went wrong while compile the shader.");
  11027. }
  11028. return shader;
  11029. };
  11030. var getSamplingParameters = function (samplingMode, generateMipMaps, gl) {
  11031. var magFilter = gl.NEAREST;
  11032. var minFilter = gl.NEAREST;
  11033. switch (samplingMode) {
  11034. case BABYLON.Texture.BILINEAR_SAMPLINGMODE:
  11035. magFilter = gl.LINEAR;
  11036. if (generateMipMaps) {
  11037. minFilter = gl.LINEAR_MIPMAP_NEAREST;
  11038. }
  11039. else {
  11040. minFilter = gl.LINEAR;
  11041. }
  11042. break;
  11043. case BABYLON.Texture.TRILINEAR_SAMPLINGMODE:
  11044. magFilter = gl.LINEAR;
  11045. if (generateMipMaps) {
  11046. minFilter = gl.LINEAR_MIPMAP_LINEAR;
  11047. }
  11048. else {
  11049. minFilter = gl.LINEAR;
  11050. }
  11051. break;
  11052. case BABYLON.Texture.NEAREST_SAMPLINGMODE:
  11053. magFilter = gl.NEAREST;
  11054. if (generateMipMaps) {
  11055. minFilter = gl.NEAREST_MIPMAP_LINEAR;
  11056. }
  11057. else {
  11058. minFilter = gl.NEAREST;
  11059. }
  11060. break;
  11061. case BABYLON.Texture.NEAREST_NEAREST_MIPNEAREST:
  11062. magFilter = gl.NEAREST;
  11063. if (generateMipMaps) {
  11064. minFilter = gl.NEAREST_MIPMAP_NEAREST;
  11065. }
  11066. else {
  11067. minFilter = gl.NEAREST;
  11068. }
  11069. break;
  11070. case BABYLON.Texture.NEAREST_LINEAR_MIPNEAREST:
  11071. magFilter = gl.NEAREST;
  11072. if (generateMipMaps) {
  11073. minFilter = gl.LINEAR_MIPMAP_NEAREST;
  11074. }
  11075. else {
  11076. minFilter = gl.LINEAR;
  11077. }
  11078. break;
  11079. case BABYLON.Texture.NEAREST_LINEAR_MIPLINEAR:
  11080. magFilter = gl.NEAREST;
  11081. if (generateMipMaps) {
  11082. minFilter = gl.LINEAR_MIPMAP_LINEAR;
  11083. }
  11084. else {
  11085. minFilter = gl.LINEAR;
  11086. }
  11087. break;
  11088. case BABYLON.Texture.NEAREST_LINEAR:
  11089. magFilter = gl.NEAREST;
  11090. minFilter = gl.LINEAR;
  11091. break;
  11092. case BABYLON.Texture.NEAREST_NEAREST:
  11093. magFilter = gl.NEAREST;
  11094. minFilter = gl.NEAREST;
  11095. break;
  11096. case BABYLON.Texture.LINEAR_NEAREST_MIPNEAREST:
  11097. magFilter = gl.LINEAR;
  11098. if (generateMipMaps) {
  11099. minFilter = gl.NEAREST_MIPMAP_NEAREST;
  11100. }
  11101. else {
  11102. minFilter = gl.NEAREST;
  11103. }
  11104. break;
  11105. case BABYLON.Texture.LINEAR_NEAREST_MIPLINEAR:
  11106. magFilter = gl.LINEAR;
  11107. if (generateMipMaps) {
  11108. minFilter = gl.NEAREST_MIPMAP_LINEAR;
  11109. }
  11110. else {
  11111. minFilter = gl.NEAREST;
  11112. }
  11113. break;
  11114. case BABYLON.Texture.LINEAR_LINEAR:
  11115. magFilter = gl.LINEAR;
  11116. minFilter = gl.LINEAR;
  11117. break;
  11118. case BABYLON.Texture.LINEAR_NEAREST:
  11119. magFilter = gl.LINEAR;
  11120. minFilter = gl.NEAREST;
  11121. break;
  11122. }
  11123. return {
  11124. min: minFilter,
  11125. mag: magFilter
  11126. };
  11127. };
  11128. var partialLoadImg = function (url, index, loadedImages, scene, onfinish, onErrorCallBack) {
  11129. if (onErrorCallBack === void 0) { onErrorCallBack = null; }
  11130. var img;
  11131. var onload = function () {
  11132. loadedImages[index] = img;
  11133. loadedImages._internalCount++;
  11134. if (scene) {
  11135. scene._removePendingData(img);
  11136. }
  11137. if (loadedImages._internalCount === 6) {
  11138. onfinish(loadedImages);
  11139. }
  11140. };
  11141. var onerror = function (message, exception) {
  11142. if (scene) {
  11143. scene._removePendingData(img);
  11144. }
  11145. if (onErrorCallBack) {
  11146. onErrorCallBack(message, exception);
  11147. }
  11148. };
  11149. img = BABYLON.Tools.LoadImage(url, onload, onerror, scene ? scene.database : null);
  11150. if (scene) {
  11151. scene._addPendingData(img);
  11152. }
  11153. };
  11154. var cascadeLoadImgs = function (rootUrl, scene, onfinish, files, onError) {
  11155. if (onError === void 0) { onError = null; }
  11156. var loadedImages = [];
  11157. loadedImages._internalCount = 0;
  11158. for (var index = 0; index < 6; index++) {
  11159. partialLoadImg(files[index], index, loadedImages, scene, onfinish, onError);
  11160. }
  11161. };
  11162. var BufferPointer = /** @class */ (function () {
  11163. function BufferPointer() {
  11164. }
  11165. return BufferPointer;
  11166. }());
  11167. /**
  11168. * Interface for attribute information associated with buffer instanciation
  11169. */
  11170. var InstancingAttributeInfo = /** @class */ (function () {
  11171. function InstancingAttributeInfo() {
  11172. }
  11173. return InstancingAttributeInfo;
  11174. }());
  11175. BABYLON.InstancingAttributeInfo = InstancingAttributeInfo;
  11176. /**
  11177. * Define options used to create a render target texture
  11178. */
  11179. var RenderTargetCreationOptions = /** @class */ (function () {
  11180. function RenderTargetCreationOptions() {
  11181. }
  11182. return RenderTargetCreationOptions;
  11183. }());
  11184. BABYLON.RenderTargetCreationOptions = RenderTargetCreationOptions;
  11185. /**
  11186. * Define options used to create a depth texture
  11187. */
  11188. var DepthTextureCreationOptions = /** @class */ (function () {
  11189. function DepthTextureCreationOptions() {
  11190. }
  11191. return DepthTextureCreationOptions;
  11192. }());
  11193. BABYLON.DepthTextureCreationOptions = DepthTextureCreationOptions;
  11194. /**
  11195. * Class used to describe the capabilities of the engine relatively to the current browser
  11196. */
  11197. var EngineCapabilities = /** @class */ (function () {
  11198. function EngineCapabilities() {
  11199. }
  11200. return EngineCapabilities;
  11201. }());
  11202. BABYLON.EngineCapabilities = EngineCapabilities;
  11203. /**
  11204. * The engine class is responsible for interfacing with all lower-level APIs such as WebGL and Audio
  11205. */
  11206. var Engine = /** @class */ (function () {
  11207. /**
  11208. * Creates a new engine
  11209. * @param canvasOrContext defines the canvas or WebGL context to use for rendering
  11210. * @param antialias defines enable antialiasing (default: false)
  11211. * @param options defines further options to be sent to the getContext() function
  11212. * @param adaptToDeviceRatio defines whether to adapt to the device's viewport characteristics (default: false)
  11213. */
  11214. function Engine(canvasOrContext, antialias, options, adaptToDeviceRatio) {
  11215. if (adaptToDeviceRatio === void 0) { adaptToDeviceRatio = false; }
  11216. var _this = this;
  11217. // Public members
  11218. /**
  11219. * Gets or sets a boolean that indicates if textures must be forced to power of 2 size even if not required
  11220. */
  11221. this.forcePOTTextures = false;
  11222. /**
  11223. * Gets a boolean indicating if the engine is currently rendering in fullscreen mode
  11224. */
  11225. this.isFullscreen = false;
  11226. /**
  11227. * Gets a boolean indicating if the pointer is currently locked
  11228. */
  11229. this.isPointerLock = false;
  11230. /**
  11231. * Gets or sets a boolean indicating if back faces must be culled (true by default)
  11232. */
  11233. this.cullBackFaces = true;
  11234. /**
  11235. * Gets or sets a boolean indicating if the engine must keep rendering even if the window is not in foregroun
  11236. */
  11237. this.renderEvenInBackground = true;
  11238. /**
  11239. * Gets or sets a boolean indicating that cache can be kept between frames
  11240. */
  11241. this.preventCacheWipeBetweenFrames = false;
  11242. /**
  11243. * Gets or sets a boolean to enable/disable IndexedDB support and avoid XHR on .manifest
  11244. **/
  11245. this.enableOfflineSupport = false;
  11246. /**
  11247. * Gets or sets a boolean to enable/disable checking manifest if IndexedDB support is enabled (Babylon.js will always consider the database is up to date)
  11248. **/
  11249. this.disableManifestCheck = false;
  11250. /**
  11251. * Gets the list of created scenes
  11252. */
  11253. this.scenes = new Array();
  11254. /**
  11255. * Gets the list of created postprocesses
  11256. */
  11257. this.postProcesses = new Array();
  11258. // Observables
  11259. /**
  11260. * Observable event triggered each time the rendering canvas is resized
  11261. */
  11262. this.onResizeObservable = new BABYLON.Observable();
  11263. /**
  11264. * Observable event triggered each time the canvas loses focus
  11265. */
  11266. this.onCanvasBlurObservable = new BABYLON.Observable();
  11267. /**
  11268. * Observable event triggered each time the canvas gains focus
  11269. */
  11270. this.onCanvasFocusObservable = new BABYLON.Observable();
  11271. /**
  11272. * Observable event triggered each time the canvas receives pointerout event
  11273. */
  11274. this.onCanvasPointerOutObservable = new BABYLON.Observable();
  11275. /**
  11276. * Observable event triggered before each texture is initialized
  11277. */
  11278. this.onBeforeTextureInitObservable = new BABYLON.Observable();
  11279. //WebVR
  11280. this._vrDisplay = undefined;
  11281. this._vrSupported = false;
  11282. this._vrExclusivePointerMode = false;
  11283. // Uniform buffers list
  11284. /**
  11285. * Gets or sets a boolean indicating that uniform buffers must be disabled even if they are supported
  11286. */
  11287. this.disableUniformBuffers = false;
  11288. /** @hidden */
  11289. this._uniformBuffers = new Array();
  11290. // Observables
  11291. /**
  11292. * Observable raised when the engine begins a new frame
  11293. */
  11294. this.onBeginFrameObservable = new BABYLON.Observable();
  11295. /**
  11296. * Observable raised when the engine ends the current frame
  11297. */
  11298. this.onEndFrameObservable = new BABYLON.Observable();
  11299. /**
  11300. * Observable raised when the engine is about to compile a shader
  11301. */
  11302. this.onBeforeShaderCompilationObservable = new BABYLON.Observable();
  11303. /**
  11304. * Observable raised when the engine has jsut compiled a shader
  11305. */
  11306. this.onAfterShaderCompilationObservable = new BABYLON.Observable();
  11307. this._windowIsBackground = false;
  11308. this._webGLVersion = 1.0;
  11309. /** @hidden */
  11310. this._badOS = false;
  11311. /** @hidden */
  11312. this._badDesktopOS = false;
  11313. /**
  11314. * Gets or sets a value indicating if we want to disable texture binding optmization.
  11315. * This could be required on some buggy drivers which wants to have textures bound in a progressive order.
  11316. * By default Babylon.js will try to let textures bound where they are and only update the samplers to point where the texture is
  11317. */
  11318. this.disableTextureBindingOptimization = false;
  11319. /**
  11320. * Observable signaled when VR display mode changes
  11321. */
  11322. this.onVRDisplayChangedObservable = new BABYLON.Observable();
  11323. /**
  11324. * Observable signaled when VR request present is complete
  11325. */
  11326. this.onVRRequestPresentComplete = new BABYLON.Observable();
  11327. /**
  11328. * Observable signaled when VR request present starts
  11329. */
  11330. this.onVRRequestPresentStart = new BABYLON.Observable();
  11331. this._colorWrite = true;
  11332. /** @hidden */
  11333. this._drawCalls = new BABYLON.PerfCounter();
  11334. /** @hidden */
  11335. this._textureCollisions = new BABYLON.PerfCounter();
  11336. this._renderingQueueLaunched = false;
  11337. this._activeRenderLoops = new Array();
  11338. // Deterministic lockstepMaxSteps
  11339. this._deterministicLockstep = false;
  11340. this._lockstepMaxSteps = 4;
  11341. // Lost context
  11342. /**
  11343. * Observable signaled when a context lost event is raised
  11344. */
  11345. this.onContextLostObservable = new BABYLON.Observable();
  11346. /**
  11347. * Observable signaled when a context restored event is raised
  11348. */
  11349. this.onContextRestoredObservable = new BABYLON.Observable();
  11350. this._contextWasLost = false;
  11351. this._doNotHandleContextLost = false;
  11352. // FPS
  11353. this._performanceMonitor = new BABYLON.PerformanceMonitor();
  11354. this._fps = 60;
  11355. this._deltaTime = 0;
  11356. /**
  11357. * Turn this value on if you want to pause FPS computation when in background
  11358. */
  11359. this.disablePerformanceMonitorInBackground = false;
  11360. // States
  11361. /** @hidden */
  11362. this._depthCullingState = new BABYLON._DepthCullingState();
  11363. /** @hidden */
  11364. this._stencilState = new BABYLON._StencilState();
  11365. /** @hidden */
  11366. this._alphaState = new BABYLON._AlphaState();
  11367. /** @hidden */
  11368. this._alphaMode = Engine.ALPHA_DISABLE;
  11369. // Cache
  11370. this._internalTexturesCache = new Array();
  11371. /** @hidden */
  11372. this._activeChannel = 0;
  11373. this._currentTextureChannel = -1;
  11374. /** @hidden */
  11375. this._boundTexturesCache = {};
  11376. this._compiledEffects = {};
  11377. this._vertexAttribArraysEnabled = [];
  11378. this._uintIndicesCurrentlySet = false;
  11379. this._currentBoundBuffer = new Array();
  11380. this._currentBufferPointers = new Array();
  11381. this._currentInstanceLocations = new Array();
  11382. this._currentInstanceBuffers = new Array();
  11383. this._firstBoundInternalTextureTracker = new BABYLON.DummyInternalTextureTracker();
  11384. this._lastBoundInternalTextureTracker = new BABYLON.DummyInternalTextureTracker();
  11385. this._vaoRecordInProgress = false;
  11386. this._mustWipeVertexAttributes = false;
  11387. this._nextFreeTextureSlots = new Array();
  11388. this._maxSimultaneousTextures = 0;
  11389. this._activeRequests = new Array();
  11390. // Hardware supported Compressed Textures
  11391. this._texturesSupported = new Array();
  11392. this._onVRFullScreenTriggered = function () {
  11393. if (_this._vrDisplay && _this._vrDisplay.isPresenting) {
  11394. //get the old size before we change
  11395. _this._oldSize = new BABYLON.Size(_this.getRenderWidth(), _this.getRenderHeight());
  11396. _this._oldHardwareScaleFactor = _this.getHardwareScalingLevel();
  11397. //get the width and height, change the render size
  11398. var leftEye = _this._vrDisplay.getEyeParameters('left');
  11399. _this.setHardwareScalingLevel(1);
  11400. _this.setSize(leftEye.renderWidth * 2, leftEye.renderHeight);
  11401. }
  11402. else {
  11403. _this.setHardwareScalingLevel(_this._oldHardwareScaleFactor);
  11404. _this.setSize(_this._oldSize.width, _this._oldSize.height);
  11405. }
  11406. };
  11407. this._boundUniforms = {};
  11408. // Register promises
  11409. BABYLON.PromisePolyfill.Apply();
  11410. var canvas = null;
  11411. Engine.Instances.push(this);
  11412. if (!canvasOrContext) {
  11413. return;
  11414. }
  11415. options = options || {};
  11416. if (canvasOrContext.getContext) {
  11417. canvas = canvasOrContext;
  11418. this._renderingCanvas = canvas;
  11419. if (antialias != null) {
  11420. options.antialias = antialias;
  11421. }
  11422. if (options.deterministicLockstep === undefined) {
  11423. options.deterministicLockstep = false;
  11424. }
  11425. if (options.lockstepMaxSteps === undefined) {
  11426. options.lockstepMaxSteps = 4;
  11427. }
  11428. if (options.preserveDrawingBuffer === undefined) {
  11429. options.preserveDrawingBuffer = false;
  11430. }
  11431. if (options.audioEngine === undefined) {
  11432. options.audioEngine = true;
  11433. }
  11434. if (options.stencil === undefined) {
  11435. options.stencil = true;
  11436. }
  11437. this._deterministicLockstep = options.deterministicLockstep;
  11438. this._lockstepMaxSteps = options.lockstepMaxSteps;
  11439. this._doNotHandleContextLost = options.doNotHandleContextLost ? true : false;
  11440. // Exceptions
  11441. if (navigator && navigator.userAgent) {
  11442. var ua = navigator.userAgent;
  11443. for (var _i = 0, _a = Engine.ExceptionList; _i < _a.length; _i++) {
  11444. var exception = _a[_i];
  11445. var key = exception.key;
  11446. var targets = exception.targets;
  11447. if (ua.indexOf(key) > -1) {
  11448. if (exception.capture && exception.captureConstraint) {
  11449. var capture = exception.capture;
  11450. var constraint = exception.captureConstraint;
  11451. var regex = new RegExp(capture);
  11452. var matches = regex.exec(ua);
  11453. if (matches && matches.length > 0) {
  11454. var capturedValue = parseInt(matches[matches.length - 1]);
  11455. if (capturedValue >= constraint) {
  11456. continue;
  11457. }
  11458. }
  11459. }
  11460. for (var _b = 0, targets_1 = targets; _b < targets_1.length; _b++) {
  11461. var target = targets_1[_b];
  11462. switch (target) {
  11463. case "uniformBuffer":
  11464. this.disableUniformBuffers = true;
  11465. break;
  11466. case "textureBindingOptimization":
  11467. this.disableTextureBindingOptimization = true;
  11468. break;
  11469. }
  11470. }
  11471. }
  11472. }
  11473. }
  11474. // GL
  11475. if (!options.disableWebGL2Support) {
  11476. try {
  11477. this._gl = (canvas.getContext("webgl2", options) || canvas.getContext("experimental-webgl2", options));
  11478. if (this._gl) {
  11479. this._webGLVersion = 2.0;
  11480. }
  11481. }
  11482. catch (e) {
  11483. // Do nothing
  11484. }
  11485. }
  11486. if (!this._gl) {
  11487. if (!canvas) {
  11488. throw new Error("The provided canvas is null or undefined.");
  11489. }
  11490. try {
  11491. this._gl = (canvas.getContext("webgl", options) || canvas.getContext("experimental-webgl", options));
  11492. }
  11493. catch (e) {
  11494. throw new Error("WebGL not supported");
  11495. }
  11496. }
  11497. if (!this._gl) {
  11498. throw new Error("WebGL not supported");
  11499. }
  11500. this._onCanvasFocus = function () {
  11501. _this.onCanvasFocusObservable.notifyObservers(_this);
  11502. };
  11503. this._onCanvasBlur = function () {
  11504. _this.onCanvasBlurObservable.notifyObservers(_this);
  11505. };
  11506. canvas.addEventListener("focus", this._onCanvasFocus);
  11507. canvas.addEventListener("blur", this._onCanvasBlur);
  11508. this._onBlur = function () {
  11509. if (_this.disablePerformanceMonitorInBackground) {
  11510. _this._performanceMonitor.disable();
  11511. }
  11512. _this._windowIsBackground = true;
  11513. };
  11514. this._onFocus = function () {
  11515. if (_this.disablePerformanceMonitorInBackground) {
  11516. _this._performanceMonitor.enable();
  11517. }
  11518. _this._windowIsBackground = false;
  11519. };
  11520. this._onCanvasPointerOut = function (ev) {
  11521. _this.onCanvasPointerOutObservable.notifyObservers(ev);
  11522. };
  11523. window.addEventListener("blur", this._onBlur);
  11524. window.addEventListener("focus", this._onFocus);
  11525. canvas.addEventListener("pointerout", this._onCanvasPointerOut);
  11526. // Context lost
  11527. if (!this._doNotHandleContextLost) {
  11528. this._onContextLost = function (evt) {
  11529. evt.preventDefault();
  11530. _this._contextWasLost = true;
  11531. BABYLON.Tools.Warn("WebGL context lost.");
  11532. _this.onContextLostObservable.notifyObservers(_this);
  11533. };
  11534. this._onContextRestored = function (evt) {
  11535. // Adding a timeout to avoid race condition at browser level
  11536. setTimeout(function () {
  11537. // Rebuild gl context
  11538. _this._initGLContext();
  11539. // Rebuild effects
  11540. _this._rebuildEffects();
  11541. // Rebuild textures
  11542. _this._rebuildInternalTextures();
  11543. // Rebuild buffers
  11544. _this._rebuildBuffers();
  11545. // Cache
  11546. _this.wipeCaches(true);
  11547. BABYLON.Tools.Warn("WebGL context successfully restored.");
  11548. _this.onContextRestoredObservable.notifyObservers(_this);
  11549. _this._contextWasLost = false;
  11550. }, 0);
  11551. };
  11552. canvas.addEventListener("webglcontextlost", this._onContextLost, false);
  11553. canvas.addEventListener("webglcontextrestored", this._onContextRestored, false);
  11554. }
  11555. }
  11556. else {
  11557. this._gl = canvasOrContext;
  11558. this._renderingCanvas = this._gl.canvas;
  11559. if (this._gl.renderbufferStorageMultisample) {
  11560. this._webGLVersion = 2.0;
  11561. }
  11562. options.stencil = this._gl.getContextAttributes().stencil;
  11563. }
  11564. // Viewport
  11565. var limitDeviceRatio = options.limitDeviceRatio || window.devicePixelRatio || 1.0;
  11566. this._hardwareScalingLevel = adaptToDeviceRatio ? 1.0 / Math.min(limitDeviceRatio, window.devicePixelRatio || 1.0) : 1.0;
  11567. this.resize();
  11568. this._isStencilEnable = options.stencil ? true : false;
  11569. this._initGLContext();
  11570. if (canvas) {
  11571. // Fullscreen
  11572. this._onFullscreenChange = function () {
  11573. if (document.fullscreen !== undefined) {
  11574. _this.isFullscreen = document.fullscreen;
  11575. }
  11576. else if (document.mozFullScreen !== undefined) {
  11577. _this.isFullscreen = document.mozFullScreen;
  11578. }
  11579. else if (document.webkitIsFullScreen !== undefined) {
  11580. _this.isFullscreen = document.webkitIsFullScreen;
  11581. }
  11582. else if (document.msIsFullScreen !== undefined) {
  11583. _this.isFullscreen = document.msIsFullScreen;
  11584. }
  11585. // Pointer lock
  11586. if (_this.isFullscreen && _this._pointerLockRequested && canvas) {
  11587. canvas.requestPointerLock = canvas.requestPointerLock ||
  11588. canvas.msRequestPointerLock ||
  11589. canvas.mozRequestPointerLock ||
  11590. canvas.webkitRequestPointerLock;
  11591. if (canvas.requestPointerLock) {
  11592. canvas.requestPointerLock();
  11593. }
  11594. }
  11595. };
  11596. document.addEventListener("fullscreenchange", this._onFullscreenChange, false);
  11597. document.addEventListener("mozfullscreenchange", this._onFullscreenChange, false);
  11598. document.addEventListener("webkitfullscreenchange", this._onFullscreenChange, false);
  11599. document.addEventListener("msfullscreenchange", this._onFullscreenChange, false);
  11600. // Pointer lock
  11601. this._onPointerLockChange = function () {
  11602. _this.isPointerLock = (document.mozPointerLockElement === canvas ||
  11603. document.webkitPointerLockElement === canvas ||
  11604. document.msPointerLockElement === canvas ||
  11605. document.pointerLockElement === canvas);
  11606. };
  11607. document.addEventListener("pointerlockchange", this._onPointerLockChange, false);
  11608. document.addEventListener("mspointerlockchange", this._onPointerLockChange, false);
  11609. document.addEventListener("mozpointerlockchange", this._onPointerLockChange, false);
  11610. document.addEventListener("webkitpointerlockchange", this._onPointerLockChange, false);
  11611. this._onVRDisplayPointerRestricted = function () {
  11612. if (canvas) {
  11613. canvas.requestPointerLock();
  11614. }
  11615. };
  11616. this._onVRDisplayPointerUnrestricted = function () {
  11617. document.exitPointerLock();
  11618. };
  11619. window.addEventListener('vrdisplaypointerrestricted', this._onVRDisplayPointerRestricted, false);
  11620. window.addEventListener('vrdisplaypointerunrestricted', this._onVRDisplayPointerUnrestricted, false);
  11621. }
  11622. if (options.audioEngine && BABYLON.AudioEngine && !Engine.audioEngine) {
  11623. Engine.audioEngine = new BABYLON.AudioEngine();
  11624. }
  11625. // Prepare buffer pointers
  11626. for (var i = 0; i < this._caps.maxVertexAttribs; i++) {
  11627. this._currentBufferPointers[i] = new BufferPointer();
  11628. }
  11629. this._linkTrackers(this._firstBoundInternalTextureTracker, this._lastBoundInternalTextureTracker);
  11630. // Load WebVR Devices
  11631. if (options.autoEnableWebVR) {
  11632. this.initWebVR();
  11633. }
  11634. // Detect if we are running on a faulty buggy OS.
  11635. this._badOS = /iPad/i.test(navigator.userAgent) || /iPhone/i.test(navigator.userAgent);
  11636. // Detect if we are running on a faulty buggy desktop OS.
  11637. this._badDesktopOS = /^((?!chrome|android).)*safari/i.test(navigator.userAgent);
  11638. console.log("Babylon.js engine (v" + Engine.Version + ") launched");
  11639. this.enableOfflineSupport = (BABYLON.Database !== undefined);
  11640. }
  11641. Object.defineProperty(Engine, "LastCreatedEngine", {
  11642. /**
  11643. * Gets the latest created engine
  11644. */
  11645. get: function () {
  11646. if (Engine.Instances.length === 0) {
  11647. return null;
  11648. }
  11649. return Engine.Instances[Engine.Instances.length - 1];
  11650. },
  11651. enumerable: true,
  11652. configurable: true
  11653. });
  11654. Object.defineProperty(Engine, "LastCreatedScene", {
  11655. /**
  11656. * Gets the latest created scene
  11657. */
  11658. get: function () {
  11659. var lastCreatedEngine = Engine.LastCreatedEngine;
  11660. if (!lastCreatedEngine) {
  11661. return null;
  11662. }
  11663. if (lastCreatedEngine.scenes.length === 0) {
  11664. return null;
  11665. }
  11666. return lastCreatedEngine.scenes[lastCreatedEngine.scenes.length - 1];
  11667. },
  11668. enumerable: true,
  11669. configurable: true
  11670. });
  11671. /**
  11672. * Will flag all materials in all scenes in all engines as dirty to trigger new shader compilation
  11673. * @param flag defines which part of the materials must be marked as dirty
  11674. * @param predicate defines a predicate used to filter which materials should be affected
  11675. */
  11676. Engine.MarkAllMaterialsAsDirty = function (flag, predicate) {
  11677. for (var engineIndex = 0; engineIndex < Engine.Instances.length; engineIndex++) {
  11678. var engine = Engine.Instances[engineIndex];
  11679. for (var sceneIndex = 0; sceneIndex < engine.scenes.length; sceneIndex++) {
  11680. engine.scenes[sceneIndex].markAllMaterialsAsDirty(flag, predicate);
  11681. }
  11682. }
  11683. };
  11684. Object.defineProperty(Engine, "NEVER", {
  11685. /** Passed to depthFunction or stencilFunction to specify depth or stencil tests will never pass. i.e. Nothing will be drawn */
  11686. get: function () {
  11687. return Engine._NEVER;
  11688. },
  11689. enumerable: true,
  11690. configurable: true
  11691. });
  11692. Object.defineProperty(Engine, "ALWAYS", {
  11693. /** 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 */
  11694. get: function () {
  11695. return Engine._ALWAYS;
  11696. },
  11697. enumerable: true,
  11698. configurable: true
  11699. });
  11700. Object.defineProperty(Engine, "LESS", {
  11701. /** Passed to depthFunction or stencilFunction to specify depth or stencil tests will pass if the new depth value is less than the stored value */
  11702. get: function () {
  11703. return Engine._LESS;
  11704. },
  11705. enumerable: true,
  11706. configurable: true
  11707. });
  11708. Object.defineProperty(Engine, "EQUAL", {
  11709. /** Passed to depthFunction or stencilFunction to specify depth or stencil tests will pass if the new depth value is equals to the stored value */
  11710. get: function () {
  11711. return Engine._EQUAL;
  11712. },
  11713. enumerable: true,
  11714. configurable: true
  11715. });
  11716. Object.defineProperty(Engine, "LEQUAL", {
  11717. /** 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 */
  11718. get: function () {
  11719. return Engine._LEQUAL;
  11720. },
  11721. enumerable: true,
  11722. configurable: true
  11723. });
  11724. Object.defineProperty(Engine, "GREATER", {
  11725. /** Passed to depthFunction or stencilFunction to specify depth or stencil tests will pass if the new depth value is greater than the stored value */
  11726. get: function () {
  11727. return Engine._GREATER;
  11728. },
  11729. enumerable: true,
  11730. configurable: true
  11731. });
  11732. Object.defineProperty(Engine, "GEQUAL", {
  11733. /** 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 */
  11734. get: function () {
  11735. return Engine._GEQUAL;
  11736. },
  11737. enumerable: true,
  11738. configurable: true
  11739. });
  11740. Object.defineProperty(Engine, "NOTEQUAL", {
  11741. /** 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 */
  11742. get: function () {
  11743. return Engine._NOTEQUAL;
  11744. },
  11745. enumerable: true,
  11746. configurable: true
  11747. });
  11748. Object.defineProperty(Engine, "KEEP", {
  11749. /** Passed to stencilOperation to specify that stencil value must be kept */
  11750. get: function () {
  11751. return Engine._KEEP;
  11752. },
  11753. enumerable: true,
  11754. configurable: true
  11755. });
  11756. Object.defineProperty(Engine, "REPLACE", {
  11757. /** Passed to stencilOperation to specify that stencil value must be replaced */
  11758. get: function () {
  11759. return Engine._REPLACE;
  11760. },
  11761. enumerable: true,
  11762. configurable: true
  11763. });
  11764. Object.defineProperty(Engine, "INCR", {
  11765. /** Passed to stencilOperation to specify that stencil value must be incremented */
  11766. get: function () {
  11767. return Engine._INCR;
  11768. },
  11769. enumerable: true,
  11770. configurable: true
  11771. });
  11772. Object.defineProperty(Engine, "DECR", {
  11773. /** Passed to stencilOperation to specify that stencil value must be decremented */
  11774. get: function () {
  11775. return Engine._DECR;
  11776. },
  11777. enumerable: true,
  11778. configurable: true
  11779. });
  11780. Object.defineProperty(Engine, "INVERT", {
  11781. /** Passed to stencilOperation to specify that stencil value must be inverted */
  11782. get: function () {
  11783. return Engine._INVERT;
  11784. },
  11785. enumerable: true,
  11786. configurable: true
  11787. });
  11788. Object.defineProperty(Engine, "INCR_WRAP", {
  11789. /** Passed to stencilOperation to specify that stencil value must be incremented with wrapping */
  11790. get: function () {
  11791. return Engine._INCR_WRAP;
  11792. },
  11793. enumerable: true,
  11794. configurable: true
  11795. });
  11796. Object.defineProperty(Engine, "DECR_WRAP", {
  11797. /** Passed to stencilOperation to specify that stencil value must be decremented with wrapping */
  11798. get: function () {
  11799. return Engine._DECR_WRAP;
  11800. },
  11801. enumerable: true,
  11802. configurable: true
  11803. });
  11804. Object.defineProperty(Engine, "ALPHA_DISABLE", {
  11805. // Alpha
  11806. /** Defines that alpha blending is disabled */
  11807. get: function () {
  11808. return Engine._ALPHA_DISABLE;
  11809. },
  11810. enumerable: true,
  11811. configurable: true
  11812. });
  11813. Object.defineProperty(Engine, "ALPHA_ONEONE", {
  11814. /** Defines that alpha blending to SRC + DEST */
  11815. get: function () {
  11816. return Engine._ALPHA_ONEONE;
  11817. },
  11818. enumerable: true,
  11819. configurable: true
  11820. });
  11821. Object.defineProperty(Engine, "ALPHA_ADD", {
  11822. /** Defines that alpha blending to SRC ALPHA * SRC + DEST */
  11823. get: function () {
  11824. return Engine._ALPHA_ADD;
  11825. },
  11826. enumerable: true,
  11827. configurable: true
  11828. });
  11829. Object.defineProperty(Engine, "ALPHA_COMBINE", {
  11830. /** Defines that alpha blending to SRC ALPHA * SRC + (1 - SRC ALPHA) * DEST */
  11831. get: function () {
  11832. return Engine._ALPHA_COMBINE;
  11833. },
  11834. enumerable: true,
  11835. configurable: true
  11836. });
  11837. Object.defineProperty(Engine, "ALPHA_SUBTRACT", {
  11838. /** Defines that alpha blending to DEST - SRC * DEST */
  11839. get: function () {
  11840. return Engine._ALPHA_SUBTRACT;
  11841. },
  11842. enumerable: true,
  11843. configurable: true
  11844. });
  11845. Object.defineProperty(Engine, "ALPHA_MULTIPLY", {
  11846. /** Defines that alpha blending to SRC * DEST */
  11847. get: function () {
  11848. return Engine._ALPHA_MULTIPLY;
  11849. },
  11850. enumerable: true,
  11851. configurable: true
  11852. });
  11853. Object.defineProperty(Engine, "ALPHA_MAXIMIZED", {
  11854. /** Defines that alpha blending to SRC ALPHA * SRC + (1 - SRC) * DEST */
  11855. get: function () {
  11856. return Engine._ALPHA_MAXIMIZED;
  11857. },
  11858. enumerable: true,
  11859. configurable: true
  11860. });
  11861. Object.defineProperty(Engine, "ALPHA_PREMULTIPLIED", {
  11862. /** Defines that alpha blending to SRC + (1 - SRC ALPHA) * DEST */
  11863. get: function () {
  11864. return Engine._ALPHA_PREMULTIPLIED;
  11865. },
  11866. enumerable: true,
  11867. configurable: true
  11868. });
  11869. Object.defineProperty(Engine, "ALPHA_PREMULTIPLIED_PORTERDUFF", {
  11870. /**
  11871. * Defines that alpha blending to SRC + (1 - SRC ALPHA) * DEST
  11872. * Alpha will be set to (1 - SRC ALPHA) * DEST ALPHA
  11873. */
  11874. get: function () {
  11875. return Engine._ALPHA_PREMULTIPLIED_PORTERDUFF;
  11876. },
  11877. enumerable: true,
  11878. configurable: true
  11879. });
  11880. Object.defineProperty(Engine, "ALPHA_INTERPOLATE", {
  11881. /** Defines that alpha blending to CST * SRC + (1 - CST) * DEST */
  11882. get: function () {
  11883. return Engine._ALPHA_INTERPOLATE;
  11884. },
  11885. enumerable: true,
  11886. configurable: true
  11887. });
  11888. Object.defineProperty(Engine, "ALPHA_SCREENMODE", {
  11889. /**
  11890. * Defines that alpha blending to SRC + (1 - SRC) * DEST
  11891. * Alpha will be set to SRC ALPHA + (1 - SRC ALPHA) * DEST ALPHA
  11892. */
  11893. get: function () {
  11894. return Engine._ALPHA_SCREENMODE;
  11895. },
  11896. enumerable: true,
  11897. configurable: true
  11898. });
  11899. Object.defineProperty(Engine, "DELAYLOADSTATE_NONE", {
  11900. // Delays
  11901. /** Defines that the ressource is not delayed*/
  11902. get: function () {
  11903. return Engine._DELAYLOADSTATE_NONE;
  11904. },
  11905. enumerable: true,
  11906. configurable: true
  11907. });
  11908. Object.defineProperty(Engine, "DELAYLOADSTATE_LOADED", {
  11909. /** Defines that the ressource was successfully delay loaded */
  11910. get: function () {
  11911. return Engine._DELAYLOADSTATE_LOADED;
  11912. },
  11913. enumerable: true,
  11914. configurable: true
  11915. });
  11916. Object.defineProperty(Engine, "DELAYLOADSTATE_LOADING", {
  11917. /** Defines that the ressource is currently delay loading */
  11918. get: function () {
  11919. return Engine._DELAYLOADSTATE_LOADING;
  11920. },
  11921. enumerable: true,
  11922. configurable: true
  11923. });
  11924. Object.defineProperty(Engine, "DELAYLOADSTATE_NOTLOADED", {
  11925. /** Defines that the ressource is delayed and has not started loading */
  11926. get: function () {
  11927. return Engine._DELAYLOADSTATE_NOTLOADED;
  11928. },
  11929. enumerable: true,
  11930. configurable: true
  11931. });
  11932. Object.defineProperty(Engine, "TEXTUREFORMAT_ALPHA", {
  11933. /** ALPHA */
  11934. get: function () {
  11935. return Engine._TEXTUREFORMAT_ALPHA;
  11936. },
  11937. enumerable: true,
  11938. configurable: true
  11939. });
  11940. Object.defineProperty(Engine, "TEXTUREFORMAT_LUMINANCE", {
  11941. /** LUMINANCE */
  11942. get: function () {
  11943. return Engine._TEXTUREFORMAT_LUMINANCE;
  11944. },
  11945. enumerable: true,
  11946. configurable: true
  11947. });
  11948. Object.defineProperty(Engine, "TEXTUREFORMAT_R32F", {
  11949. /**
  11950. * R32F
  11951. */
  11952. get: function () {
  11953. return Engine._TEXTUREFORMAT_R32F;
  11954. },
  11955. enumerable: true,
  11956. configurable: true
  11957. });
  11958. Object.defineProperty(Engine, "TEXTUREFORMAT_RG32F", {
  11959. /**
  11960. * RG32F
  11961. */
  11962. get: function () {
  11963. return Engine._TEXTUREFORMAT_RG32F;
  11964. },
  11965. enumerable: true,
  11966. configurable: true
  11967. });
  11968. Object.defineProperty(Engine, "TEXTUREFORMAT_RGB32F", {
  11969. /**
  11970. * RGB32F
  11971. */
  11972. get: function () {
  11973. return Engine._TEXTUREFORMAT_RGB32F;
  11974. },
  11975. enumerable: true,
  11976. configurable: true
  11977. });
  11978. Object.defineProperty(Engine, "TEXTUREFORMAT_RGBA32F", {
  11979. /**
  11980. * RGBA32F
  11981. */
  11982. get: function () {
  11983. return Engine._TEXTUREFORMAT_RGBA32F;
  11984. },
  11985. enumerable: true,
  11986. configurable: true
  11987. });
  11988. Object.defineProperty(Engine, "TEXTUREFORMAT_LUMINANCE_ALPHA", {
  11989. /** LUMINANCE_ALPHA */
  11990. get: function () {
  11991. return Engine._TEXTUREFORMAT_LUMINANCE_ALPHA;
  11992. },
  11993. enumerable: true,
  11994. configurable: true
  11995. });
  11996. Object.defineProperty(Engine, "TEXTUREFORMAT_RGB", {
  11997. /** RGB */
  11998. get: function () {
  11999. return Engine._TEXTUREFORMAT_RGB;
  12000. },
  12001. enumerable: true,
  12002. configurable: true
  12003. });
  12004. Object.defineProperty(Engine, "TEXTUREFORMAT_RGBA", {
  12005. /** RGBA */
  12006. get: function () {
  12007. return Engine._TEXTUREFORMAT_RGBA;
  12008. },
  12009. enumerable: true,
  12010. configurable: true
  12011. });
  12012. Object.defineProperty(Engine, "TEXTURETYPE_UNSIGNED_INT", {
  12013. /** UNSIGNED_INT */
  12014. get: function () {
  12015. return Engine._TEXTURETYPE_UNSIGNED_INT;
  12016. },
  12017. enumerable: true,
  12018. configurable: true
  12019. });
  12020. Object.defineProperty(Engine, "TEXTURETYPE_FLOAT", {
  12021. /** FLOAT */
  12022. get: function () {
  12023. return Engine._TEXTURETYPE_FLOAT;
  12024. },
  12025. enumerable: true,
  12026. configurable: true
  12027. });
  12028. Object.defineProperty(Engine, "TEXTURETYPE_HALF_FLOAT", {
  12029. /** HALF_FLOAT */
  12030. get: function () {
  12031. return Engine._TEXTURETYPE_HALF_FLOAT;
  12032. },
  12033. enumerable: true,
  12034. configurable: true
  12035. });
  12036. Object.defineProperty(Engine, "SCALEMODE_FLOOR", {
  12037. /** Defines that texture rescaling will use a floor to find the closer power of 2 size */
  12038. get: function () {
  12039. return Engine._SCALEMODE_FLOOR;
  12040. },
  12041. enumerable: true,
  12042. configurable: true
  12043. });
  12044. Object.defineProperty(Engine, "SCALEMODE_NEAREST", {
  12045. /** Defines that texture rescaling will look for the nearest power of 2 size */
  12046. get: function () {
  12047. return Engine._SCALEMODE_NEAREST;
  12048. },
  12049. enumerable: true,
  12050. configurable: true
  12051. });
  12052. Object.defineProperty(Engine, "SCALEMODE_CEILING", {
  12053. /** Defines that texture rescaling will use a ceil to find the closer power of 2 size */
  12054. get: function () {
  12055. return Engine._SCALEMODE_CEILING;
  12056. },
  12057. enumerable: true,
  12058. configurable: true
  12059. });
  12060. Object.defineProperty(Engine, "Version", {
  12061. /**
  12062. * Returns the current version of the framework
  12063. */
  12064. get: function () {
  12065. return "3.2.0-rc.1";
  12066. },
  12067. enumerable: true,
  12068. configurable: true
  12069. });
  12070. Object.defineProperty(Engine.prototype, "isInVRExclusivePointerMode", {
  12071. /**
  12072. * Gets a boolean indicating that the engine is currently in VR exclusive mode for the pointers
  12073. * @see https://docs.microsoft.com/en-us/microsoft-edge/webvr/essentials#mouse-input
  12074. */
  12075. get: function () {
  12076. return this._vrExclusivePointerMode;
  12077. },
  12078. enumerable: true,
  12079. configurable: true
  12080. });
  12081. Object.defineProperty(Engine.prototype, "supportsUniformBuffers", {
  12082. /**
  12083. * Gets a boolean indicating that the engine supports uniform buffers
  12084. * @see http://doc.babylonjs.com/features/webgl2#uniform-buffer-objets
  12085. */
  12086. get: function () {
  12087. return this.webGLVersion > 1 && !this.disableUniformBuffers;
  12088. },
  12089. enumerable: true,
  12090. configurable: true
  12091. });
  12092. Object.defineProperty(Engine.prototype, "needPOTTextures", {
  12093. /**
  12094. * Gets a boolean indicating that only power of 2 textures are supported
  12095. * Please note that you can still use non power of 2 textures but in this case the engine will forcefully convert them
  12096. */
  12097. get: function () {
  12098. return this._webGLVersion < 2 || this.forcePOTTextures;
  12099. },
  12100. enumerable: true,
  12101. configurable: true
  12102. });
  12103. Object.defineProperty(Engine.prototype, "performanceMonitor", {
  12104. /**
  12105. * Gets the performance monitor attached to this engine
  12106. * @see http://doc.babylonjs.com/how_to/optimizing_your_scene#engineinstrumentation
  12107. */
  12108. get: function () {
  12109. return this._performanceMonitor;
  12110. },
  12111. enumerable: true,
  12112. configurable: true
  12113. });
  12114. Object.defineProperty(Engine.prototype, "texturesSupported", {
  12115. /**
  12116. * Gets the list of texture formats supported
  12117. */
  12118. get: function () {
  12119. return this._texturesSupported;
  12120. },
  12121. enumerable: true,
  12122. configurable: true
  12123. });
  12124. Object.defineProperty(Engine.prototype, "textureFormatInUse", {
  12125. /**
  12126. * Gets the list of texture formats in use
  12127. */
  12128. get: function () {
  12129. return this._textureFormatInUse;
  12130. },
  12131. enumerable: true,
  12132. configurable: true
  12133. });
  12134. Object.defineProperty(Engine.prototype, "currentViewport", {
  12135. /**
  12136. * Gets the current viewport
  12137. */
  12138. get: function () {
  12139. return this._cachedViewport;
  12140. },
  12141. enumerable: true,
  12142. configurable: true
  12143. });
  12144. Object.defineProperty(Engine.prototype, "emptyTexture", {
  12145. /**
  12146. * Gets the default empty texture
  12147. */
  12148. get: function () {
  12149. if (!this._emptyTexture) {
  12150. this._emptyTexture = this.createRawTexture(new Uint8Array(4), 1, 1, Engine.TEXTUREFORMAT_RGBA, false, false, BABYLON.Texture.NEAREST_SAMPLINGMODE);
  12151. }
  12152. return this._emptyTexture;
  12153. },
  12154. enumerable: true,
  12155. configurable: true
  12156. });
  12157. Object.defineProperty(Engine.prototype, "emptyTexture3D", {
  12158. /**
  12159. * Gets the default empty 3D texture
  12160. */
  12161. get: function () {
  12162. if (!this._emptyTexture3D) {
  12163. this._emptyTexture3D = this.createRawTexture3D(new Uint8Array(4), 1, 1, 1, Engine.TEXTUREFORMAT_RGBA, false, false, BABYLON.Texture.NEAREST_SAMPLINGMODE);
  12164. }
  12165. return this._emptyTexture3D;
  12166. },
  12167. enumerable: true,
  12168. configurable: true
  12169. });
  12170. Object.defineProperty(Engine.prototype, "emptyCubeTexture", {
  12171. /**
  12172. * Gets the default empty cube texture
  12173. */
  12174. get: function () {
  12175. if (!this._emptyCubeTexture) {
  12176. var faceData = new Uint8Array(4);
  12177. var cubeData = [faceData, faceData, faceData, faceData, faceData, faceData];
  12178. this._emptyCubeTexture = this.createRawCubeTexture(cubeData, 1, Engine.TEXTUREFORMAT_RGBA, Engine.TEXTURETYPE_UNSIGNED_INT, false, false, BABYLON.Texture.NEAREST_SAMPLINGMODE);
  12179. }
  12180. return this._emptyCubeTexture;
  12181. },
  12182. enumerable: true,
  12183. configurable: true
  12184. });
  12185. Engine.prototype._rebuildInternalTextures = function () {
  12186. var currentState = this._internalTexturesCache.slice(); // Do a copy because the rebuild will add proxies
  12187. for (var _i = 0, currentState_1 = currentState; _i < currentState_1.length; _i++) {
  12188. var internalTexture = currentState_1[_i];
  12189. internalTexture._rebuild();
  12190. }
  12191. };
  12192. Engine.prototype._rebuildEffects = function () {
  12193. for (var key in this._compiledEffects) {
  12194. var effect = this._compiledEffects[key];
  12195. effect._prepareEffect();
  12196. }
  12197. BABYLON.Effect.ResetCache();
  12198. };
  12199. Engine.prototype._rebuildBuffers = function () {
  12200. // Index / Vertex
  12201. for (var _i = 0, _a = this.scenes; _i < _a.length; _i++) {
  12202. var scene = _a[_i];
  12203. scene.resetCachedMaterial();
  12204. scene._rebuildGeometries();
  12205. scene._rebuildTextures();
  12206. }
  12207. // Uniforms
  12208. for (var _b = 0, _c = this._uniformBuffers; _b < _c.length; _b++) {
  12209. var uniformBuffer = _c[_b];
  12210. uniformBuffer._rebuild();
  12211. }
  12212. };
  12213. Engine.prototype._initGLContext = function () {
  12214. // Caps
  12215. this._caps = new EngineCapabilities();
  12216. this._caps.maxTexturesImageUnits = this._gl.getParameter(this._gl.MAX_TEXTURE_IMAGE_UNITS);
  12217. this._caps.maxCombinedTexturesImageUnits = this._gl.getParameter(this._gl.MAX_COMBINED_TEXTURE_IMAGE_UNITS);
  12218. this._caps.maxVertexTextureImageUnits = this._gl.getParameter(this._gl.MAX_VERTEX_TEXTURE_IMAGE_UNITS);
  12219. this._caps.maxTextureSize = this._gl.getParameter(this._gl.MAX_TEXTURE_SIZE);
  12220. this._caps.maxCubemapTextureSize = this._gl.getParameter(this._gl.MAX_CUBE_MAP_TEXTURE_SIZE);
  12221. this._caps.maxRenderTextureSize = this._gl.getParameter(this._gl.MAX_RENDERBUFFER_SIZE);
  12222. this._caps.maxVertexAttribs = this._gl.getParameter(this._gl.MAX_VERTEX_ATTRIBS);
  12223. this._caps.maxVaryingVectors = this._gl.getParameter(this._gl.MAX_VARYING_VECTORS);
  12224. this._caps.maxFragmentUniformVectors = this._gl.getParameter(this._gl.MAX_FRAGMENT_UNIFORM_VECTORS);
  12225. this._caps.maxVertexUniformVectors = this._gl.getParameter(this._gl.MAX_VERTEX_UNIFORM_VECTORS);
  12226. // Infos
  12227. this._glVersion = this._gl.getParameter(this._gl.VERSION);
  12228. var rendererInfo = this._gl.getExtension("WEBGL_debug_renderer_info");
  12229. if (rendererInfo != null) {
  12230. this._glRenderer = this._gl.getParameter(rendererInfo.UNMASKED_RENDERER_WEBGL);
  12231. this._glVendor = this._gl.getParameter(rendererInfo.UNMASKED_VENDOR_WEBGL);
  12232. }
  12233. if (!this._glVendor) {
  12234. this._glVendor = "Unknown vendor";
  12235. }
  12236. if (!this._glRenderer) {
  12237. this._glRenderer = "Unknown renderer";
  12238. }
  12239. // Constants
  12240. this._gl.HALF_FLOAT_OES = 0x8D61; // Half floating-point type (16-bit).
  12241. if (this._gl.RGBA16F !== 0x881A) {
  12242. this._gl.RGBA16F = 0x881A; // RGBA 16-bit floating-point color-renderable internal sized format.
  12243. }
  12244. if (this._gl.RGBA32F !== 0x8814) {
  12245. this._gl.RGBA32F = 0x8814; // RGBA 32-bit floating-point color-renderable internal sized format.
  12246. }
  12247. if (this._gl.DEPTH24_STENCIL8 !== 35056) {
  12248. this._gl.DEPTH24_STENCIL8 = 35056;
  12249. }
  12250. // Extensions
  12251. this._caps.standardDerivatives = this._webGLVersion > 1 || (this._gl.getExtension('OES_standard_derivatives') !== null);
  12252. this._caps.astc = this._gl.getExtension('WEBGL_compressed_texture_astc') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_astc');
  12253. this._caps.s3tc = this._gl.getExtension('WEBGL_compressed_texture_s3tc') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_s3tc');
  12254. this._caps.pvrtc = this._gl.getExtension('WEBGL_compressed_texture_pvrtc') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_pvrtc');
  12255. this._caps.etc1 = this._gl.getExtension('WEBGL_compressed_texture_etc1') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_etc1');
  12256. this._caps.etc2 = this._gl.getExtension('WEBGL_compressed_texture_etc') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_etc') ||
  12257. this._gl.getExtension('WEBGL_compressed_texture_es3_0'); // also a requirement of OpenGL ES 3
  12258. 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');
  12259. this._caps.maxAnisotropy = this._caps.textureAnisotropicFilterExtension ? this._gl.getParameter(this._caps.textureAnisotropicFilterExtension.MAX_TEXTURE_MAX_ANISOTROPY_EXT) : 0;
  12260. this._caps.uintIndices = this._webGLVersion > 1 || this._gl.getExtension('OES_element_index_uint') !== null;
  12261. this._caps.fragmentDepthSupported = this._webGLVersion > 1 || this._gl.getExtension('EXT_frag_depth') !== null;
  12262. this._caps.highPrecisionShaderSupported = true;
  12263. this._caps.timerQuery = this._gl.getExtension('EXT_disjoint_timer_query_webgl2') || this._gl.getExtension("EXT_disjoint_timer_query");
  12264. if (this._caps.timerQuery) {
  12265. if (this._webGLVersion === 1) {
  12266. this._gl.getQuery = this._caps.timerQuery.getQueryEXT.bind(this._caps.timerQuery);
  12267. }
  12268. this._caps.canUseTimestampForTimerQuery = this._gl.getQuery(this._caps.timerQuery.TIMESTAMP_EXT, this._caps.timerQuery.QUERY_COUNTER_BITS_EXT) > 0;
  12269. }
  12270. // Checks if some of the format renders first to allow the use of webgl inspector.
  12271. this._caps.colorBufferFloat = this._webGLVersion > 1 && this._gl.getExtension('EXT_color_buffer_float');
  12272. this._caps.textureFloat = (this._webGLVersion > 1 || this._gl.getExtension('OES_texture_float')) ? true : false;
  12273. this._caps.textureFloatLinearFiltering = this._caps.textureFloat && this._gl.getExtension('OES_texture_float_linear') ? true : false;
  12274. this._caps.textureFloatRender = this._caps.textureFloat && this._canRenderToFloatFramebuffer() ? true : false;
  12275. this._caps.textureHalfFloat = (this._webGLVersion > 1 || this._gl.getExtension('OES_texture_half_float')) ? true : false;
  12276. this._caps.textureHalfFloatLinearFiltering = (this._webGLVersion > 1 || (this._caps.textureHalfFloat && this._gl.getExtension('OES_texture_half_float_linear'))) ? true : false;
  12277. if (this._webGLVersion > 1) {
  12278. this._gl.HALF_FLOAT_OES = 0x140B;
  12279. }
  12280. this._caps.textureHalfFloatRender = this._caps.textureHalfFloat && this._canRenderToHalfFloatFramebuffer();
  12281. this._caps.textureLOD = (this._webGLVersion > 1 || this._gl.getExtension('EXT_shader_texture_lod')) ? true : false;
  12282. // Draw buffers
  12283. if (this._webGLVersion > 1) {
  12284. this._caps.drawBuffersExtension = true;
  12285. }
  12286. else {
  12287. var drawBuffersExtension = this._gl.getExtension('WEBGL_draw_buffers');
  12288. if (drawBuffersExtension !== null) {
  12289. this._caps.drawBuffersExtension = true;
  12290. this._gl.drawBuffers = drawBuffersExtension.drawBuffersWEBGL.bind(drawBuffersExtension);
  12291. this._gl.DRAW_FRAMEBUFFER = this._gl.FRAMEBUFFER;
  12292. for (var i = 0; i < 16; i++) {
  12293. this._gl["COLOR_ATTACHMENT" + i + "_WEBGL"] = drawBuffersExtension["COLOR_ATTACHMENT" + i + "_WEBGL"];
  12294. }
  12295. }
  12296. else {
  12297. this._caps.drawBuffersExtension = false;
  12298. }
  12299. }
  12300. // Depth Texture
  12301. if (this._webGLVersion > 1) {
  12302. this._caps.depthTextureExtension = true;
  12303. }
  12304. else {
  12305. var depthTextureExtension = this._gl.getExtension('WEBGL_depth_texture');
  12306. if (depthTextureExtension != null) {
  12307. this._caps.depthTextureExtension = true;
  12308. this._gl.UNSIGNED_INT_24_8 = depthTextureExtension.UNSIGNED_INT_24_8_WEBGL;
  12309. }
  12310. }
  12311. // Vertex array object
  12312. if (this._webGLVersion > 1) {
  12313. this._caps.vertexArrayObject = true;
  12314. }
  12315. else {
  12316. var vertexArrayObjectExtension = this._gl.getExtension('OES_vertex_array_object');
  12317. if (vertexArrayObjectExtension != null) {
  12318. this._caps.vertexArrayObject = true;
  12319. this._gl.createVertexArray = vertexArrayObjectExtension.createVertexArrayOES.bind(vertexArrayObjectExtension);
  12320. this._gl.bindVertexArray = vertexArrayObjectExtension.bindVertexArrayOES.bind(vertexArrayObjectExtension);
  12321. this._gl.deleteVertexArray = vertexArrayObjectExtension.deleteVertexArrayOES.bind(vertexArrayObjectExtension);
  12322. }
  12323. else {
  12324. this._caps.vertexArrayObject = false;
  12325. }
  12326. }
  12327. // Instances count
  12328. if (this._webGLVersion > 1) {
  12329. this._caps.instancedArrays = true;
  12330. }
  12331. else {
  12332. var instanceExtension = this._gl.getExtension('ANGLE_instanced_arrays');
  12333. if (instanceExtension != null) {
  12334. this._caps.instancedArrays = true;
  12335. this._gl.drawArraysInstanced = instanceExtension.drawArraysInstancedANGLE.bind(instanceExtension);
  12336. this._gl.drawElementsInstanced = instanceExtension.drawElementsInstancedANGLE.bind(instanceExtension);
  12337. this._gl.vertexAttribDivisor = instanceExtension.vertexAttribDivisorANGLE.bind(instanceExtension);
  12338. }
  12339. else {
  12340. this._caps.instancedArrays = false;
  12341. }
  12342. }
  12343. // Intelligently add supported compressed formats in order to check for.
  12344. // Check for ASTC support first as it is most powerful and to be very cross platform.
  12345. // Next PVRTC & DXT, which are probably superior to ETC1/2.
  12346. // Likely no hardware which supports both PVR & DXT, so order matters little.
  12347. // ETC2 is newer and handles ETC1 (no alpha capability), so check for first.
  12348. if (this._caps.astc)
  12349. this.texturesSupported.push('-astc.ktx');
  12350. if (this._caps.s3tc)
  12351. this.texturesSupported.push('-dxt.ktx');
  12352. if (this._caps.pvrtc)
  12353. this.texturesSupported.push('-pvrtc.ktx');
  12354. if (this._caps.etc2)
  12355. this.texturesSupported.push('-etc2.ktx');
  12356. if (this._caps.etc1)
  12357. this.texturesSupported.push('-etc1.ktx');
  12358. if (this._gl.getShaderPrecisionFormat) {
  12359. var highp = this._gl.getShaderPrecisionFormat(this._gl.FRAGMENT_SHADER, this._gl.HIGH_FLOAT);
  12360. if (highp) {
  12361. this._caps.highPrecisionShaderSupported = highp.precision !== 0;
  12362. }
  12363. }
  12364. // Depth buffer
  12365. this.setDepthBuffer(true);
  12366. this.setDepthFunctionToLessOrEqual();
  12367. this.setDepthWrite(true);
  12368. // Texture maps
  12369. this._maxSimultaneousTextures = this._caps.maxCombinedTexturesImageUnits;
  12370. for (var slot = 0; slot < this._maxSimultaneousTextures; slot++) {
  12371. this._nextFreeTextureSlots.push(slot);
  12372. }
  12373. };
  12374. Object.defineProperty(Engine.prototype, "webGLVersion", {
  12375. /**
  12376. * Gets version of the current webGL context
  12377. */
  12378. get: function () {
  12379. return this._webGLVersion;
  12380. },
  12381. enumerable: true,
  12382. configurable: true
  12383. });
  12384. Object.defineProperty(Engine.prototype, "isStencilEnable", {
  12385. /**
  12386. * Returns true if the stencil buffer has been enabled through the creation option of the context.
  12387. */
  12388. get: function () {
  12389. return this._isStencilEnable;
  12390. },
  12391. enumerable: true,
  12392. configurable: true
  12393. });
  12394. Engine.prototype._prepareWorkingCanvas = function () {
  12395. if (this._workingCanvas) {
  12396. return;
  12397. }
  12398. this._workingCanvas = document.createElement("canvas");
  12399. var context = this._workingCanvas.getContext("2d");
  12400. if (context) {
  12401. this._workingContext = context;
  12402. }
  12403. };
  12404. /**
  12405. * Reset the texture cache to empty state
  12406. */
  12407. Engine.prototype.resetTextureCache = function () {
  12408. for (var key in this._boundTexturesCache) {
  12409. if (!this._boundTexturesCache.hasOwnProperty(key)) {
  12410. continue;
  12411. }
  12412. var boundTexture = this._boundTexturesCache[key];
  12413. if (boundTexture) {
  12414. this._removeDesignatedSlot(boundTexture);
  12415. }
  12416. this._boundTexturesCache[key] = null;
  12417. }
  12418. if (!this.disableTextureBindingOptimization) {
  12419. this._nextFreeTextureSlots = [];
  12420. for (var slot = 0; slot < this._maxSimultaneousTextures; slot++) {
  12421. this._nextFreeTextureSlots.push(slot);
  12422. }
  12423. }
  12424. this._currentTextureChannel = -1;
  12425. };
  12426. /**
  12427. * Gets a boolean indicating that the engine is running in deterministic lock step mode
  12428. * @see http://doc.babylonjs.com/babylon101/animations#deterministic-lockstep
  12429. * @returns true if engine is in deterministic lock step mode
  12430. */
  12431. Engine.prototype.isDeterministicLockStep = function () {
  12432. return this._deterministicLockstep;
  12433. };
  12434. /**
  12435. * Gets the max steps when engine is running in deterministic lock step
  12436. * @see http://doc.babylonjs.com/babylon101/animations#deterministic-lockstep
  12437. * @returns the max steps
  12438. */
  12439. Engine.prototype.getLockstepMaxSteps = function () {
  12440. return this._lockstepMaxSteps;
  12441. };
  12442. /**
  12443. * Gets an object containing information about the current webGL context
  12444. * @returns an object containing the vender, the renderer and the version of the current webGL context
  12445. */
  12446. Engine.prototype.getGlInfo = function () {
  12447. return {
  12448. vendor: this._glVendor,
  12449. renderer: this._glRenderer,
  12450. version: this._glVersion
  12451. };
  12452. };
  12453. /**
  12454. * Gets current aspect ratio
  12455. * @param camera defines the camera to use to get the aspect ratio
  12456. * @param useScreen defines if screen size must be used (or the current render target if any)
  12457. * @returns a number defining the aspect ratio
  12458. */
  12459. Engine.prototype.getAspectRatio = function (camera, useScreen) {
  12460. if (useScreen === void 0) { useScreen = false; }
  12461. var viewport = camera.viewport;
  12462. return (this.getRenderWidth(useScreen) * viewport.width) / (this.getRenderHeight(useScreen) * viewport.height);
  12463. };
  12464. /**
  12465. * Gets the current render width
  12466. * @param useScreen defines if screen size must be used (or the current render target if any)
  12467. * @returns a number defining the current render width
  12468. */
  12469. Engine.prototype.getRenderWidth = function (useScreen) {
  12470. if (useScreen === void 0) { useScreen = false; }
  12471. if (!useScreen && this._currentRenderTarget) {
  12472. return this._currentRenderTarget.width;
  12473. }
  12474. return this._gl.drawingBufferWidth;
  12475. };
  12476. /**
  12477. * Gets the current render height
  12478. * @param useScreen defines if screen size must be used (or the current render target if any)
  12479. * @returns a number defining the current render height
  12480. */
  12481. Engine.prototype.getRenderHeight = function (useScreen) {
  12482. if (useScreen === void 0) { useScreen = false; }
  12483. if (!useScreen && this._currentRenderTarget) {
  12484. return this._currentRenderTarget.height;
  12485. }
  12486. return this._gl.drawingBufferHeight;
  12487. };
  12488. /**
  12489. * Gets the HTML canvas attached with the current webGL context
  12490. * @returns a HTML canvas
  12491. */
  12492. Engine.prototype.getRenderingCanvas = function () {
  12493. return this._renderingCanvas;
  12494. };
  12495. /**
  12496. * Gets the client rect of the HTML canvas attached with the current webGL context
  12497. * @returns a client rectanglee
  12498. */
  12499. Engine.prototype.getRenderingCanvasClientRect = function () {
  12500. if (!this._renderingCanvas) {
  12501. return null;
  12502. }
  12503. return this._renderingCanvas.getBoundingClientRect();
  12504. };
  12505. /**
  12506. * Defines the hardware scaling level.
  12507. * By default the hardware scaling level is computed from the window device ratio.
  12508. * 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.
  12509. * @param level defines the level to use
  12510. */
  12511. Engine.prototype.setHardwareScalingLevel = function (level) {
  12512. this._hardwareScalingLevel = level;
  12513. this.resize();
  12514. };
  12515. /**
  12516. * Gets the current hardware scaling level.
  12517. * By default the hardware scaling level is computed from the window device ratio.
  12518. * 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.
  12519. * @returns a number indicating the current hardware scaling level
  12520. */
  12521. Engine.prototype.getHardwareScalingLevel = function () {
  12522. return this._hardwareScalingLevel;
  12523. };
  12524. /**
  12525. * Gets the list of loaded textures
  12526. * @returns an array containing all loaded textures
  12527. */
  12528. Engine.prototype.getLoadedTexturesCache = function () {
  12529. return this._internalTexturesCache;
  12530. };
  12531. /**
  12532. * Gets the object containing all engine capabilities
  12533. * @returns the EngineCapabilities object
  12534. */
  12535. Engine.prototype.getCaps = function () {
  12536. return this._caps;
  12537. };
  12538. Object.defineProperty(Engine.prototype, "drawCalls", {
  12539. /** @hidden */
  12540. get: function () {
  12541. BABYLON.Tools.Warn("drawCalls is deprecated. Please use SceneInstrumentation class");
  12542. return 0;
  12543. },
  12544. enumerable: true,
  12545. configurable: true
  12546. });
  12547. Object.defineProperty(Engine.prototype, "drawCallsPerfCounter", {
  12548. /** @hidden */
  12549. get: function () {
  12550. BABYLON.Tools.Warn("drawCallsPerfCounter is deprecated. Please use SceneInstrumentation class");
  12551. return null;
  12552. },
  12553. enumerable: true,
  12554. configurable: true
  12555. });
  12556. /**
  12557. * Gets the current depth function
  12558. * @returns a number defining the depth function
  12559. */
  12560. Engine.prototype.getDepthFunction = function () {
  12561. return this._depthCullingState.depthFunc;
  12562. };
  12563. /**
  12564. * Sets the current depth function
  12565. * @param depthFunc defines the function to use
  12566. */
  12567. Engine.prototype.setDepthFunction = function (depthFunc) {
  12568. this._depthCullingState.depthFunc = depthFunc;
  12569. };
  12570. /**
  12571. * Sets the current depth function to GREATER
  12572. */
  12573. Engine.prototype.setDepthFunctionToGreater = function () {
  12574. this._depthCullingState.depthFunc = this._gl.GREATER;
  12575. };
  12576. /**
  12577. * Sets the current depth function to GEQUAL
  12578. */
  12579. Engine.prototype.setDepthFunctionToGreaterOrEqual = function () {
  12580. this._depthCullingState.depthFunc = this._gl.GEQUAL;
  12581. };
  12582. /**
  12583. * Sets the current depth function to LESS
  12584. */
  12585. Engine.prototype.setDepthFunctionToLess = function () {
  12586. this._depthCullingState.depthFunc = this._gl.LESS;
  12587. };
  12588. /**
  12589. * Sets the current depth function to LEQUAL
  12590. */
  12591. Engine.prototype.setDepthFunctionToLessOrEqual = function () {
  12592. this._depthCullingState.depthFunc = this._gl.LEQUAL;
  12593. };
  12594. /**
  12595. * Gets a boolean indicating if stencil buffer is enabled
  12596. * @returns the current stencil buffer state
  12597. */
  12598. Engine.prototype.getStencilBuffer = function () {
  12599. return this._stencilState.stencilTest;
  12600. };
  12601. /**
  12602. * Enable or disable the stencil buffer
  12603. * @param enable defines if the stencil buffer must be enabled or disabled
  12604. */
  12605. Engine.prototype.setStencilBuffer = function (enable) {
  12606. this._stencilState.stencilTest = enable;
  12607. };
  12608. /**
  12609. * Gets the current stencil mask
  12610. * @returns a number defining the new stencil mask to use
  12611. */
  12612. Engine.prototype.getStencilMask = function () {
  12613. return this._stencilState.stencilMask;
  12614. };
  12615. /**
  12616. * Sets the current stencil mask
  12617. * @param mask defines the new stencil mask to use
  12618. */
  12619. Engine.prototype.setStencilMask = function (mask) {
  12620. this._stencilState.stencilMask = mask;
  12621. };
  12622. /**
  12623. * Gets the current stencil function
  12624. * @returns a number defining the stencil function to use
  12625. */
  12626. Engine.prototype.getStencilFunction = function () {
  12627. return this._stencilState.stencilFunc;
  12628. };
  12629. /**
  12630. * Gets the current stencil reference value
  12631. * @returns a number defining the stencil reference value to use
  12632. */
  12633. Engine.prototype.getStencilFunctionReference = function () {
  12634. return this._stencilState.stencilFuncRef;
  12635. };
  12636. /**
  12637. * Gets the current stencil mask
  12638. * @returns a number defining the stencil mask to use
  12639. */
  12640. Engine.prototype.getStencilFunctionMask = function () {
  12641. return this._stencilState.stencilFuncMask;
  12642. };
  12643. /**
  12644. * Sets the current stencil function
  12645. * @param stencilFunc defines the new stencil function to use
  12646. */
  12647. Engine.prototype.setStencilFunction = function (stencilFunc) {
  12648. this._stencilState.stencilFunc = stencilFunc;
  12649. };
  12650. /**
  12651. * Sets the current stencil reference
  12652. * @param reference defines the new stencil reference to use
  12653. */
  12654. Engine.prototype.setStencilFunctionReference = function (reference) {
  12655. this._stencilState.stencilFuncRef = reference;
  12656. };
  12657. /**
  12658. * Sets the current stencil mask
  12659. * @param mask defines the new stencil mask to use
  12660. */
  12661. Engine.prototype.setStencilFunctionMask = function (mask) {
  12662. this._stencilState.stencilFuncMask = mask;
  12663. };
  12664. /**
  12665. * Gets the current stencil operation when stencil fails
  12666. * @returns a number defining stencil operation to use when stencil fails
  12667. */
  12668. Engine.prototype.getStencilOperationFail = function () {
  12669. return this._stencilState.stencilOpStencilFail;
  12670. };
  12671. /**
  12672. * Gets the current stencil operation when depth fails
  12673. * @returns a number defining stencil operation to use when depth fails
  12674. */
  12675. Engine.prototype.getStencilOperationDepthFail = function () {
  12676. return this._stencilState.stencilOpDepthFail;
  12677. };
  12678. /**
  12679. * Gets the current stencil operation when stencil passes
  12680. * @returns a number defining stencil operation to use when stencil passes
  12681. */
  12682. Engine.prototype.getStencilOperationPass = function () {
  12683. return this._stencilState.stencilOpStencilDepthPass;
  12684. };
  12685. /**
  12686. * Sets the stencil operation to use when stencil fails
  12687. * @param operation defines the stencil operation to use when stencil fails
  12688. */
  12689. Engine.prototype.setStencilOperationFail = function (operation) {
  12690. this._stencilState.stencilOpStencilFail = operation;
  12691. };
  12692. /**
  12693. * Sets the stencil operation to use when depth fails
  12694. * @param operation defines the stencil operation to use when depth fails
  12695. */
  12696. Engine.prototype.setStencilOperationDepthFail = function (operation) {
  12697. this._stencilState.stencilOpDepthFail = operation;
  12698. };
  12699. /**
  12700. * Sets the stencil operation to use when stencil passes
  12701. * @param operation defines the stencil operation to use when stencil passes
  12702. */
  12703. Engine.prototype.setStencilOperationPass = function (operation) {
  12704. this._stencilState.stencilOpStencilDepthPass = operation;
  12705. };
  12706. /**
  12707. * Sets a boolean indicating if the dithering state is enabled or disabled
  12708. * @param value defines the dithering state
  12709. */
  12710. Engine.prototype.setDitheringState = function (value) {
  12711. if (value) {
  12712. this._gl.enable(this._gl.DITHER);
  12713. }
  12714. else {
  12715. this._gl.disable(this._gl.DITHER);
  12716. }
  12717. };
  12718. /**
  12719. * Sets a boolean indicating if the rasterizer state is enabled or disabled
  12720. * @param value defines the rasterizer state
  12721. */
  12722. Engine.prototype.setRasterizerState = function (value) {
  12723. if (value) {
  12724. this._gl.disable(this._gl.RASTERIZER_DISCARD);
  12725. }
  12726. else {
  12727. this._gl.enable(this._gl.RASTERIZER_DISCARD);
  12728. }
  12729. };
  12730. /**
  12731. * stop executing a render loop function and remove it from the execution array
  12732. * @param renderFunction defines the function to be removed. If not provided all functions will be removed.
  12733. */
  12734. Engine.prototype.stopRenderLoop = function (renderFunction) {
  12735. if (!renderFunction) {
  12736. this._activeRenderLoops = [];
  12737. return;
  12738. }
  12739. var index = this._activeRenderLoops.indexOf(renderFunction);
  12740. if (index >= 0) {
  12741. this._activeRenderLoops.splice(index, 1);
  12742. }
  12743. };
  12744. /** @hidden */
  12745. Engine.prototype._renderLoop = function () {
  12746. if (!this._contextWasLost) {
  12747. var shouldRender = true;
  12748. if (!this.renderEvenInBackground && this._windowIsBackground) {
  12749. shouldRender = false;
  12750. }
  12751. if (shouldRender) {
  12752. // Start new frame
  12753. this.beginFrame();
  12754. for (var index = 0; index < this._activeRenderLoops.length; index++) {
  12755. var renderFunction = this._activeRenderLoops[index];
  12756. renderFunction();
  12757. }
  12758. // Present
  12759. this.endFrame();
  12760. }
  12761. }
  12762. if (this._activeRenderLoops.length > 0) {
  12763. // Register new frame
  12764. var requester = null;
  12765. if (this._vrDisplay && this._vrDisplay.isPresenting)
  12766. requester = this._vrDisplay;
  12767. this._frameHandler = BABYLON.Tools.QueueNewFrame(this._bindedRenderFunction, requester);
  12768. }
  12769. else {
  12770. this._renderingQueueLaunched = false;
  12771. }
  12772. };
  12773. /**
  12774. * Register and execute a render loop. The engine can have more than one render function
  12775. * @param renderFunction defines the function to continuously execute
  12776. */
  12777. Engine.prototype.runRenderLoop = function (renderFunction) {
  12778. if (this._activeRenderLoops.indexOf(renderFunction) !== -1) {
  12779. return;
  12780. }
  12781. this._activeRenderLoops.push(renderFunction);
  12782. if (!this._renderingQueueLaunched) {
  12783. this._renderingQueueLaunched = true;
  12784. this._bindedRenderFunction = this._renderLoop.bind(this);
  12785. this._frameHandler = BABYLON.Tools.QueueNewFrame(this._bindedRenderFunction);
  12786. }
  12787. };
  12788. /**
  12789. * Toggle full screen mode
  12790. * @param requestPointerLock defines if a pointer lock should be requested from the user
  12791. * @param options defines an option object to be sent to the requestFullscreen function
  12792. */
  12793. Engine.prototype.switchFullscreen = function (requestPointerLock) {
  12794. if (this.isFullscreen) {
  12795. BABYLON.Tools.ExitFullscreen();
  12796. }
  12797. else {
  12798. this._pointerLockRequested = requestPointerLock;
  12799. if (this._renderingCanvas) {
  12800. BABYLON.Tools.RequestFullscreen(this._renderingCanvas);
  12801. }
  12802. }
  12803. };
  12804. /**
  12805. * Clear the current render buffer or the current render target (if any is set up)
  12806. * @param color defines the color to use
  12807. * @param backBuffer defines if the back buffer must be cleared
  12808. * @param depth defines if the depth buffer must be cleared
  12809. * @param stencil defines if the stencil buffer must be cleared
  12810. */
  12811. Engine.prototype.clear = function (color, backBuffer, depth, stencil) {
  12812. if (stencil === void 0) { stencil = false; }
  12813. this.applyStates();
  12814. var mode = 0;
  12815. if (backBuffer && color) {
  12816. this._gl.clearColor(color.r, color.g, color.b, color.a !== undefined ? color.a : 1.0);
  12817. mode |= this._gl.COLOR_BUFFER_BIT;
  12818. }
  12819. if (depth) {
  12820. this._gl.clearDepth(1.0);
  12821. mode |= this._gl.DEPTH_BUFFER_BIT;
  12822. }
  12823. if (stencil) {
  12824. this._gl.clearStencil(0);
  12825. mode |= this._gl.STENCIL_BUFFER_BIT;
  12826. }
  12827. this._gl.clear(mode);
  12828. };
  12829. /**
  12830. * Executes a scissor clear (ie. a clear on a specific portion of the screen)
  12831. * @param x defines the x-coordinate of the top left corner of the clear rectangle
  12832. * @param y defines the y-coordinate of the corner of the clear rectangle
  12833. * @param width defines the width of the clear rectangle
  12834. * @param height defines the height of the clear rectangle
  12835. * @param clearColor defines the clear color
  12836. */
  12837. Engine.prototype.scissorClear = function (x, y, width, height, clearColor) {
  12838. var gl = this._gl;
  12839. // Save state
  12840. var curScissor = gl.getParameter(gl.SCISSOR_TEST);
  12841. var curScissorBox = gl.getParameter(gl.SCISSOR_BOX);
  12842. // Change state
  12843. gl.enable(gl.SCISSOR_TEST);
  12844. gl.scissor(x, y, width, height);
  12845. // Clear
  12846. this.clear(clearColor, true, true, true);
  12847. // Restore state
  12848. gl.scissor(curScissorBox[0], curScissorBox[1], curScissorBox[2], curScissorBox[3]);
  12849. if (curScissor === true) {
  12850. gl.enable(gl.SCISSOR_TEST);
  12851. }
  12852. else {
  12853. gl.disable(gl.SCISSOR_TEST);
  12854. }
  12855. };
  12856. /**
  12857. * Set the WebGL's viewport
  12858. * @param viewport defines the viewport element to be used
  12859. * @param requiredWidth defines the width required for rendering. If not provided the rendering canvas' width is used
  12860. * @param requiredHeight defines the height required for rendering. If not provided the rendering canvas' height is used
  12861. */
  12862. Engine.prototype.setViewport = function (viewport, requiredWidth, requiredHeight) {
  12863. var width = requiredWidth || this.getRenderWidth();
  12864. var height = requiredHeight || this.getRenderHeight();
  12865. var x = viewport.x || 0;
  12866. var y = viewport.y || 0;
  12867. this._cachedViewport = viewport;
  12868. this._gl.viewport(x * width, y * height, width * viewport.width, height * viewport.height);
  12869. };
  12870. /**
  12871. * Directly set the WebGL Viewport
  12872. * @param x defines the x coordinate of the viewport (in screen space)
  12873. * @param y defines the y coordinate of the viewport (in screen space)
  12874. * @param width defines the width of the viewport (in screen space)
  12875. * @param height defines the height of the viewport (in screen space)
  12876. * @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
  12877. */
  12878. Engine.prototype.setDirectViewport = function (x, y, width, height) {
  12879. var currentViewport = this._cachedViewport;
  12880. this._cachedViewport = null;
  12881. this._gl.viewport(x, y, width, height);
  12882. return currentViewport;
  12883. };
  12884. /**
  12885. * Begin a new frame
  12886. */
  12887. Engine.prototype.beginFrame = function () {
  12888. this.onBeginFrameObservable.notifyObservers(this);
  12889. this._measureFps();
  12890. };
  12891. /**
  12892. * Enf the current frame
  12893. */
  12894. Engine.prototype.endFrame = function () {
  12895. // Force a flush in case we are using a bad OS.
  12896. if (this._badOS) {
  12897. this.flushFramebuffer();
  12898. }
  12899. // Submit frame to the vr device, if enabled
  12900. if (this._vrDisplay && this._vrDisplay.isPresenting) {
  12901. // TODO: We should only submit the frame if we read frameData successfully.
  12902. this._vrDisplay.submitFrame();
  12903. }
  12904. this.onEndFrameObservable.notifyObservers(this);
  12905. };
  12906. /**
  12907. * Resize the view according to the canvas' size
  12908. */
  12909. Engine.prototype.resize = function () {
  12910. // We're not resizing the size of the canvas while in VR mode & presenting
  12911. if (!(this._vrDisplay && this._vrDisplay.isPresenting)) {
  12912. var width = this._renderingCanvas ? this._renderingCanvas.clientWidth : window.innerWidth;
  12913. var height = this._renderingCanvas ? this._renderingCanvas.clientHeight : window.innerHeight;
  12914. this.setSize(width / this._hardwareScalingLevel, height / this._hardwareScalingLevel);
  12915. }
  12916. };
  12917. /**
  12918. * Force a specific size of the canvas
  12919. * @param width defines the new canvas' width
  12920. * @param height defines the new canvas' height
  12921. */
  12922. Engine.prototype.setSize = function (width, height) {
  12923. if (!this._renderingCanvas) {
  12924. return;
  12925. }
  12926. if (this._renderingCanvas.width === width && this._renderingCanvas.height === height) {
  12927. return;
  12928. }
  12929. this._renderingCanvas.width = width;
  12930. this._renderingCanvas.height = height;
  12931. for (var index = 0; index < this.scenes.length; index++) {
  12932. var scene = this.scenes[index];
  12933. for (var camIndex = 0; camIndex < scene.cameras.length; camIndex++) {
  12934. var cam = scene.cameras[camIndex];
  12935. cam._currentRenderId = 0;
  12936. }
  12937. }
  12938. if (this.onResizeObservable.hasObservers) {
  12939. this.onResizeObservable.notifyObservers(this);
  12940. }
  12941. };
  12942. // WebVR functions
  12943. /**
  12944. * Gets a boolean indicating if a webVR device was detected
  12945. * @returns true if a webVR device was detected
  12946. */
  12947. Engine.prototype.isVRDevicePresent = function () {
  12948. return !!this._vrDisplay;
  12949. };
  12950. /**
  12951. * Gets the current webVR device
  12952. * @returns the current webVR device (or null)
  12953. */
  12954. Engine.prototype.getVRDevice = function () {
  12955. return this._vrDisplay;
  12956. };
  12957. /**
  12958. * Initializes a webVR display and starts listening to display change events
  12959. * The onVRDisplayChangedObservable will be notified upon these changes
  12960. * @returns The onVRDisplayChangedObservable
  12961. */
  12962. Engine.prototype.initWebVR = function () {
  12963. this.initWebVRAsync();
  12964. return this.onVRDisplayChangedObservable;
  12965. };
  12966. /**
  12967. * Initializes a webVR display and starts listening to display change events
  12968. * The onVRDisplayChangedObservable will be notified upon these changes
  12969. * @returns A promise containing a VRDisplay and if vr is supported
  12970. */
  12971. Engine.prototype.initWebVRAsync = function () {
  12972. var _this = this;
  12973. var notifyObservers = function () {
  12974. var eventArgs = {
  12975. vrDisplay: _this._vrDisplay,
  12976. vrSupported: _this._vrSupported
  12977. };
  12978. _this.onVRDisplayChangedObservable.notifyObservers(eventArgs);
  12979. _this._webVRInitPromise = new Promise(function (res) { res(eventArgs); });
  12980. };
  12981. if (!this._onVrDisplayConnect) {
  12982. this._onVrDisplayConnect = function (event) {
  12983. _this._vrDisplay = event.display;
  12984. notifyObservers();
  12985. };
  12986. this._onVrDisplayDisconnect = function () {
  12987. _this._vrDisplay.cancelAnimationFrame(_this._frameHandler);
  12988. _this._vrDisplay = undefined;
  12989. _this._frameHandler = BABYLON.Tools.QueueNewFrame(_this._bindedRenderFunction);
  12990. notifyObservers();
  12991. };
  12992. this._onVrDisplayPresentChange = function () {
  12993. _this._vrExclusivePointerMode = _this._vrDisplay && _this._vrDisplay.isPresenting;
  12994. };
  12995. window.addEventListener('vrdisplayconnect', this._onVrDisplayConnect);
  12996. window.addEventListener('vrdisplaydisconnect', this._onVrDisplayDisconnect);
  12997. window.addEventListener('vrdisplaypresentchange', this._onVrDisplayPresentChange);
  12998. }
  12999. this._webVRInitPromise = this._webVRInitPromise || this._getVRDisplaysAsync();
  13000. this._webVRInitPromise.then(notifyObservers);
  13001. return this._webVRInitPromise;
  13002. };
  13003. /**
  13004. * Call this function to switch to webVR mode
  13005. * Will do nothing if webVR is not supported or if there is no webVR device
  13006. * @see http://doc.babylonjs.com/how_to/webvr_camera
  13007. */
  13008. Engine.prototype.enableVR = function () {
  13009. var _this = this;
  13010. if (this._vrDisplay && !this._vrDisplay.isPresenting) {
  13011. var onResolved = function () {
  13012. _this.onVRRequestPresentComplete.notifyObservers(true);
  13013. _this._onVRFullScreenTriggered();
  13014. };
  13015. var onRejected = function () {
  13016. _this.onVRRequestPresentComplete.notifyObservers(false);
  13017. };
  13018. this.onVRRequestPresentStart.notifyObservers(this);
  13019. this._vrDisplay.requestPresent([{ source: this.getRenderingCanvas() }]).then(onResolved).catch(onRejected);
  13020. }
  13021. };
  13022. /**
  13023. * Call this function to leave webVR mode
  13024. * Will do nothing if webVR is not supported or if there is no webVR device
  13025. * @see http://doc.babylonjs.com/how_to/webvr_camera
  13026. */
  13027. Engine.prototype.disableVR = function () {
  13028. if (this._vrDisplay && this._vrDisplay.isPresenting) {
  13029. this._vrDisplay.exitPresent().then(this._onVRFullScreenTriggered).catch(this._onVRFullScreenTriggered);
  13030. }
  13031. };
  13032. Engine.prototype._getVRDisplaysAsync = function () {
  13033. var _this = this;
  13034. return new Promise(function (res, rej) {
  13035. if (navigator.getVRDisplays) {
  13036. navigator.getVRDisplays().then(function (devices) {
  13037. _this._vrSupported = true;
  13038. // note that devices may actually be an empty array. This is fine;
  13039. // we expect this._vrDisplay to be undefined in this case.
  13040. _this._vrDisplay = devices[0];
  13041. res({
  13042. vrDisplay: _this._vrDisplay,
  13043. vrSupported: _this._vrSupported
  13044. });
  13045. });
  13046. }
  13047. else {
  13048. _this._vrDisplay = undefined;
  13049. _this._vrSupported = false;
  13050. res({
  13051. vrDisplay: _this._vrDisplay,
  13052. vrSupported: _this._vrSupported
  13053. });
  13054. }
  13055. });
  13056. };
  13057. /**
  13058. * Binds the frame buffer to the specified texture.
  13059. * @param texture The texture to render to or null for the default canvas
  13060. * @param faceIndex The face of the texture to render to in case of cube texture
  13061. * @param requiredWidth The width of the target to render to
  13062. * @param requiredHeight The height of the target to render to
  13063. * @param forceFullscreenViewport Forces the viewport to be the entire texture/screen if true
  13064. * @param depthStencilTexture The depth stencil texture to use to render
  13065. */
  13066. Engine.prototype.bindFramebuffer = function (texture, faceIndex, requiredWidth, requiredHeight, forceFullscreenViewport, depthStencilTexture) {
  13067. if (this._currentRenderTarget) {
  13068. this.unBindFramebuffer(this._currentRenderTarget);
  13069. }
  13070. this._currentRenderTarget = texture;
  13071. this.bindUnboundFramebuffer(texture._MSAAFramebuffer ? texture._MSAAFramebuffer : texture._framebuffer);
  13072. var gl = this._gl;
  13073. if (texture.isCube) {
  13074. if (faceIndex === undefined) {
  13075. faceIndex = 0;
  13076. }
  13077. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, texture._webGLTexture, 0);
  13078. if (depthStencilTexture) {
  13079. if (depthStencilTexture._generateStencilBuffer) {
  13080. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_STENCIL_ATTACHMENT, gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, depthStencilTexture._webGLTexture, 0);
  13081. }
  13082. else {
  13083. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, depthStencilTexture._webGLTexture, 0);
  13084. }
  13085. }
  13086. }
  13087. if (this._cachedViewport && !forceFullscreenViewport) {
  13088. this.setViewport(this._cachedViewport, requiredWidth, requiredHeight);
  13089. }
  13090. else {
  13091. gl.viewport(0, 0, requiredWidth || texture.width, requiredHeight || texture.height);
  13092. }
  13093. this.wipeCaches();
  13094. };
  13095. Engine.prototype.bindUnboundFramebuffer = function (framebuffer) {
  13096. if (this._currentFramebuffer !== framebuffer) {
  13097. this._gl.bindFramebuffer(this._gl.FRAMEBUFFER, framebuffer);
  13098. this._currentFramebuffer = framebuffer;
  13099. }
  13100. };
  13101. /**
  13102. * Unbind the current render target texture from the webGL context
  13103. * @param texture defines the render target texture to unbind
  13104. * @param disableGenerateMipMaps defines a boolean indicating that mipmaps must not be generated
  13105. * @param onBeforeUnbind defines a function which will be called before the effective unbind
  13106. */
  13107. Engine.prototype.unBindFramebuffer = function (texture, disableGenerateMipMaps, onBeforeUnbind) {
  13108. if (disableGenerateMipMaps === void 0) { disableGenerateMipMaps = false; }
  13109. this._currentRenderTarget = null;
  13110. // If MSAA, we need to bitblt back to main texture
  13111. var gl = this._gl;
  13112. if (texture._MSAAFramebuffer) {
  13113. gl.bindFramebuffer(gl.READ_FRAMEBUFFER, texture._MSAAFramebuffer);
  13114. gl.bindFramebuffer(gl.DRAW_FRAMEBUFFER, texture._framebuffer);
  13115. gl.blitFramebuffer(0, 0, texture.width, texture.height, 0, 0, texture.width, texture.height, gl.COLOR_BUFFER_BIT, gl.NEAREST);
  13116. }
  13117. if (texture.generateMipMaps && !disableGenerateMipMaps && !texture.isCube) {
  13118. this._bindTextureDirectly(gl.TEXTURE_2D, texture, true);
  13119. gl.generateMipmap(gl.TEXTURE_2D);
  13120. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  13121. }
  13122. if (onBeforeUnbind) {
  13123. if (texture._MSAAFramebuffer) {
  13124. // Bind the correct framebuffer
  13125. this.bindUnboundFramebuffer(texture._framebuffer);
  13126. }
  13127. onBeforeUnbind();
  13128. }
  13129. this.bindUnboundFramebuffer(null);
  13130. };
  13131. /**
  13132. * Unbind a list of render target textures from the webGL context
  13133. * This is used only when drawBuffer extension or webGL2 are active
  13134. * @param textures defines the render target textures to unbind
  13135. * @param disableGenerateMipMaps defines a boolean indicating that mipmaps must not be generated
  13136. * @param onBeforeUnbind defines a function which will be called before the effective unbind
  13137. */
  13138. Engine.prototype.unBindMultiColorAttachmentFramebuffer = function (textures, disableGenerateMipMaps, onBeforeUnbind) {
  13139. if (disableGenerateMipMaps === void 0) { disableGenerateMipMaps = false; }
  13140. this._currentRenderTarget = null;
  13141. // If MSAA, we need to bitblt back to main texture
  13142. var gl = this._gl;
  13143. if (textures[0]._MSAAFramebuffer) {
  13144. gl.bindFramebuffer(gl.READ_FRAMEBUFFER, textures[0]._MSAAFramebuffer);
  13145. gl.bindFramebuffer(gl.DRAW_FRAMEBUFFER, textures[0]._framebuffer);
  13146. var attachments = textures[0]._attachments;
  13147. if (!attachments) {
  13148. attachments = new Array(textures.length);
  13149. textures[0]._attachments = attachments;
  13150. }
  13151. for (var i = 0; i < textures.length; i++) {
  13152. var texture = textures[i];
  13153. for (var j = 0; j < attachments.length; j++) {
  13154. attachments[j] = gl.NONE;
  13155. }
  13156. attachments[i] = gl[this.webGLVersion > 1 ? "COLOR_ATTACHMENT" + i : "COLOR_ATTACHMENT" + i + "_WEBGL"];
  13157. gl.readBuffer(attachments[i]);
  13158. gl.drawBuffers(attachments);
  13159. gl.blitFramebuffer(0, 0, texture.width, texture.height, 0, 0, texture.width, texture.height, gl.COLOR_BUFFER_BIT, gl.NEAREST);
  13160. }
  13161. for (var i = 0; i < attachments.length; i++) {
  13162. attachments[i] = gl[this.webGLVersion > 1 ? "COLOR_ATTACHMENT" + i : "COLOR_ATTACHMENT" + i + "_WEBGL"];
  13163. }
  13164. gl.drawBuffers(attachments);
  13165. }
  13166. for (var i = 0; i < textures.length; i++) {
  13167. var texture = textures[i];
  13168. if (texture.generateMipMaps && !disableGenerateMipMaps && !texture.isCube) {
  13169. this._bindTextureDirectly(gl.TEXTURE_2D, texture);
  13170. gl.generateMipmap(gl.TEXTURE_2D);
  13171. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  13172. }
  13173. }
  13174. if (onBeforeUnbind) {
  13175. if (textures[0]._MSAAFramebuffer) {
  13176. // Bind the correct framebuffer
  13177. this.bindUnboundFramebuffer(textures[0]._framebuffer);
  13178. }
  13179. onBeforeUnbind();
  13180. }
  13181. this.bindUnboundFramebuffer(null);
  13182. };
  13183. /**
  13184. * Force the mipmap generation for the given render target texture
  13185. * @param texture defines the render target texture to use
  13186. */
  13187. Engine.prototype.generateMipMapsForCubemap = function (texture) {
  13188. if (texture.generateMipMaps) {
  13189. var gl = this._gl;
  13190. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  13191. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  13192. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  13193. }
  13194. };
  13195. /**
  13196. * Force a webGL flush (ie. a flush of all waiting webGL commands)
  13197. */
  13198. Engine.prototype.flushFramebuffer = function () {
  13199. this._gl.flush();
  13200. };
  13201. /**
  13202. * Unbind the current render target and bind the default framebuffer
  13203. */
  13204. Engine.prototype.restoreDefaultFramebuffer = function () {
  13205. if (this._currentRenderTarget) {
  13206. this.unBindFramebuffer(this._currentRenderTarget);
  13207. }
  13208. else {
  13209. this.bindUnboundFramebuffer(null);
  13210. }
  13211. if (this._cachedViewport) {
  13212. this.setViewport(this._cachedViewport);
  13213. }
  13214. this.wipeCaches();
  13215. };
  13216. // UBOs
  13217. /**
  13218. * Create an uniform buffer
  13219. * @see http://doc.babylonjs.com/features/webgl2#uniform-buffer-objets
  13220. * @param elements defines the content of the uniform buffer
  13221. * @returns the webGL uniform buffer
  13222. */
  13223. Engine.prototype.createUniformBuffer = function (elements) {
  13224. var ubo = this._gl.createBuffer();
  13225. if (!ubo) {
  13226. throw new Error("Unable to create uniform buffer");
  13227. }
  13228. this.bindUniformBuffer(ubo);
  13229. if (elements instanceof Float32Array) {
  13230. this._gl.bufferData(this._gl.UNIFORM_BUFFER, elements, this._gl.STATIC_DRAW);
  13231. }
  13232. else {
  13233. this._gl.bufferData(this._gl.UNIFORM_BUFFER, new Float32Array(elements), this._gl.STATIC_DRAW);
  13234. }
  13235. this.bindUniformBuffer(null);
  13236. ubo.references = 1;
  13237. return ubo;
  13238. };
  13239. /**
  13240. * Create a dynamic uniform buffer
  13241. * @see http://doc.babylonjs.com/features/webgl2#uniform-buffer-objets
  13242. * @param elements defines the content of the uniform buffer
  13243. * @returns the webGL uniform buffer
  13244. */
  13245. Engine.prototype.createDynamicUniformBuffer = function (elements) {
  13246. var ubo = this._gl.createBuffer();
  13247. if (!ubo) {
  13248. throw new Error("Unable to create dynamic uniform buffer");
  13249. }
  13250. this.bindUniformBuffer(ubo);
  13251. if (elements instanceof Float32Array) {
  13252. this._gl.bufferData(this._gl.UNIFORM_BUFFER, elements, this._gl.DYNAMIC_DRAW);
  13253. }
  13254. else {
  13255. this._gl.bufferData(this._gl.UNIFORM_BUFFER, new Float32Array(elements), this._gl.DYNAMIC_DRAW);
  13256. }
  13257. this.bindUniformBuffer(null);
  13258. ubo.references = 1;
  13259. return ubo;
  13260. };
  13261. /**
  13262. * Update an existing uniform buffer
  13263. * @see http://doc.babylonjs.com/features/webgl2#uniform-buffer-objets
  13264. * @param uniformBuffer defines the target uniform buffer
  13265. * @param elements defines the content to update
  13266. * @param offset defines the offset in the uniform buffer where update should start
  13267. * @param count defines the size of the data to update
  13268. */
  13269. Engine.prototype.updateUniformBuffer = function (uniformBuffer, elements, offset, count) {
  13270. this.bindUniformBuffer(uniformBuffer);
  13271. if (offset === undefined) {
  13272. offset = 0;
  13273. }
  13274. if (count === undefined) {
  13275. if (elements instanceof Float32Array) {
  13276. this._gl.bufferSubData(this._gl.UNIFORM_BUFFER, offset, elements);
  13277. }
  13278. else {
  13279. this._gl.bufferSubData(this._gl.UNIFORM_BUFFER, offset, new Float32Array(elements));
  13280. }
  13281. }
  13282. else {
  13283. if (elements instanceof Float32Array) {
  13284. this._gl.bufferSubData(this._gl.UNIFORM_BUFFER, 0, elements.subarray(offset, offset + count));
  13285. }
  13286. else {
  13287. this._gl.bufferSubData(this._gl.UNIFORM_BUFFER, 0, new Float32Array(elements).subarray(offset, offset + count));
  13288. }
  13289. }
  13290. this.bindUniformBuffer(null);
  13291. };
  13292. // VBOs
  13293. Engine.prototype._resetVertexBufferBinding = function () {
  13294. this.bindArrayBuffer(null);
  13295. this._cachedVertexBuffers = null;
  13296. };
  13297. /**
  13298. * Creates a vertex buffer
  13299. * @param data the data for the vertex buffer
  13300. * @returns the new WebGL static buffer
  13301. */
  13302. Engine.prototype.createVertexBuffer = function (data) {
  13303. var vbo = this._gl.createBuffer();
  13304. if (!vbo) {
  13305. throw new Error("Unable to create vertex buffer");
  13306. }
  13307. this.bindArrayBuffer(vbo);
  13308. if (data instanceof Array) {
  13309. this._gl.bufferData(this._gl.ARRAY_BUFFER, new Float32Array(data), this._gl.STATIC_DRAW);
  13310. }
  13311. else {
  13312. this._gl.bufferData(this._gl.ARRAY_BUFFER, data, this._gl.STATIC_DRAW);
  13313. }
  13314. this._resetVertexBufferBinding();
  13315. vbo.references = 1;
  13316. return vbo;
  13317. };
  13318. /**
  13319. * Creates a dynamic vertex buffer
  13320. * @param data the data for the dynamic vertex buffer
  13321. * @returns the new WebGL dynamic buffer
  13322. */
  13323. Engine.prototype.createDynamicVertexBuffer = function (data) {
  13324. var vbo = this._gl.createBuffer();
  13325. if (!vbo) {
  13326. throw new Error("Unable to create dynamic vertex buffer");
  13327. }
  13328. this.bindArrayBuffer(vbo);
  13329. if (data instanceof Array) {
  13330. this._gl.bufferData(this._gl.ARRAY_BUFFER, new Float32Array(data), this._gl.DYNAMIC_DRAW);
  13331. }
  13332. else {
  13333. this._gl.bufferData(this._gl.ARRAY_BUFFER, data, this._gl.DYNAMIC_DRAW);
  13334. }
  13335. this._resetVertexBufferBinding();
  13336. vbo.references = 1;
  13337. return vbo;
  13338. };
  13339. /**
  13340. * Update a dynamic index buffer
  13341. * @param indexBuffer defines the target index buffer
  13342. * @param indices defines the data to update
  13343. * @param offset defines the offset in the target index buffer where update should start
  13344. */
  13345. Engine.prototype.updateDynamicIndexBuffer = function (indexBuffer, indices, offset) {
  13346. if (offset === void 0) { offset = 0; }
  13347. // Force cache update
  13348. this._currentBoundBuffer[this._gl.ELEMENT_ARRAY_BUFFER] = null;
  13349. this.bindIndexBuffer(indexBuffer);
  13350. var arrayBuffer;
  13351. if (indices instanceof Uint16Array || indices instanceof Uint32Array) {
  13352. arrayBuffer = indices;
  13353. }
  13354. else {
  13355. arrayBuffer = indexBuffer.is32Bits ? new Uint32Array(indices) : new Uint16Array(indices);
  13356. }
  13357. this._gl.bufferData(this._gl.ELEMENT_ARRAY_BUFFER, arrayBuffer, this._gl.DYNAMIC_DRAW);
  13358. this._resetIndexBufferBinding();
  13359. };
  13360. /**
  13361. * Updates a dynamic vertex buffer.
  13362. * @param vertexBuffer the vertex buffer to update
  13363. * @param data the data used to update the vertex buffer
  13364. * @param byteOffset the byte offset of the data
  13365. * @param byteLength the byte length of the data
  13366. */
  13367. Engine.prototype.updateDynamicVertexBuffer = function (vertexBuffer, data, byteOffset, byteLength) {
  13368. this.bindArrayBuffer(vertexBuffer);
  13369. if (byteOffset === undefined) {
  13370. byteOffset = 0;
  13371. }
  13372. if (byteLength === undefined) {
  13373. if (data instanceof Array) {
  13374. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, byteOffset, new Float32Array(data));
  13375. }
  13376. else {
  13377. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, byteOffset, data);
  13378. }
  13379. }
  13380. else {
  13381. if (data instanceof Array) {
  13382. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, new Float32Array(data).subarray(byteOffset, byteOffset + byteLength));
  13383. }
  13384. else {
  13385. if (data instanceof ArrayBuffer) {
  13386. data = new Uint8Array(data, byteOffset, byteLength);
  13387. }
  13388. else {
  13389. data = new Uint8Array(data.buffer, data.byteOffset + byteOffset, byteLength);
  13390. }
  13391. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, data);
  13392. }
  13393. }
  13394. this._resetVertexBufferBinding();
  13395. };
  13396. Engine.prototype._resetIndexBufferBinding = function () {
  13397. this.bindIndexBuffer(null);
  13398. this._cachedIndexBuffer = null;
  13399. };
  13400. /**
  13401. * Creates a new index buffer
  13402. * @param indices defines the content of the index buffer
  13403. * @param updatable defines if the index buffer must be updatable
  13404. * @returns a new webGL buffer
  13405. */
  13406. Engine.prototype.createIndexBuffer = function (indices, updatable) {
  13407. var vbo = this._gl.createBuffer();
  13408. if (!vbo) {
  13409. throw new Error("Unable to create index buffer");
  13410. }
  13411. this.bindIndexBuffer(vbo);
  13412. // Check for 32 bits indices
  13413. var arrayBuffer;
  13414. var need32Bits = false;
  13415. if (indices instanceof Uint16Array) {
  13416. arrayBuffer = indices;
  13417. }
  13418. else {
  13419. //check 32 bit support
  13420. if (this._caps.uintIndices) {
  13421. if (indices instanceof Uint32Array) {
  13422. arrayBuffer = indices;
  13423. need32Bits = true;
  13424. }
  13425. else {
  13426. //number[] or Int32Array, check if 32 bit is necessary
  13427. for (var index = 0; index < indices.length; index++) {
  13428. if (indices[index] > 65535) {
  13429. need32Bits = true;
  13430. break;
  13431. }
  13432. }
  13433. arrayBuffer = need32Bits ? new Uint32Array(indices) : new Uint16Array(indices);
  13434. }
  13435. }
  13436. else {
  13437. //no 32 bit support, force conversion to 16 bit (values greater 16 bit are lost)
  13438. arrayBuffer = new Uint16Array(indices);
  13439. }
  13440. }
  13441. this._gl.bufferData(this._gl.ELEMENT_ARRAY_BUFFER, arrayBuffer, updatable ? this._gl.DYNAMIC_DRAW : this._gl.STATIC_DRAW);
  13442. this._resetIndexBufferBinding();
  13443. vbo.references = 1;
  13444. vbo.is32Bits = need32Bits;
  13445. return vbo;
  13446. };
  13447. /**
  13448. * Bind a webGL buffer to the webGL context
  13449. * @param buffer defines the buffer to bind
  13450. */
  13451. Engine.prototype.bindArrayBuffer = function (buffer) {
  13452. if (!this._vaoRecordInProgress) {
  13453. this._unbindVertexArrayObject();
  13454. }
  13455. this.bindBuffer(buffer, this._gl.ARRAY_BUFFER);
  13456. };
  13457. /**
  13458. * Bind an uniform buffer to the current webGL context
  13459. * @param buffer defines the buffer to bind
  13460. */
  13461. Engine.prototype.bindUniformBuffer = function (buffer) {
  13462. this._gl.bindBuffer(this._gl.UNIFORM_BUFFER, buffer);
  13463. };
  13464. /**
  13465. * Bind a buffer to the current webGL context at a given location
  13466. * @param buffer defines the buffer to bind
  13467. * @param location defines the index where to bind the buffer
  13468. */
  13469. Engine.prototype.bindUniformBufferBase = function (buffer, location) {
  13470. this._gl.bindBufferBase(this._gl.UNIFORM_BUFFER, location, buffer);
  13471. };
  13472. /**
  13473. * Bind a specific block at a given index in a specific shader program
  13474. * @param shaderProgram defines the shader program
  13475. * @param blockName defines the block name
  13476. * @param index defines the index where to bind the block
  13477. */
  13478. Engine.prototype.bindUniformBlock = function (shaderProgram, blockName, index) {
  13479. var uniformLocation = this._gl.getUniformBlockIndex(shaderProgram, blockName);
  13480. this._gl.uniformBlockBinding(shaderProgram, uniformLocation, index);
  13481. };
  13482. ;
  13483. Engine.prototype.bindIndexBuffer = function (buffer) {
  13484. if (!this._vaoRecordInProgress) {
  13485. this._unbindVertexArrayObject();
  13486. }
  13487. this.bindBuffer(buffer, this._gl.ELEMENT_ARRAY_BUFFER);
  13488. };
  13489. Engine.prototype.bindBuffer = function (buffer, target) {
  13490. if (this._vaoRecordInProgress || this._currentBoundBuffer[target] !== buffer) {
  13491. this._gl.bindBuffer(target, buffer);
  13492. this._currentBoundBuffer[target] = buffer;
  13493. }
  13494. };
  13495. /**
  13496. * update the bound buffer with the given data
  13497. * @param data defines the data to update
  13498. */
  13499. Engine.prototype.updateArrayBuffer = function (data) {
  13500. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, data);
  13501. };
  13502. Engine.prototype._vertexAttribPointer = function (buffer, indx, size, type, normalized, stride, offset) {
  13503. var pointer = this._currentBufferPointers[indx];
  13504. var changed = false;
  13505. if (!pointer.active) {
  13506. changed = true;
  13507. pointer.active = true;
  13508. pointer.index = indx;
  13509. pointer.size = size;
  13510. pointer.type = type;
  13511. pointer.normalized = normalized;
  13512. pointer.stride = stride;
  13513. pointer.offset = offset;
  13514. pointer.buffer = buffer;
  13515. }
  13516. else {
  13517. if (pointer.buffer !== buffer) {
  13518. pointer.buffer = buffer;
  13519. changed = true;
  13520. }
  13521. if (pointer.size !== size) {
  13522. pointer.size = size;
  13523. changed = true;
  13524. }
  13525. if (pointer.type !== type) {
  13526. pointer.type = type;
  13527. changed = true;
  13528. }
  13529. if (pointer.normalized !== normalized) {
  13530. pointer.normalized = normalized;
  13531. changed = true;
  13532. }
  13533. if (pointer.stride !== stride) {
  13534. pointer.stride = stride;
  13535. changed = true;
  13536. }
  13537. if (pointer.offset !== offset) {
  13538. pointer.offset = offset;
  13539. changed = true;
  13540. }
  13541. }
  13542. if (changed || this._vaoRecordInProgress) {
  13543. this.bindArrayBuffer(buffer);
  13544. this._gl.vertexAttribPointer(indx, size, type, normalized, stride, offset);
  13545. }
  13546. };
  13547. Engine.prototype._bindIndexBufferWithCache = function (indexBuffer) {
  13548. if (indexBuffer == null) {
  13549. return;
  13550. }
  13551. if (this._cachedIndexBuffer !== indexBuffer) {
  13552. this._cachedIndexBuffer = indexBuffer;
  13553. this.bindIndexBuffer(indexBuffer);
  13554. this._uintIndicesCurrentlySet = indexBuffer.is32Bits;
  13555. }
  13556. };
  13557. Engine.prototype._bindVertexBuffersAttributes = function (vertexBuffers, effect) {
  13558. var attributes = effect.getAttributesNames();
  13559. if (!this._vaoRecordInProgress) {
  13560. this._unbindVertexArrayObject();
  13561. }
  13562. this.unbindAllAttributes();
  13563. for (var index = 0; index < attributes.length; index++) {
  13564. var order = effect.getAttributeLocation(index);
  13565. if (order >= 0) {
  13566. var vertexBuffer = vertexBuffers[attributes[index]];
  13567. if (!vertexBuffer) {
  13568. continue;
  13569. }
  13570. this._gl.enableVertexAttribArray(order);
  13571. if (!this._vaoRecordInProgress) {
  13572. this._vertexAttribArraysEnabled[order] = true;
  13573. }
  13574. var buffer = vertexBuffer.getBuffer();
  13575. if (buffer) {
  13576. this._vertexAttribPointer(buffer, order, vertexBuffer.getSize(), vertexBuffer.type, vertexBuffer.normalized, vertexBuffer.byteStride, vertexBuffer.byteOffset);
  13577. if (vertexBuffer.getIsInstanced()) {
  13578. this._gl.vertexAttribDivisor(order, vertexBuffer.getInstanceDivisor());
  13579. if (!this._vaoRecordInProgress) {
  13580. this._currentInstanceLocations.push(order);
  13581. this._currentInstanceBuffers.push(buffer);
  13582. }
  13583. }
  13584. }
  13585. }
  13586. }
  13587. };
  13588. /**
  13589. * Records a vertex array object
  13590. * @see http://doc.babylonjs.com/features/webgl2#vertex-array-objects
  13591. * @param vertexBuffers defines the list of vertex buffers to store
  13592. * @param indexBuffer defines the index buffer to store
  13593. * @param effect defines the effect to store
  13594. * @returns the new vertex array object
  13595. */
  13596. Engine.prototype.recordVertexArrayObject = function (vertexBuffers, indexBuffer, effect) {
  13597. var vao = this._gl.createVertexArray();
  13598. this._vaoRecordInProgress = true;
  13599. this._gl.bindVertexArray(vao);
  13600. this._mustWipeVertexAttributes = true;
  13601. this._bindVertexBuffersAttributes(vertexBuffers, effect);
  13602. this.bindIndexBuffer(indexBuffer);
  13603. this._vaoRecordInProgress = false;
  13604. this._gl.bindVertexArray(null);
  13605. return vao;
  13606. };
  13607. /**
  13608. * Bind a specific vertex array object
  13609. * @see http://doc.babylonjs.com/features/webgl2#vertex-array-objects
  13610. * @param vertexArrayObject defines the vertex array object to bind
  13611. * @param indexBuffer defines the index buffer to bind
  13612. */
  13613. Engine.prototype.bindVertexArrayObject = function (vertexArrayObject, indexBuffer) {
  13614. if (this._cachedVertexArrayObject !== vertexArrayObject) {
  13615. this._cachedVertexArrayObject = vertexArrayObject;
  13616. this._gl.bindVertexArray(vertexArrayObject);
  13617. this._cachedVertexBuffers = null;
  13618. this._cachedIndexBuffer = null;
  13619. this._uintIndicesCurrentlySet = indexBuffer != null && indexBuffer.is32Bits;
  13620. this._mustWipeVertexAttributes = true;
  13621. }
  13622. };
  13623. /**
  13624. * Bind webGl buffers directly to the webGL context
  13625. * @param vertexBuffer defines the vertex buffer to bind
  13626. * @param indexBuffer defines the index buffer to bind
  13627. * @param vertexDeclaration defines the vertex declaration to use with the vertex buffer
  13628. * @param vertexStrideSize defines the vertex stride of the vertex buffer
  13629. * @param effect defines the effect associated with the vertex buffer
  13630. */
  13631. Engine.prototype.bindBuffersDirectly = function (vertexBuffer, indexBuffer, vertexDeclaration, vertexStrideSize, effect) {
  13632. if (this._cachedVertexBuffers !== vertexBuffer || this._cachedEffectForVertexBuffers !== effect) {
  13633. this._cachedVertexBuffers = vertexBuffer;
  13634. this._cachedEffectForVertexBuffers = effect;
  13635. var attributesCount = effect.getAttributesCount();
  13636. this._unbindVertexArrayObject();
  13637. this.unbindAllAttributes();
  13638. var offset = 0;
  13639. for (var index = 0; index < attributesCount; index++) {
  13640. if (index < vertexDeclaration.length) {
  13641. var order = effect.getAttributeLocation(index);
  13642. if (order >= 0) {
  13643. this._gl.enableVertexAttribArray(order);
  13644. this._vertexAttribArraysEnabled[order] = true;
  13645. this._vertexAttribPointer(vertexBuffer, order, vertexDeclaration[index], this._gl.FLOAT, false, vertexStrideSize, offset);
  13646. }
  13647. offset += vertexDeclaration[index] * 4;
  13648. }
  13649. }
  13650. }
  13651. this._bindIndexBufferWithCache(indexBuffer);
  13652. };
  13653. Engine.prototype._unbindVertexArrayObject = function () {
  13654. if (!this._cachedVertexArrayObject) {
  13655. return;
  13656. }
  13657. this._cachedVertexArrayObject = null;
  13658. this._gl.bindVertexArray(null);
  13659. };
  13660. /**
  13661. * Bind a list of vertex buffers to the webGL context
  13662. * @param vertexBuffers defines the list of vertex buffers to bind
  13663. * @param indexBuffer defines the index buffer to bind
  13664. * @param effect defines the effect associated with the vertex buffers
  13665. */
  13666. Engine.prototype.bindBuffers = function (vertexBuffers, indexBuffer, effect) {
  13667. if (this._cachedVertexBuffers !== vertexBuffers || this._cachedEffectForVertexBuffers !== effect) {
  13668. this._cachedVertexBuffers = vertexBuffers;
  13669. this._cachedEffectForVertexBuffers = effect;
  13670. this._bindVertexBuffersAttributes(vertexBuffers, effect);
  13671. }
  13672. this._bindIndexBufferWithCache(indexBuffer);
  13673. };
  13674. /**
  13675. * Unbind all instance attributes
  13676. */
  13677. Engine.prototype.unbindInstanceAttributes = function () {
  13678. var boundBuffer;
  13679. for (var i = 0, ul = this._currentInstanceLocations.length; i < ul; i++) {
  13680. var instancesBuffer = this._currentInstanceBuffers[i];
  13681. if (boundBuffer != instancesBuffer && instancesBuffer.references) {
  13682. boundBuffer = instancesBuffer;
  13683. this.bindArrayBuffer(instancesBuffer);
  13684. }
  13685. var offsetLocation = this._currentInstanceLocations[i];
  13686. this._gl.vertexAttribDivisor(offsetLocation, 0);
  13687. }
  13688. this._currentInstanceBuffers.length = 0;
  13689. this._currentInstanceLocations.length = 0;
  13690. };
  13691. /**
  13692. * Release and free the memory of a vertex array object
  13693. * @param vao defines the vertex array object to delete
  13694. */
  13695. Engine.prototype.releaseVertexArrayObject = function (vao) {
  13696. this._gl.deleteVertexArray(vao);
  13697. };
  13698. /** @hidden */
  13699. Engine.prototype._releaseBuffer = function (buffer) {
  13700. buffer.references--;
  13701. if (buffer.references === 0) {
  13702. this._gl.deleteBuffer(buffer);
  13703. return true;
  13704. }
  13705. return false;
  13706. };
  13707. /**
  13708. * Creates a webGL buffer to use with instanciation
  13709. * @param capacity defines the size of the buffer
  13710. * @returns the webGL buffer
  13711. */
  13712. Engine.prototype.createInstancesBuffer = function (capacity) {
  13713. var buffer = this._gl.createBuffer();
  13714. if (!buffer) {
  13715. throw new Error("Unable to create instance buffer");
  13716. }
  13717. buffer.capacity = capacity;
  13718. this.bindArrayBuffer(buffer);
  13719. this._gl.bufferData(this._gl.ARRAY_BUFFER, capacity, this._gl.DYNAMIC_DRAW);
  13720. return buffer;
  13721. };
  13722. /**
  13723. * Delete a webGL buffer used with instanciation
  13724. * @param buffer defines the webGL buffer to delete
  13725. */
  13726. Engine.prototype.deleteInstancesBuffer = function (buffer) {
  13727. this._gl.deleteBuffer(buffer);
  13728. };
  13729. /**
  13730. * Update the content of a webGL buffer used with instanciation and bind it to the webGL context
  13731. * @param instancesBuffer defines the webGL buffer to update and bind
  13732. * @param data defines the data to store in the buffer
  13733. * @param offsetLocations defines the offsets or attributes information used to determine where data must be stored in the buffer
  13734. */
  13735. Engine.prototype.updateAndBindInstancesBuffer = function (instancesBuffer, data, offsetLocations) {
  13736. this.bindArrayBuffer(instancesBuffer);
  13737. if (data) {
  13738. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, data);
  13739. }
  13740. if (offsetLocations[0].index !== undefined) {
  13741. var stride = 0;
  13742. for (var i = 0; i < offsetLocations.length; i++) {
  13743. var ai = offsetLocations[i];
  13744. stride += ai.attributeSize * 4;
  13745. }
  13746. for (var i = 0; i < offsetLocations.length; i++) {
  13747. var ai = offsetLocations[i];
  13748. if (!this._vertexAttribArraysEnabled[ai.index]) {
  13749. this._gl.enableVertexAttribArray(ai.index);
  13750. this._vertexAttribArraysEnabled[ai.index] = true;
  13751. }
  13752. this._vertexAttribPointer(instancesBuffer, ai.index, ai.attributeSize, ai.attribyteType || this._gl.FLOAT, ai.normalized || false, stride, ai.offset);
  13753. this._gl.vertexAttribDivisor(ai.index, 1);
  13754. this._currentInstanceLocations.push(ai.index);
  13755. this._currentInstanceBuffers.push(instancesBuffer);
  13756. }
  13757. }
  13758. else {
  13759. for (var index = 0; index < 4; index++) {
  13760. var offsetLocation = offsetLocations[index];
  13761. if (!this._vertexAttribArraysEnabled[offsetLocation]) {
  13762. this._gl.enableVertexAttribArray(offsetLocation);
  13763. this._vertexAttribArraysEnabled[offsetLocation] = true;
  13764. }
  13765. this._vertexAttribPointer(instancesBuffer, offsetLocation, 4, this._gl.FLOAT, false, 64, index * 16);
  13766. this._gl.vertexAttribDivisor(offsetLocation, 1);
  13767. this._currentInstanceLocations.push(offsetLocation);
  13768. this._currentInstanceBuffers.push(instancesBuffer);
  13769. }
  13770. }
  13771. };
  13772. /**
  13773. * Apply all cached states (depth, culling, stencil and alpha)
  13774. */
  13775. Engine.prototype.applyStates = function () {
  13776. this._depthCullingState.apply(this._gl);
  13777. this._stencilState.apply(this._gl);
  13778. this._alphaState.apply(this._gl);
  13779. };
  13780. /**
  13781. * Send a draw order
  13782. * @param useTriangles defines if triangles must be used to draw (else wireframe will be used)
  13783. * @param indexStart defines the starting index
  13784. * @param indexCount defines the number of index to draw
  13785. * @param instancesCount defines the number of instances to draw (if instanciation is enabled)
  13786. */
  13787. Engine.prototype.draw = function (useTriangles, indexStart, indexCount, instancesCount) {
  13788. this.drawElementsType(useTriangles ? BABYLON.Material.TriangleFillMode : BABYLON.Material.WireFrameFillMode, indexStart, indexCount, instancesCount);
  13789. };
  13790. /**
  13791. * Draw a list of points
  13792. * @param verticesStart defines the index of first vertex to draw
  13793. * @param verticesCount defines the count of vertices to draw
  13794. * @param instancesCount defines the number of instances to draw (if instanciation is enabled)
  13795. */
  13796. Engine.prototype.drawPointClouds = function (verticesStart, verticesCount, instancesCount) {
  13797. this.drawArraysType(BABYLON.Material.PointFillMode, verticesStart, verticesCount, instancesCount);
  13798. };
  13799. /**
  13800. * Draw a list of unindexed primitives
  13801. * @param useTriangles defines if triangles must be used to draw (else wireframe will be used)
  13802. * @param verticesStart defines the index of first vertex to draw
  13803. * @param verticesCount defines the count of vertices to draw
  13804. * @param instancesCount defines the number of instances to draw (if instanciation is enabled)
  13805. */
  13806. Engine.prototype.drawUnIndexed = function (useTriangles, verticesStart, verticesCount, instancesCount) {
  13807. this.drawArraysType(useTriangles ? BABYLON.Material.TriangleFillMode : BABYLON.Material.WireFrameFillMode, verticesStart, verticesCount, instancesCount);
  13808. };
  13809. /**
  13810. * Draw a list of indexed primitives
  13811. * @param fillMode defines the primitive to use
  13812. * @param indexStart defines the starting index
  13813. * @param indexCount defines the number of index to draw
  13814. * @param instancesCount defines the number of instances to draw (if instanciation is enabled)
  13815. */
  13816. Engine.prototype.drawElementsType = function (fillMode, indexStart, indexCount, instancesCount) {
  13817. // Apply states
  13818. this.applyStates();
  13819. this._drawCalls.addCount(1, false);
  13820. // Render
  13821. var drawMode = this._drawMode(fillMode);
  13822. var indexFormat = this._uintIndicesCurrentlySet ? this._gl.UNSIGNED_INT : this._gl.UNSIGNED_SHORT;
  13823. var mult = this._uintIndicesCurrentlySet ? 4 : 2;
  13824. if (instancesCount) {
  13825. this._gl.drawElementsInstanced(drawMode, indexCount, indexFormat, indexStart * mult, instancesCount);
  13826. }
  13827. else {
  13828. this._gl.drawElements(drawMode, indexCount, indexFormat, indexStart * mult);
  13829. }
  13830. };
  13831. /**
  13832. * Draw a list of unindexed primitives
  13833. * @param fillMode defines the primitive to use
  13834. * @param verticesStart defines the index of first vertex to draw
  13835. * @param verticesCount defines the count of vertices to draw
  13836. * @param instancesCount defines the number of instances to draw (if instanciation is enabled)
  13837. */
  13838. Engine.prototype.drawArraysType = function (fillMode, verticesStart, verticesCount, instancesCount) {
  13839. // Apply states
  13840. this.applyStates();
  13841. this._drawCalls.addCount(1, false);
  13842. var drawMode = this._drawMode(fillMode);
  13843. if (instancesCount) {
  13844. this._gl.drawArraysInstanced(drawMode, verticesStart, verticesCount, instancesCount);
  13845. }
  13846. else {
  13847. this._gl.drawArrays(drawMode, verticesStart, verticesCount);
  13848. }
  13849. };
  13850. Engine.prototype._drawMode = function (fillMode) {
  13851. switch (fillMode) {
  13852. // Triangle views
  13853. case BABYLON.Material.TriangleFillMode:
  13854. return this._gl.TRIANGLES;
  13855. case BABYLON.Material.PointFillMode:
  13856. return this._gl.POINTS;
  13857. case BABYLON.Material.WireFrameFillMode:
  13858. return this._gl.LINES;
  13859. // Draw modes
  13860. case BABYLON.Material.PointListDrawMode:
  13861. return this._gl.POINTS;
  13862. case BABYLON.Material.LineListDrawMode:
  13863. return this._gl.LINES;
  13864. case BABYLON.Material.LineLoopDrawMode:
  13865. return this._gl.LINE_LOOP;
  13866. case BABYLON.Material.LineStripDrawMode:
  13867. return this._gl.LINE_STRIP;
  13868. case BABYLON.Material.TriangleStripDrawMode:
  13869. return this._gl.TRIANGLE_STRIP;
  13870. case BABYLON.Material.TriangleFanDrawMode:
  13871. return this._gl.TRIANGLE_FAN;
  13872. default:
  13873. return this._gl.TRIANGLES;
  13874. }
  13875. };
  13876. // Shaders
  13877. /** @hidden */
  13878. Engine.prototype._releaseEffect = function (effect) {
  13879. if (this._compiledEffects[effect._key]) {
  13880. delete this._compiledEffects[effect._key];
  13881. this._deleteProgram(effect.getProgram());
  13882. }
  13883. };
  13884. /** @hidden */
  13885. Engine.prototype._deleteProgram = function (program) {
  13886. if (program) {
  13887. program.__SPECTOR_rebuildProgram = null;
  13888. if (program.transformFeedback) {
  13889. this.deleteTransformFeedback(program.transformFeedback);
  13890. program.transformFeedback = null;
  13891. }
  13892. this._gl.deleteProgram(program);
  13893. }
  13894. };
  13895. /**
  13896. * Create a new effect (used to store vertex/fragment shaders)
  13897. * @param baseName defines the base name of the effect (The name of file without .fragment.fx or .vertex.fx)
  13898. * @param attributesNamesOrOptions defines either a list of attribute names or an EffectCreationOptions object
  13899. * @param uniformsNamesOrEngine defines either a list of uniform names or the engine to use
  13900. * @param samplers defines an array of string used to represent textures
  13901. * @param defines defines the string containing the defines to use to compile the shaders
  13902. * @param fallbacks defines the list of potential fallbacks to use if shader conmpilation fails
  13903. * @param onCompiled defines a function to call when the effect creation is successful
  13904. * @param onError defines a function to call when the effect creation has failed
  13905. * @param indexParameters defines an object containing the index values to use to compile shaders (like the maximum number of simultaneous lights)
  13906. * @returns the new Effect
  13907. */
  13908. Engine.prototype.createEffect = function (baseName, attributesNamesOrOptions, uniformsNamesOrEngine, samplers, defines, fallbacks, onCompiled, onError, indexParameters) {
  13909. var vertex = baseName.vertexElement || baseName.vertex || baseName;
  13910. var fragment = baseName.fragmentElement || baseName.fragment || baseName;
  13911. var name = vertex + "+" + fragment + "@" + (defines ? defines : attributesNamesOrOptions.defines);
  13912. if (this._compiledEffects[name]) {
  13913. var compiledEffect = this._compiledEffects[name];
  13914. if (onCompiled && compiledEffect.isReady()) {
  13915. onCompiled(compiledEffect);
  13916. }
  13917. return compiledEffect;
  13918. }
  13919. var effect = new BABYLON.Effect(baseName, attributesNamesOrOptions, uniformsNamesOrEngine, samplers, this, defines, fallbacks, onCompiled, onError, indexParameters);
  13920. effect._key = name;
  13921. this._compiledEffects[name] = effect;
  13922. return effect;
  13923. };
  13924. /**
  13925. * Create an effect to use with particle systems
  13926. * @param fragmentName defines the base name of the effect (The name of file without .fragment.fx)
  13927. * @param uniformsNames defines a list of attribute names
  13928. * @param samplers defines an array of string used to represent textures
  13929. * @param defines defines the string containing the defines to use to compile the shaders
  13930. * @param fallbacks defines the list of potential fallbacks to use if shader conmpilation fails
  13931. * @param onCompiled defines a function to call when the effect creation is successful
  13932. * @param onError defines a function to call when the effect creation has failed
  13933. * @returns the new Effect
  13934. */
  13935. Engine.prototype.createEffectForParticles = function (fragmentName, uniformsNames, samplers, defines, fallbacks, onCompiled, onError) {
  13936. if (uniformsNames === void 0) { uniformsNames = []; }
  13937. if (samplers === void 0) { samplers = []; }
  13938. if (defines === void 0) { defines = ""; }
  13939. return this.createEffect({
  13940. vertex: "particles",
  13941. fragmentElement: fragmentName
  13942. }, ["position", "color", "options"], ["view", "projection"].concat(uniformsNames), ["diffuseSampler"].concat(samplers), defines, fallbacks, onCompiled, onError);
  13943. };
  13944. /**
  13945. * Directly creates a webGL program
  13946. * @param vertexCode defines the vertex shader code to use
  13947. * @param fragmentCode defines the fragment shader code to use
  13948. * @param context defines the webGL context to use (if not set, the current one will be used)
  13949. * @param transformFeedbackVaryings defines the list of transform feedback varyings to use
  13950. * @returns the new webGL program
  13951. */
  13952. Engine.prototype.createRawShaderProgram = function (vertexCode, fragmentCode, context, transformFeedbackVaryings) {
  13953. if (transformFeedbackVaryings === void 0) { transformFeedbackVaryings = null; }
  13954. context = context || this._gl;
  13955. var vertexShader = compileRawShader(context, vertexCode, "vertex");
  13956. var fragmentShader = compileRawShader(context, fragmentCode, "fragment");
  13957. return this._createShaderProgram(vertexShader, fragmentShader, context, transformFeedbackVaryings);
  13958. };
  13959. /**
  13960. * Creates a webGL program
  13961. * @param vertexCode defines the vertex shader code to use
  13962. * @param fragmentCode defines the fragment shader code to use
  13963. * @param defines defines the string containing the defines to use to compile the shaders
  13964. * @param context defines the webGL context to use (if not set, the current one will be used)
  13965. * @param transformFeedbackVaryings defines the list of transform feedback varyings to use
  13966. * @returns the new webGL program
  13967. */
  13968. Engine.prototype.createShaderProgram = function (vertexCode, fragmentCode, defines, context, transformFeedbackVaryings) {
  13969. if (transformFeedbackVaryings === void 0) { transformFeedbackVaryings = null; }
  13970. context = context || this._gl;
  13971. this.onBeforeShaderCompilationObservable.notifyObservers(this);
  13972. var shaderVersion = (this._webGLVersion > 1) ? "#version 300 es\n#define WEBGL2 \n" : "";
  13973. var vertexShader = compileShader(context, vertexCode, "vertex", defines, shaderVersion);
  13974. var fragmentShader = compileShader(context, fragmentCode, "fragment", defines, shaderVersion);
  13975. var program = this._createShaderProgram(vertexShader, fragmentShader, context, transformFeedbackVaryings);
  13976. this.onAfterShaderCompilationObservable.notifyObservers(this);
  13977. return program;
  13978. };
  13979. Engine.prototype._createShaderProgram = function (vertexShader, fragmentShader, context, transformFeedbackVaryings) {
  13980. if (transformFeedbackVaryings === void 0) { transformFeedbackVaryings = null; }
  13981. var shaderProgram = context.createProgram();
  13982. if (!shaderProgram) {
  13983. throw new Error("Unable to create program");
  13984. }
  13985. context.attachShader(shaderProgram, vertexShader);
  13986. context.attachShader(shaderProgram, fragmentShader);
  13987. if (this.webGLVersion > 1 && transformFeedbackVaryings) {
  13988. var transformFeedback = this.createTransformFeedback();
  13989. this.bindTransformFeedback(transformFeedback);
  13990. this.setTranformFeedbackVaryings(shaderProgram, transformFeedbackVaryings);
  13991. shaderProgram.transformFeedback = transformFeedback;
  13992. }
  13993. context.linkProgram(shaderProgram);
  13994. if (this.webGLVersion > 1 && transformFeedbackVaryings) {
  13995. this.bindTransformFeedback(null);
  13996. }
  13997. var linked = context.getProgramParameter(shaderProgram, context.LINK_STATUS);
  13998. if (!linked) {
  13999. context.validateProgram(shaderProgram);
  14000. var error = context.getProgramInfoLog(shaderProgram);
  14001. if (error) {
  14002. throw new Error(error);
  14003. }
  14004. }
  14005. context.deleteShader(vertexShader);
  14006. context.deleteShader(fragmentShader);
  14007. return shaderProgram;
  14008. };
  14009. /**
  14010. * Gets the list of webGL uniform locations associated with a specific program based on a list of uniform names
  14011. * @param shaderProgram defines the webGL program to use
  14012. * @param uniformsNames defines the list of uniform names
  14013. * @returns an array of webGL uniform locations
  14014. */
  14015. Engine.prototype.getUniforms = function (shaderProgram, uniformsNames) {
  14016. var results = new Array();
  14017. for (var index = 0; index < uniformsNames.length; index++) {
  14018. results.push(this._gl.getUniformLocation(shaderProgram, uniformsNames[index]));
  14019. }
  14020. return results;
  14021. };
  14022. /**
  14023. * Gets the lsit of active attributes for a given webGL program
  14024. * @param shaderProgram defines the webGL program to use
  14025. * @param attributesNames defines the list of attribute names to get
  14026. * @returns an array of indices indicating the offset of each attribute
  14027. */
  14028. Engine.prototype.getAttributes = function (shaderProgram, attributesNames) {
  14029. var results = [];
  14030. for (var index = 0; index < attributesNames.length; index++) {
  14031. try {
  14032. results.push(this._gl.getAttribLocation(shaderProgram, attributesNames[index]));
  14033. }
  14034. catch (e) {
  14035. results.push(-1);
  14036. }
  14037. }
  14038. return results;
  14039. };
  14040. /**
  14041. * Activates an effect, mkaing it the current one (ie. the one used for rendering)
  14042. * @param effect defines the effect to activate
  14043. */
  14044. Engine.prototype.enableEffect = function (effect) {
  14045. if (!effect) {
  14046. return;
  14047. }
  14048. // Use program
  14049. this.bindSamplers(effect);
  14050. this._currentEffect = effect;
  14051. if (effect.onBind) {
  14052. effect.onBind(effect);
  14053. }
  14054. effect.onBindObservable.notifyObservers(effect);
  14055. };
  14056. /**
  14057. * Set the value of an uniform to an array of int32
  14058. * @param uniform defines the webGL uniform location where to store the value
  14059. * @param array defines the array of int32 to store
  14060. */
  14061. Engine.prototype.setIntArray = function (uniform, array) {
  14062. if (!uniform)
  14063. return;
  14064. this._gl.uniform1iv(uniform, array);
  14065. };
  14066. /**
  14067. * Set the value of an uniform to an array of int32 (stored as vec2)
  14068. * @param uniform defines the webGL uniform location where to store the value
  14069. * @param array defines the array of int32 to store
  14070. */
  14071. Engine.prototype.setIntArray2 = function (uniform, array) {
  14072. if (!uniform || array.length % 2 !== 0)
  14073. return;
  14074. this._gl.uniform2iv(uniform, array);
  14075. };
  14076. /**
  14077. * Set the value of an uniform to an array of int32 (stored as vec3)
  14078. * @param uniform defines the webGL uniform location where to store the value
  14079. * @param array defines the array of int32 to store
  14080. */
  14081. Engine.prototype.setIntArray3 = function (uniform, array) {
  14082. if (!uniform || array.length % 3 !== 0)
  14083. return;
  14084. this._gl.uniform3iv(uniform, array);
  14085. };
  14086. /**
  14087. * Set the value of an uniform to an array of int32 (stored as vec4)
  14088. * @param uniform defines the webGL uniform location where to store the value
  14089. * @param array defines the array of int32 to store
  14090. */
  14091. Engine.prototype.setIntArray4 = function (uniform, array) {
  14092. if (!uniform || array.length % 4 !== 0)
  14093. return;
  14094. this._gl.uniform4iv(uniform, array);
  14095. };
  14096. /**
  14097. * Set the value of an uniform to an array of float32
  14098. * @param uniform defines the webGL uniform location where to store the value
  14099. * @param array defines the array of float32 to store
  14100. */
  14101. Engine.prototype.setFloatArray = function (uniform, array) {
  14102. if (!uniform)
  14103. return;
  14104. this._gl.uniform1fv(uniform, array);
  14105. };
  14106. /**
  14107. * Set the value of an uniform to an array of float32 (stored as vec2)
  14108. * @param uniform defines the webGL uniform location where to store the value
  14109. * @param array defines the array of float32 to store
  14110. */
  14111. Engine.prototype.setFloatArray2 = function (uniform, array) {
  14112. if (!uniform || array.length % 2 !== 0)
  14113. return;
  14114. this._gl.uniform2fv(uniform, array);
  14115. };
  14116. /**
  14117. * Set the value of an uniform to an array of float32 (stored as vec3)
  14118. * @param uniform defines the webGL uniform location where to store the value
  14119. * @param array defines the array of float32 to store
  14120. */
  14121. Engine.prototype.setFloatArray3 = function (uniform, array) {
  14122. if (!uniform || array.length % 3 !== 0)
  14123. return;
  14124. this._gl.uniform3fv(uniform, array);
  14125. };
  14126. /**
  14127. * Set the value of an uniform to an array of float32 (stored as vec4)
  14128. * @param uniform defines the webGL uniform location where to store the value
  14129. * @param array defines the array of float32 to store
  14130. */
  14131. Engine.prototype.setFloatArray4 = function (uniform, array) {
  14132. if (!uniform || array.length % 4 !== 0)
  14133. return;
  14134. this._gl.uniform4fv(uniform, array);
  14135. };
  14136. /**
  14137. * Set the value of an uniform to an array of number
  14138. * @param uniform defines the webGL uniform location where to store the value
  14139. * @param array defines the array of number to store
  14140. */
  14141. Engine.prototype.setArray = function (uniform, array) {
  14142. if (!uniform)
  14143. return;
  14144. this._gl.uniform1fv(uniform, array);
  14145. };
  14146. /**
  14147. * Set the value of an uniform to an array of number (stored as vec2)
  14148. * @param uniform defines the webGL uniform location where to store the value
  14149. * @param array defines the array of number to store
  14150. */
  14151. Engine.prototype.setArray2 = function (uniform, array) {
  14152. if (!uniform || array.length % 2 !== 0)
  14153. return;
  14154. this._gl.uniform2fv(uniform, array);
  14155. };
  14156. /**
  14157. * Set the value of an uniform to an array of number (stored as vec3)
  14158. * @param uniform defines the webGL uniform location where to store the value
  14159. * @param array defines the array of number to store
  14160. */
  14161. Engine.prototype.setArray3 = function (uniform, array) {
  14162. if (!uniform || array.length % 3 !== 0)
  14163. return;
  14164. this._gl.uniform3fv(uniform, array);
  14165. };
  14166. /**
  14167. * Set the value of an uniform to an array of number (stored as vec4)
  14168. * @param uniform defines the webGL uniform location where to store the value
  14169. * @param array defines the array of number to store
  14170. */
  14171. Engine.prototype.setArray4 = function (uniform, array) {
  14172. if (!uniform || array.length % 4 !== 0)
  14173. return;
  14174. this._gl.uniform4fv(uniform, array);
  14175. };
  14176. /**
  14177. * Set the value of an uniform to an array of float32 (stored as matrices)
  14178. * @param uniform defines the webGL uniform location where to store the value
  14179. * @param matrices defines the array of float32 to store
  14180. */
  14181. Engine.prototype.setMatrices = function (uniform, matrices) {
  14182. if (!uniform)
  14183. return;
  14184. this._gl.uniformMatrix4fv(uniform, false, matrices);
  14185. };
  14186. /**
  14187. * Set the value of an uniform to a matrix
  14188. * @param uniform defines the webGL uniform location where to store the value
  14189. * @param matrix defines the matrix to store
  14190. */
  14191. Engine.prototype.setMatrix = function (uniform, matrix) {
  14192. if (!uniform)
  14193. return;
  14194. this._gl.uniformMatrix4fv(uniform, false, matrix.toArray());
  14195. };
  14196. /**
  14197. * Set the value of an uniform to a matrix (3x3)
  14198. * @param uniform defines the webGL uniform location where to store the value
  14199. * @param matrix defines the Float32Array representing the 3x3 matrix to store
  14200. */
  14201. Engine.prototype.setMatrix3x3 = function (uniform, matrix) {
  14202. if (!uniform)
  14203. return;
  14204. this._gl.uniformMatrix3fv(uniform, false, matrix);
  14205. };
  14206. /**
  14207. * Set the value of an uniform to a matrix (2x2)
  14208. * @param uniform defines the webGL uniform location where to store the value
  14209. * @param matrix defines the Float32Array representing the 2x2 matrix to store
  14210. */
  14211. Engine.prototype.setMatrix2x2 = function (uniform, matrix) {
  14212. if (!uniform)
  14213. return;
  14214. this._gl.uniformMatrix2fv(uniform, false, matrix);
  14215. };
  14216. /**
  14217. * Set the value of an uniform to a number (int)
  14218. * @param uniform defines the webGL uniform location where to store the value
  14219. * @param value defines the int number to store
  14220. */
  14221. Engine.prototype.setInt = function (uniform, value) {
  14222. if (!uniform)
  14223. return;
  14224. this._gl.uniform1i(uniform, value);
  14225. };
  14226. /**
  14227. * Set the value of an uniform to a number (float)
  14228. * @param uniform defines the webGL uniform location where to store the value
  14229. * @param value defines the float number to store
  14230. */
  14231. Engine.prototype.setFloat = function (uniform, value) {
  14232. if (!uniform)
  14233. return;
  14234. this._gl.uniform1f(uniform, value);
  14235. };
  14236. /**
  14237. * Set the value of an uniform to a vec2
  14238. * @param uniform defines the webGL uniform location where to store the value
  14239. * @param x defines the 1st component of the value
  14240. * @param y defines the 2nd component of the value
  14241. */
  14242. Engine.prototype.setFloat2 = function (uniform, x, y) {
  14243. if (!uniform)
  14244. return;
  14245. this._gl.uniform2f(uniform, x, y);
  14246. };
  14247. /**
  14248. * Set the value of an uniform to a vec3
  14249. * @param uniform defines the webGL uniform location where to store the value
  14250. * @param x defines the 1st component of the value
  14251. * @param y defines the 2nd component of the value
  14252. * @param z defines the 3rd component of the value
  14253. */
  14254. Engine.prototype.setFloat3 = function (uniform, x, y, z) {
  14255. if (!uniform)
  14256. return;
  14257. this._gl.uniform3f(uniform, x, y, z);
  14258. };
  14259. /**
  14260. * Set the value of an uniform to a boolean
  14261. * @param uniform defines the webGL uniform location where to store the value
  14262. * @param bool defines the boolean to store
  14263. */
  14264. Engine.prototype.setBool = function (uniform, bool) {
  14265. if (!uniform)
  14266. return;
  14267. this._gl.uniform1i(uniform, bool);
  14268. };
  14269. /**
  14270. * Set the value of an uniform to a vec4
  14271. * @param uniform defines the webGL uniform location where to store the value
  14272. * @param x defines the 1st component of the value
  14273. * @param y defines the 2nd component of the value
  14274. * @param z defines the 3rd component of the value
  14275. * @param w defines the 4th component of the value
  14276. */
  14277. Engine.prototype.setFloat4 = function (uniform, x, y, z, w) {
  14278. if (!uniform)
  14279. return;
  14280. this._gl.uniform4f(uniform, x, y, z, w);
  14281. };
  14282. /**
  14283. * Set the value of an uniform to a Color3
  14284. * @param uniform defines the webGL uniform location where to store the value
  14285. * @param color3 defines the color to store
  14286. */
  14287. Engine.prototype.setColor3 = function (uniform, color3) {
  14288. if (!uniform)
  14289. return;
  14290. this._gl.uniform3f(uniform, color3.r, color3.g, color3.b);
  14291. };
  14292. /**
  14293. * Set the value of an uniform to a Color3 and an alpha value
  14294. * @param uniform defines the webGL uniform location where to store the value
  14295. * @param color3 defines the color to store
  14296. * @param alpha defines the alpha component to store
  14297. */
  14298. Engine.prototype.setColor4 = function (uniform, color3, alpha) {
  14299. if (!uniform)
  14300. return;
  14301. this._gl.uniform4f(uniform, color3.r, color3.g, color3.b, alpha);
  14302. };
  14303. /**
  14304. * Sets a Color4 on a uniform variable
  14305. * @param uniform defines the uniform location
  14306. * @param color4 defines the value to be set
  14307. */
  14308. Engine.prototype.setDirectColor4 = function (uniform, color4) {
  14309. if (!uniform)
  14310. return;
  14311. this._gl.uniform4f(uniform, color4.r, color4.g, color4.b, color4.a);
  14312. };
  14313. // States
  14314. /**
  14315. * Set various states to the webGL context
  14316. * @param culling defines backface culling state
  14317. * @param zOffset defines the value to apply to zOffset (0 by default)
  14318. * @param force defines if states must be applied even if cache is up to date
  14319. * @param reverseSide defines if culling must be reversed (CCW instead of CW and CW instead of CCW)
  14320. */
  14321. Engine.prototype.setState = function (culling, zOffset, force, reverseSide) {
  14322. if (zOffset === void 0) { zOffset = 0; }
  14323. if (reverseSide === void 0) { reverseSide = false; }
  14324. // Culling
  14325. if (this._depthCullingState.cull !== culling || force) {
  14326. this._depthCullingState.cull = culling;
  14327. }
  14328. // Cull face
  14329. var cullFace = this.cullBackFaces ? this._gl.BACK : this._gl.FRONT;
  14330. if (this._depthCullingState.cullFace !== cullFace || force) {
  14331. this._depthCullingState.cullFace = cullFace;
  14332. }
  14333. // Z offset
  14334. this.setZOffset(zOffset);
  14335. // Front face
  14336. var frontFace = reverseSide ? this._gl.CW : this._gl.CCW;
  14337. if (this._depthCullingState.frontFace !== frontFace || force) {
  14338. this._depthCullingState.frontFace = frontFace;
  14339. }
  14340. };
  14341. /**
  14342. * Set the z offset to apply to current rendering
  14343. * @param value defines the offset to apply
  14344. */
  14345. Engine.prototype.setZOffset = function (value) {
  14346. this._depthCullingState.zOffset = value;
  14347. };
  14348. /**
  14349. * Gets the current value of the zOffset
  14350. * @returns the current zOffset state
  14351. */
  14352. Engine.prototype.getZOffset = function () {
  14353. return this._depthCullingState.zOffset;
  14354. };
  14355. /**
  14356. * Enable or disable depth buffering
  14357. * @param enable defines the state to set
  14358. */
  14359. Engine.prototype.setDepthBuffer = function (enable) {
  14360. this._depthCullingState.depthTest = enable;
  14361. };
  14362. /**
  14363. * Gets a boolean indicating if depth writing is enabled
  14364. * @returns the current depth writing state
  14365. */
  14366. Engine.prototype.getDepthWrite = function () {
  14367. return this._depthCullingState.depthMask;
  14368. };
  14369. /**
  14370. * Enable or disable depth writing
  14371. * @param enable defines the state to set
  14372. */
  14373. Engine.prototype.setDepthWrite = function (enable) {
  14374. this._depthCullingState.depthMask = enable;
  14375. };
  14376. /**
  14377. * Enable or disable color writing
  14378. * @param enable defines the state to set
  14379. */
  14380. Engine.prototype.setColorWrite = function (enable) {
  14381. this._gl.colorMask(enable, enable, enable, enable);
  14382. this._colorWrite = enable;
  14383. };
  14384. /**
  14385. * Gets a boolean indicating if color writing is enabled
  14386. * @returns the current color writing state
  14387. */
  14388. Engine.prototype.getColorWrite = function () {
  14389. return this._colorWrite;
  14390. };
  14391. /**
  14392. * Sets alpha constants used by some alpha blending modes
  14393. * @param r defines the red component
  14394. * @param g defines the green component
  14395. * @param b defines the blue component
  14396. * @param a defines the alpha component
  14397. */
  14398. Engine.prototype.setAlphaConstants = function (r, g, b, a) {
  14399. this._alphaState.setAlphaBlendConstants(r, g, b, a);
  14400. };
  14401. /**
  14402. * Sets the current alpha mode
  14403. * @param mode defines the mode to use (one of the BABYLON.Engine.ALPHA_XXX)
  14404. * @param noDepthWriteChange defines if depth writing state should remains unchanged (false by default)
  14405. * @see http://doc.babylonjs.com/resources/transparency_and_how_meshes_are_rendered
  14406. */
  14407. Engine.prototype.setAlphaMode = function (mode, noDepthWriteChange) {
  14408. if (noDepthWriteChange === void 0) { noDepthWriteChange = false; }
  14409. if (this._alphaMode === mode) {
  14410. return;
  14411. }
  14412. switch (mode) {
  14413. case Engine.ALPHA_DISABLE:
  14414. this._alphaState.alphaBlend = false;
  14415. break;
  14416. case Engine.ALPHA_PREMULTIPLIED:
  14417. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE_MINUS_SRC_ALPHA, this._gl.ONE, this._gl.ONE);
  14418. this._alphaState.alphaBlend = true;
  14419. break;
  14420. case Engine.ALPHA_PREMULTIPLIED_PORTERDUFF:
  14421. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE_MINUS_SRC_ALPHA, this._gl.ONE, this._gl.ONE_MINUS_SRC_ALPHA);
  14422. this._alphaState.alphaBlend = true;
  14423. break;
  14424. case Engine.ALPHA_COMBINE:
  14425. this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE_MINUS_SRC_ALPHA, this._gl.ONE, this._gl.ONE);
  14426. this._alphaState.alphaBlend = true;
  14427. break;
  14428. case Engine.ALPHA_ONEONE:
  14429. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE, this._gl.ZERO, this._gl.ONE);
  14430. this._alphaState.alphaBlend = true;
  14431. break;
  14432. case Engine.ALPHA_ADD:
  14433. this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE, this._gl.ZERO, this._gl.ONE);
  14434. this._alphaState.alphaBlend = true;
  14435. break;
  14436. case Engine.ALPHA_SUBTRACT:
  14437. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ZERO, this._gl.ONE_MINUS_SRC_COLOR, this._gl.ONE, this._gl.ONE);
  14438. this._alphaState.alphaBlend = true;
  14439. break;
  14440. case Engine.ALPHA_MULTIPLY:
  14441. this._alphaState.setAlphaBlendFunctionParameters(this._gl.DST_COLOR, this._gl.ZERO, this._gl.ONE, this._gl.ONE);
  14442. this._alphaState.alphaBlend = true;
  14443. break;
  14444. case Engine.ALPHA_MAXIMIZED:
  14445. this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE_MINUS_SRC_COLOR, this._gl.ONE, this._gl.ONE);
  14446. this._alphaState.alphaBlend = true;
  14447. break;
  14448. case Engine.ALPHA_INTERPOLATE:
  14449. this._alphaState.setAlphaBlendFunctionParameters(this._gl.CONSTANT_COLOR, this._gl.ONE_MINUS_CONSTANT_COLOR, this._gl.CONSTANT_ALPHA, this._gl.ONE_MINUS_CONSTANT_ALPHA);
  14450. this._alphaState.alphaBlend = true;
  14451. break;
  14452. case Engine.ALPHA_SCREENMODE:
  14453. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE_MINUS_SRC_COLOR, this._gl.ONE, this._gl.ONE_MINUS_SRC_ALPHA);
  14454. this._alphaState.alphaBlend = true;
  14455. break;
  14456. }
  14457. if (!noDepthWriteChange) {
  14458. this.setDepthWrite(mode === Engine.ALPHA_DISABLE);
  14459. }
  14460. this._alphaMode = mode;
  14461. };
  14462. /**
  14463. * Gets the current alpha mode
  14464. * @see http://doc.babylonjs.com/resources/transparency_and_how_meshes_are_rendered
  14465. * @returns the current alpha mode
  14466. */
  14467. Engine.prototype.getAlphaMode = function () {
  14468. return this._alphaMode;
  14469. };
  14470. // Textures
  14471. /**
  14472. * Force the entire cache to be cleared
  14473. * You should not have to use this function unless your engine needs to share the webGL context with another engine
  14474. * @param bruteForce defines a boolean to force clearing ALL caches (including stencil, detoh and alpha states)
  14475. */
  14476. Engine.prototype.wipeCaches = function (bruteForce) {
  14477. if (this.preventCacheWipeBetweenFrames && !bruteForce) {
  14478. return;
  14479. }
  14480. this._currentEffect = null;
  14481. if (bruteForce) {
  14482. this.resetTextureCache();
  14483. this._currentProgram = null;
  14484. this._stencilState.reset();
  14485. this._depthCullingState.reset();
  14486. this.setDepthFunctionToLessOrEqual();
  14487. this._alphaState.reset();
  14488. }
  14489. this._resetVertexBufferBinding();
  14490. this._cachedIndexBuffer = null;
  14491. this._cachedEffectForVertexBuffers = null;
  14492. this._unbindVertexArrayObject();
  14493. this.bindIndexBuffer(null);
  14494. };
  14495. /**
  14496. * Set the compressed texture format to use, based on the formats you have, and the formats
  14497. * supported by the hardware / browser.
  14498. *
  14499. * Khronos Texture Container (.ktx) files are used to support this. This format has the
  14500. * advantage of being specifically designed for OpenGL. Header elements directly correspond
  14501. * to API arguments needed to compressed textures. This puts the burden on the container
  14502. * generator to house the arcane code for determining these for current & future formats.
  14503. *
  14504. * for description see https://www.khronos.org/opengles/sdk/tools/KTX/
  14505. * for file layout see https://www.khronos.org/opengles/sdk/tools/KTX/file_format_spec/
  14506. *
  14507. * Note: The result of this call is not taken into account when a texture is base64.
  14508. *
  14509. * @param formatsAvailable defines the list of those format families you have created
  14510. * on your server. Syntax: '-' + format family + '.ktx'. (Case and order do not matter.)
  14511. *
  14512. * Current families are astc, dxt, pvrtc, etc2, & etc1.
  14513. * @returns The extension selected.
  14514. */
  14515. Engine.prototype.setTextureFormatToUse = function (formatsAvailable) {
  14516. for (var i = 0, len1 = this.texturesSupported.length; i < len1; i++) {
  14517. for (var j = 0, len2 = formatsAvailable.length; j < len2; j++) {
  14518. if (this._texturesSupported[i] === formatsAvailable[j].toLowerCase()) {
  14519. return this._textureFormatInUse = this._texturesSupported[i];
  14520. }
  14521. }
  14522. }
  14523. // actively set format to nothing, to allow this to be called more than once
  14524. // and possibly fail the 2nd time
  14525. this._textureFormatInUse = null;
  14526. return null;
  14527. };
  14528. /** @hidden */
  14529. Engine.prototype._createTexture = function () {
  14530. var texture = this._gl.createTexture();
  14531. if (!texture) {
  14532. throw new Error("Unable to create texture");
  14533. }
  14534. return texture;
  14535. };
  14536. /**
  14537. * Usually called from BABYLON.Texture.ts.
  14538. * Passed information to create a WebGLTexture
  14539. * @param urlArg defines a value which contains one of the following:
  14540. * * A conventional http URL, e.g. 'http://...' or 'file://...'
  14541. * * A base64 string of in-line texture data, e.g. 'data:image/jpg;base64,/...'
  14542. * * An indicator that data being passed using the buffer parameter, e.g. 'data:mytexture.jpg'
  14543. * @param noMipmap defines a boolean indicating that no mipmaps shall be generated. Ignored for compressed textures. They must be in the file
  14544. * @param invertY when true, image is flipped when loaded. You probably want true. Ignored for compressed textures. Must be flipped in the file
  14545. * @param scene needed for loading to the correct scene
  14546. * @param samplingMode mode with should be used sample / access the texture (Default: BABYLON.Texture.TRILINEAR_SAMPLINGMODE)
  14547. * @param onLoad optional callback to be called upon successful completion
  14548. * @param onError optional callback to be called upon failure
  14549. * @param buffer a source of a file previously fetched as either an ArrayBuffer (compressed or image format) or HTMLImageElement (image format)
  14550. * @param fallback an internal argument in case the function must be called again, due to etc1 not having alpha capabilities
  14551. * @param format internal format. Default: RGB when extension is '.jpg' else RGBA. Ignored for compressed textures
  14552. * @returns a InternalTexture for assignment back into BABYLON.Texture
  14553. */
  14554. Engine.prototype.createTexture = function (urlArg, noMipmap, invertY, scene, samplingMode, onLoad, onError, buffer, fallback, format) {
  14555. var _this = this;
  14556. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  14557. if (onLoad === void 0) { onLoad = null; }
  14558. if (onError === void 0) { onError = null; }
  14559. if (buffer === void 0) { buffer = null; }
  14560. if (fallback === void 0) { fallback = null; }
  14561. if (format === void 0) { format = null; }
  14562. var url = String(urlArg); // assign a new string, so that the original is still available in case of fallback
  14563. var fromData = url.substr(0, 5) === "data:";
  14564. var fromBlob = url.substr(0, 5) === "blob:";
  14565. var isBase64 = fromData && url.indexOf("base64") !== -1;
  14566. var texture = fallback ? fallback : new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_URL);
  14567. // establish the file extension, if possible
  14568. var lastDot = url.lastIndexOf('.');
  14569. var extension = (lastDot > 0) ? url.substring(lastDot).toLowerCase() : "";
  14570. var isDDS = this.getCaps().s3tc && (extension.indexOf(".dds") === 0);
  14571. var isTGA = (extension.indexOf(".tga") === 0);
  14572. // determine if a ktx file should be substituted
  14573. var isKTX = false;
  14574. if (this._textureFormatInUse && !isBase64 && !fallback) {
  14575. url = url.substring(0, lastDot) + this._textureFormatInUse;
  14576. isKTX = true;
  14577. }
  14578. if (scene) {
  14579. scene._addPendingData(texture);
  14580. }
  14581. texture.url = url;
  14582. texture.generateMipMaps = !noMipmap;
  14583. texture.samplingMode = samplingMode;
  14584. texture.invertY = invertY;
  14585. if (!this._doNotHandleContextLost) {
  14586. // Keep a link to the buffer only if we plan to handle context lost
  14587. texture._buffer = buffer;
  14588. }
  14589. var onLoadObserver = null;
  14590. if (onLoad && !fallback) {
  14591. onLoadObserver = texture.onLoadedObservable.add(onLoad);
  14592. }
  14593. if (!fallback)
  14594. this._internalTexturesCache.push(texture);
  14595. var onerror = function (message, exception) {
  14596. if (scene) {
  14597. scene._removePendingData(texture);
  14598. }
  14599. if (onLoadObserver) {
  14600. texture.onLoadedObservable.remove(onLoadObserver);
  14601. }
  14602. // fallback for when compressed file not found to try again. For instance, etc1 does not have an alpha capable type
  14603. if (isKTX) {
  14604. _this.createTexture(urlArg, noMipmap, invertY, scene, samplingMode, null, onError, buffer, texture);
  14605. }
  14606. else if (BABYLON.Tools.UseFallbackTexture) {
  14607. _this.createTexture(BABYLON.Tools.fallbackTexture, noMipmap, invertY, scene, samplingMode, null, onError, buffer, texture);
  14608. }
  14609. if (onError) {
  14610. onError(message || "Unknown error", exception);
  14611. }
  14612. };
  14613. var callback = null;
  14614. // processing for non-image formats
  14615. if (isKTX || isTGA || isDDS) {
  14616. if (isKTX) {
  14617. callback = function (data) {
  14618. var ktx = new BABYLON.KhronosTextureContainer(data, 1);
  14619. _this._prepareWebGLTexture(texture, scene, ktx.pixelWidth, ktx.pixelHeight, invertY, false, true, function () {
  14620. ktx.uploadLevels(_this._gl, !noMipmap);
  14621. return false;
  14622. }, samplingMode);
  14623. };
  14624. }
  14625. else if (isTGA) {
  14626. callback = function (arrayBuffer) {
  14627. var data = new Uint8Array(arrayBuffer);
  14628. var header = BABYLON.TGATools.GetTGAHeader(data);
  14629. _this._prepareWebGLTexture(texture, scene, header.width, header.height, invertY, noMipmap, false, function () {
  14630. BABYLON.TGATools.UploadContent(_this._gl, data);
  14631. return false;
  14632. }, samplingMode);
  14633. };
  14634. }
  14635. else if (isDDS) {
  14636. callback = function (data) {
  14637. var info = BABYLON.DDSTools.GetDDSInfo(data);
  14638. var loadMipmap = (info.isRGB || info.isLuminance || info.mipmapCount > 1) && !noMipmap && ((info.width >> (info.mipmapCount - 1)) === 1);
  14639. _this._prepareWebGLTexture(texture, scene, info.width, info.height, invertY, !loadMipmap, info.isFourCC, function () {
  14640. BABYLON.DDSTools.UploadDDSLevels(_this, _this._gl, data, info, loadMipmap, 1);
  14641. return false;
  14642. }, samplingMode);
  14643. };
  14644. }
  14645. if (!buffer) {
  14646. this._loadFile(url, function (data) {
  14647. if (callback) {
  14648. callback(data);
  14649. }
  14650. }, undefined, scene ? scene.database : undefined, true, function (request, exception) {
  14651. onerror("Unable to load " + (request ? request.responseURL : url, exception));
  14652. });
  14653. }
  14654. else {
  14655. if (callback) {
  14656. callback(buffer);
  14657. }
  14658. }
  14659. // image format processing
  14660. }
  14661. else {
  14662. var onload = function (img) {
  14663. if (fromBlob && !_this._doNotHandleContextLost) {
  14664. // We need to store the image if we need to rebuild the texture
  14665. // in case of a webgl context lost
  14666. texture._buffer = img;
  14667. }
  14668. _this._prepareWebGLTexture(texture, scene, img.width, img.height, invertY, noMipmap, false, function (potWidth, potHeight, continuationCallback) {
  14669. var gl = _this._gl;
  14670. var isPot = (img.width === potWidth && img.height === potHeight);
  14671. var internalFormat = format ? _this._getInternalFormat(format) : ((extension === ".jpg") ? gl.RGB : gl.RGBA);
  14672. if (isPot) {
  14673. gl.texImage2D(gl.TEXTURE_2D, 0, internalFormat, internalFormat, gl.UNSIGNED_BYTE, img);
  14674. return false;
  14675. }
  14676. // Using shaders to rescale because canvas.drawImage is lossy
  14677. var source = new BABYLON.InternalTexture(_this, BABYLON.InternalTexture.DATASOURCE_TEMP);
  14678. _this._bindTextureDirectly(gl.TEXTURE_2D, source, true);
  14679. gl.texImage2D(gl.TEXTURE_2D, 0, internalFormat, internalFormat, gl.UNSIGNED_BYTE, img);
  14680. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  14681. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.LINEAR);
  14682. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  14683. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  14684. _this._rescaleTexture(source, texture, scene, internalFormat, function () {
  14685. _this._releaseTexture(source);
  14686. _this._bindTextureDirectly(gl.TEXTURE_2D, texture, true);
  14687. continuationCallback();
  14688. });
  14689. return true;
  14690. }, samplingMode);
  14691. };
  14692. if (!fromData || isBase64)
  14693. if (buffer instanceof HTMLImageElement) {
  14694. onload(buffer);
  14695. }
  14696. else {
  14697. BABYLON.Tools.LoadImage(url, onload, onerror, scene ? scene.database : null);
  14698. }
  14699. else if (buffer instanceof Array || typeof buffer === "string" || buffer instanceof ArrayBuffer)
  14700. BABYLON.Tools.LoadImage(buffer, onload, onerror, scene ? scene.database : null);
  14701. else
  14702. onload(buffer);
  14703. }
  14704. return texture;
  14705. };
  14706. Engine.prototype._rescaleTexture = function (source, destination, scene, internalFormat, onComplete) {
  14707. var _this = this;
  14708. var rtt = this.createRenderTargetTexture({
  14709. width: destination.width,
  14710. height: destination.height,
  14711. }, {
  14712. generateMipMaps: false,
  14713. type: Engine.TEXTURETYPE_UNSIGNED_INT,
  14714. samplingMode: BABYLON.Texture.BILINEAR_SAMPLINGMODE,
  14715. generateDepthBuffer: false,
  14716. generateStencilBuffer: false
  14717. });
  14718. if (!this._rescalePostProcess) {
  14719. this._rescalePostProcess = new BABYLON.PassPostProcess("rescale", 1, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this, false, Engine.TEXTURETYPE_UNSIGNED_INT);
  14720. }
  14721. this._rescalePostProcess.getEffect().executeWhenCompiled(function () {
  14722. _this._rescalePostProcess.onApply = function (effect) {
  14723. effect._bindTexture("textureSampler", source);
  14724. };
  14725. var hostingScene = scene;
  14726. if (!hostingScene) {
  14727. hostingScene = _this.scenes[_this.scenes.length - 1];
  14728. }
  14729. hostingScene.postProcessManager.directRender([_this._rescalePostProcess], rtt, true);
  14730. _this._bindTextureDirectly(_this._gl.TEXTURE_2D, destination, true);
  14731. _this._gl.copyTexImage2D(_this._gl.TEXTURE_2D, 0, internalFormat, 0, 0, destination.width, destination.height, 0);
  14732. _this.unBindFramebuffer(rtt);
  14733. _this._releaseTexture(rtt);
  14734. if (onComplete) {
  14735. onComplete();
  14736. }
  14737. });
  14738. };
  14739. /**
  14740. * Update a raw texture
  14741. * @param texture defines the texture to update
  14742. * @param data defines the data to store in the texture
  14743. * @param format defines the format of the data
  14744. * @param invertY defines if data must be stored with Y axis inverted
  14745. * @param compression defines the compression used (null by default)
  14746. * @param type defines the type fo the data (BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT by default)
  14747. */
  14748. Engine.prototype.updateRawTexture = function (texture, data, format, invertY, compression, type) {
  14749. if (compression === void 0) { compression = null; }
  14750. if (type === void 0) { type = Engine.TEXTURETYPE_UNSIGNED_INT; }
  14751. if (!texture) {
  14752. return;
  14753. }
  14754. var internalSizedFomat = this._getRGBABufferInternalSizedFormat(type, format);
  14755. var internalFormat = this._getInternalFormat(format);
  14756. var textureType = this._getWebGLTextureType(type);
  14757. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture, true);
  14758. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY === undefined ? 1 : (invertY ? 1 : 0));
  14759. if (!this._doNotHandleContextLost) {
  14760. texture._bufferView = data;
  14761. texture.format = format;
  14762. texture.type = type;
  14763. texture.invertY = invertY;
  14764. texture._compression = compression;
  14765. }
  14766. if (texture.width % 4 !== 0) {
  14767. this._gl.pixelStorei(this._gl.UNPACK_ALIGNMENT, 1);
  14768. }
  14769. if (compression && data) {
  14770. this._gl.compressedTexImage2D(this._gl.TEXTURE_2D, 0, this.getCaps().s3tc[compression], texture.width, texture.height, 0, data);
  14771. }
  14772. else {
  14773. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, internalSizedFomat, texture.width, texture.height, 0, internalFormat, textureType, data);
  14774. }
  14775. if (texture.generateMipMaps) {
  14776. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  14777. }
  14778. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  14779. // this.resetTextureCache();
  14780. texture.isReady = true;
  14781. };
  14782. /**
  14783. * Creates a raw texture
  14784. * @param data defines the data to store in the texture
  14785. * @param width defines the width of the texture
  14786. * @param height defines the height of the texture
  14787. * @param format defines the format of the data
  14788. * @param generateMipMaps defines if the engine should generate the mip levels
  14789. * @param invertY defines if data must be stored with Y axis inverted
  14790. * @param samplingMode defines the required sampling mode (BABYLON.Texture.NEAREST_SAMPLINGMODE by default)
  14791. * @param compression defines the compression used (null by default)
  14792. * @param type defines the type fo the data (BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT by default)
  14793. * @returns the raw texture inside an InternalTexture
  14794. */
  14795. Engine.prototype.createRawTexture = function (data, width, height, format, generateMipMaps, invertY, samplingMode, compression, type) {
  14796. if (compression === void 0) { compression = null; }
  14797. if (type === void 0) { type = Engine.TEXTURETYPE_UNSIGNED_INT; }
  14798. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_RAW);
  14799. texture.baseWidth = width;
  14800. texture.baseHeight = height;
  14801. texture.width = width;
  14802. texture.height = height;
  14803. texture.format = format;
  14804. texture.generateMipMaps = generateMipMaps;
  14805. texture.samplingMode = samplingMode;
  14806. texture.invertY = invertY;
  14807. texture._compression = compression;
  14808. texture.type = type;
  14809. if (!this._doNotHandleContextLost) {
  14810. texture._bufferView = data;
  14811. }
  14812. this.updateRawTexture(texture, data, format, invertY, compression, type);
  14813. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture, true);
  14814. // Filters
  14815. var filters = getSamplingParameters(samplingMode, generateMipMaps, this._gl);
  14816. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  14817. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  14818. if (generateMipMaps) {
  14819. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  14820. }
  14821. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  14822. this._internalTexturesCache.push(texture);
  14823. return texture;
  14824. };
  14825. /**
  14826. * Creates a dynamic texture
  14827. * @param width defines the width of the texture
  14828. * @param height defines the height of the texture
  14829. * @param generateMipMaps defines if the engine should generate the mip levels
  14830. * @param samplingMode defines the required sampling mode (BABYLON.Texture.NEAREST_SAMPLINGMODE by default)
  14831. * @returns the dynamic texture inside an InternalTexture
  14832. */
  14833. Engine.prototype.createDynamicTexture = function (width, height, generateMipMaps, samplingMode) {
  14834. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_DYNAMIC);
  14835. texture.baseWidth = width;
  14836. texture.baseHeight = height;
  14837. if (generateMipMaps) {
  14838. width = this.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(width, this._caps.maxTextureSize) : width;
  14839. height = this.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(height, this._caps.maxTextureSize) : height;
  14840. }
  14841. // this.resetTextureCache();
  14842. texture.width = width;
  14843. texture.height = height;
  14844. texture.isReady = false;
  14845. texture.generateMipMaps = generateMipMaps;
  14846. texture.samplingMode = samplingMode;
  14847. this.updateTextureSamplingMode(samplingMode, texture);
  14848. this._internalTexturesCache.push(texture);
  14849. return texture;
  14850. };
  14851. /**
  14852. * Update the sampling mode of a given texture
  14853. * @param samplingMode defines the required sampling mode
  14854. * @param texture defines the texture to update
  14855. */
  14856. Engine.prototype.updateTextureSamplingMode = function (samplingMode, texture) {
  14857. var filters = getSamplingParameters(samplingMode, texture.generateMipMaps, this._gl);
  14858. if (texture.isCube) {
  14859. this._setTextureParameterInteger(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_MAG_FILTER, filters.mag, texture);
  14860. this._setTextureParameterInteger(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_MIN_FILTER, filters.min);
  14861. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  14862. }
  14863. else if (texture.is3D) {
  14864. this._setTextureParameterInteger(this._gl.TEXTURE_3D, this._gl.TEXTURE_MAG_FILTER, filters.mag, texture);
  14865. this._setTextureParameterInteger(this._gl.TEXTURE_3D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  14866. this._bindTextureDirectly(this._gl.TEXTURE_3D, null);
  14867. }
  14868. else {
  14869. this._setTextureParameterInteger(this._gl.TEXTURE_2D, this._gl.TEXTURE_MAG_FILTER, filters.mag, texture);
  14870. this._setTextureParameterInteger(this._gl.TEXTURE_2D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  14871. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  14872. }
  14873. texture.samplingMode = samplingMode;
  14874. };
  14875. /**
  14876. * Update the content of a dynamic texture
  14877. * @param texture defines the texture to update
  14878. * @param canvas defines the canvas containing the source
  14879. * @param invertY defines if data must be stored with Y axis inverted
  14880. * @param premulAlpha defines if alpha is stored as premultiplied
  14881. * @param format defines the format of the data
  14882. */
  14883. Engine.prototype.updateDynamicTexture = function (texture, canvas, invertY, premulAlpha, format) {
  14884. if (premulAlpha === void 0) { premulAlpha = false; }
  14885. if (!texture) {
  14886. return;
  14887. }
  14888. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture, true);
  14889. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY ? 1 : 0);
  14890. if (premulAlpha) {
  14891. this._gl.pixelStorei(this._gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, 1);
  14892. }
  14893. var internalFormat = format ? this._getInternalFormat(format) : this._gl.RGBA;
  14894. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, internalFormat, internalFormat, this._gl.UNSIGNED_BYTE, canvas);
  14895. if (texture.generateMipMaps) {
  14896. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  14897. }
  14898. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  14899. if (premulAlpha) {
  14900. this._gl.pixelStorei(this._gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, 0);
  14901. }
  14902. texture.isReady = true;
  14903. };
  14904. /**
  14905. * Update a video texture
  14906. * @param texture defines the texture to update
  14907. * @param video defines the video element to use
  14908. * @param invertY defines if data must be stored with Y axis inverted
  14909. */
  14910. Engine.prototype.updateVideoTexture = function (texture, video, invertY) {
  14911. if (!texture || texture._isDisabled) {
  14912. return;
  14913. }
  14914. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture, true);
  14915. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY ? 0 : 1); // Video are upside down by default
  14916. try {
  14917. // Testing video texture support
  14918. if (this._videoTextureSupported === undefined) {
  14919. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, video);
  14920. if (this._gl.getError() !== 0) {
  14921. this._videoTextureSupported = false;
  14922. }
  14923. else {
  14924. this._videoTextureSupported = true;
  14925. }
  14926. }
  14927. // Copy video through the current working canvas if video texture is not supported
  14928. if (!this._videoTextureSupported) {
  14929. if (!texture._workingCanvas) {
  14930. texture._workingCanvas = document.createElement("canvas");
  14931. var context = texture._workingCanvas.getContext("2d");
  14932. if (!context) {
  14933. throw new Error("Unable to get 2d context");
  14934. }
  14935. texture._workingContext = context;
  14936. texture._workingCanvas.width = texture.width;
  14937. texture._workingCanvas.height = texture.height;
  14938. }
  14939. texture._workingContext.drawImage(video, 0, 0, video.videoWidth, video.videoHeight, 0, 0, texture.width, texture.height);
  14940. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, texture._workingCanvas);
  14941. }
  14942. else {
  14943. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, video);
  14944. }
  14945. if (texture.generateMipMaps) {
  14946. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  14947. }
  14948. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  14949. // this.resetTextureCache();
  14950. texture.isReady = true;
  14951. }
  14952. catch (ex) {
  14953. // Something unexpected
  14954. // Let's disable the texture
  14955. texture._isDisabled = true;
  14956. }
  14957. };
  14958. /**
  14959. * Updates a depth texture Comparison Mode and Function.
  14960. * If the comparison Function is equal to 0, the mode will be set to none.
  14961. * Otherwise, this only works in webgl 2 and requires a shadow sampler in the shader.
  14962. * @param texture The texture to set the comparison function for
  14963. * @param comparisonFunction The comparison function to set, 0 if no comparison required
  14964. */
  14965. Engine.prototype.updateTextureComparisonFunction = function (texture, comparisonFunction) {
  14966. if (this.webGLVersion === 1) {
  14967. BABYLON.Tools.Error("WebGL 1 does not support texture comparison.");
  14968. return;
  14969. }
  14970. var gl = this._gl;
  14971. if (texture.isCube) {
  14972. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, texture, true);
  14973. if (comparisonFunction === 0) {
  14974. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_COMPARE_FUNC, Engine.LEQUAL);
  14975. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_COMPARE_MODE, gl.NONE);
  14976. }
  14977. else {
  14978. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_COMPARE_FUNC, comparisonFunction);
  14979. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_COMPARE_MODE, gl.COMPARE_REF_TO_TEXTURE);
  14980. }
  14981. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  14982. }
  14983. else {
  14984. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture, true);
  14985. if (comparisonFunction === 0) {
  14986. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_COMPARE_FUNC, Engine.LEQUAL);
  14987. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_COMPARE_MODE, gl.NONE);
  14988. }
  14989. else {
  14990. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_COMPARE_FUNC, comparisonFunction);
  14991. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_COMPARE_MODE, gl.COMPARE_REF_TO_TEXTURE);
  14992. }
  14993. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  14994. }
  14995. texture._comparisonFunction = comparisonFunction;
  14996. };
  14997. Engine.prototype._setupDepthStencilTexture = function (internalTexture, size, generateStencil, bilinearFiltering, comparisonFunction) {
  14998. var width = size.width || size;
  14999. var height = size.height || size;
  15000. internalTexture.baseWidth = width;
  15001. internalTexture.baseHeight = height;
  15002. internalTexture.width = width;
  15003. internalTexture.height = height;
  15004. internalTexture.isReady = true;
  15005. internalTexture.samples = 1;
  15006. internalTexture.generateMipMaps = false;
  15007. internalTexture._generateDepthBuffer = true;
  15008. internalTexture._generateStencilBuffer = generateStencil;
  15009. internalTexture.samplingMode = bilinearFiltering ? BABYLON.Texture.BILINEAR_SAMPLINGMODE : BABYLON.Texture.NEAREST_SAMPLINGMODE;
  15010. internalTexture.type = Engine.TEXTURETYPE_UNSIGNED_INT;
  15011. internalTexture._comparisonFunction = comparisonFunction;
  15012. var gl = this._gl;
  15013. var target = internalTexture.isCube ? gl.TEXTURE_CUBE_MAP : gl.TEXTURE_2D;
  15014. var samplingParameters = getSamplingParameters(internalTexture.samplingMode, false, gl);
  15015. gl.texParameteri(target, gl.TEXTURE_MAG_FILTER, samplingParameters.mag);
  15016. gl.texParameteri(target, gl.TEXTURE_MIN_FILTER, samplingParameters.min);
  15017. gl.texParameteri(target, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  15018. gl.texParameteri(target, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  15019. if (comparisonFunction === 0) {
  15020. gl.texParameteri(target, gl.TEXTURE_COMPARE_FUNC, Engine.LEQUAL);
  15021. gl.texParameteri(target, gl.TEXTURE_COMPARE_MODE, gl.NONE);
  15022. }
  15023. else {
  15024. gl.texParameteri(target, gl.TEXTURE_COMPARE_FUNC, comparisonFunction);
  15025. gl.texParameteri(target, gl.TEXTURE_COMPARE_MODE, gl.COMPARE_REF_TO_TEXTURE);
  15026. }
  15027. };
  15028. /**
  15029. * Creates a depth stencil texture.
  15030. * This is only available in WebGL 2 or with the depth texture extension available.
  15031. * @param size The size of face edge in the texture.
  15032. * @param options The options defining the texture.
  15033. * @returns The texture
  15034. */
  15035. Engine.prototype.createDepthStencilTexture = function (size, options) {
  15036. if (options.isCube) {
  15037. var width = size.width || size;
  15038. return this._createDepthStencilCubeTexture(width, options);
  15039. }
  15040. else {
  15041. return this._createDepthStencilTexture(size, options);
  15042. }
  15043. };
  15044. /**
  15045. * Creates a depth stencil texture.
  15046. * This is only available in WebGL 2 or with the depth texture extension available.
  15047. * @param size The size of face edge in the texture.
  15048. * @param options The options defining the texture.
  15049. * @returns The texture
  15050. */
  15051. Engine.prototype._createDepthStencilTexture = function (size, options) {
  15052. var internalTexture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_DEPTHTEXTURE);
  15053. if (!this._caps.depthTextureExtension) {
  15054. BABYLON.Tools.Error("Depth texture is not supported by your browser or hardware.");
  15055. return internalTexture;
  15056. }
  15057. var internalOptions = __assign({ bilinearFiltering: false, comparisonFunction: 0, generateStencil: false }, options);
  15058. var gl = this._gl;
  15059. this._bindTextureDirectly(gl.TEXTURE_2D, internalTexture, true);
  15060. this._setupDepthStencilTexture(internalTexture, size, internalOptions.generateStencil, internalOptions.bilinearFiltering, internalOptions.comparisonFunction);
  15061. if (this.webGLVersion > 1) {
  15062. if (internalOptions.generateStencil) {
  15063. gl.texImage2D(gl.TEXTURE_2D, 0, gl.DEPTH24_STENCIL8, internalTexture.width, internalTexture.height, 0, gl.DEPTH_STENCIL, gl.UNSIGNED_INT_24_8, null);
  15064. }
  15065. else {
  15066. gl.texImage2D(gl.TEXTURE_2D, 0, gl.DEPTH_COMPONENT24, internalTexture.width, internalTexture.height, 0, gl.DEPTH_COMPONENT, gl.UNSIGNED_INT, null);
  15067. }
  15068. }
  15069. else {
  15070. if (internalOptions.generateStencil) {
  15071. gl.texImage2D(gl.TEXTURE_2D, 0, gl.DEPTH_STENCIL, internalTexture.width, internalTexture.height, 0, gl.DEPTH_STENCIL, gl.UNSIGNED_INT_24_8, null);
  15072. }
  15073. else {
  15074. gl.texImage2D(gl.TEXTURE_2D, 0, gl.DEPTH_COMPONENT, internalTexture.width, internalTexture.height, 0, gl.DEPTH_COMPONENT, gl.UNSIGNED_INT, null);
  15075. }
  15076. }
  15077. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  15078. return internalTexture;
  15079. };
  15080. /**
  15081. * Creates a depth stencil cube texture.
  15082. * This is only available in WebGL 2.
  15083. * @param size The size of face edge in the cube texture.
  15084. * @param options The options defining the cube texture.
  15085. * @returns The cube texture
  15086. */
  15087. Engine.prototype._createDepthStencilCubeTexture = function (size, options) {
  15088. var internalTexture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_UNKNOWN);
  15089. internalTexture.isCube = true;
  15090. if (this.webGLVersion === 1) {
  15091. BABYLON.Tools.Error("Depth cube texture is not supported by WebGL 1.");
  15092. return internalTexture;
  15093. }
  15094. var internalOptions = __assign({ bilinearFiltering: false, comparisonFunction: 0, generateStencil: false }, options);
  15095. var gl = this._gl;
  15096. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, internalTexture, true);
  15097. this._setupDepthStencilTexture(internalTexture, size, internalOptions.generateStencil, internalOptions.bilinearFiltering, internalOptions.comparisonFunction);
  15098. // Create the depth/stencil buffer
  15099. for (var face = 0; face < 6; face++) {
  15100. if (internalOptions.generateStencil) {
  15101. 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);
  15102. }
  15103. else {
  15104. gl.texImage2D(gl.TEXTURE_CUBE_MAP_POSITIVE_X + face, 0, gl.DEPTH_COMPONENT24, size, size, 0, gl.DEPTH_COMPONENT, gl.UNSIGNED_INT, null);
  15105. }
  15106. }
  15107. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  15108. return internalTexture;
  15109. };
  15110. /**
  15111. * Sets the frame buffer Depth / Stencil attachement of the render target to the defined depth stencil texture.
  15112. * @param renderTarget The render target to set the frame buffer for
  15113. */
  15114. Engine.prototype.setFrameBufferDepthStencilTexture = function (renderTarget) {
  15115. // Create the framebuffer
  15116. var internalTexture = renderTarget.getInternalTexture();
  15117. if (!internalTexture || !internalTexture._framebuffer || !renderTarget.depthStencilTexture) {
  15118. return;
  15119. }
  15120. var gl = this._gl;
  15121. var depthStencilTexture = renderTarget.depthStencilTexture;
  15122. this.bindUnboundFramebuffer(internalTexture._framebuffer);
  15123. if (depthStencilTexture.isCube) {
  15124. if (depthStencilTexture._generateStencilBuffer) {
  15125. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_STENCIL_ATTACHMENT, gl.TEXTURE_CUBE_MAP_POSITIVE_X, depthStencilTexture._webGLTexture, 0);
  15126. }
  15127. else {
  15128. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.TEXTURE_CUBE_MAP_POSITIVE_X, depthStencilTexture._webGLTexture, 0);
  15129. }
  15130. }
  15131. else {
  15132. if (depthStencilTexture._generateStencilBuffer) {
  15133. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_STENCIL_ATTACHMENT, gl.TEXTURE_2D, depthStencilTexture._webGLTexture, 0);
  15134. }
  15135. else {
  15136. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.TEXTURE_2D, depthStencilTexture._webGLTexture, 0);
  15137. }
  15138. }
  15139. this.bindUnboundFramebuffer(null);
  15140. };
  15141. /**
  15142. * Creates a new render target texture
  15143. * @param size defines the size of the texture
  15144. * @param options defines the options used to create the texture
  15145. * @returns a new render target texture stored in an InternalTexture
  15146. */
  15147. Engine.prototype.createRenderTargetTexture = function (size, options) {
  15148. var fullOptions = new RenderTargetCreationOptions();
  15149. if (options !== undefined && typeof options === "object") {
  15150. fullOptions.generateMipMaps = options.generateMipMaps;
  15151. fullOptions.generateDepthBuffer = options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  15152. fullOptions.generateStencilBuffer = fullOptions.generateDepthBuffer && options.generateStencilBuffer;
  15153. fullOptions.type = options.type === undefined ? Engine.TEXTURETYPE_UNSIGNED_INT : options.type;
  15154. fullOptions.samplingMode = options.samplingMode === undefined ? BABYLON.Texture.TRILINEAR_SAMPLINGMODE : options.samplingMode;
  15155. fullOptions.format = options.format === undefined ? Engine.TEXTUREFORMAT_RGBA : options.format;
  15156. }
  15157. else {
  15158. fullOptions.generateMipMaps = options;
  15159. fullOptions.generateDepthBuffer = true;
  15160. fullOptions.generateStencilBuffer = false;
  15161. fullOptions.type = Engine.TEXTURETYPE_UNSIGNED_INT;
  15162. fullOptions.samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE;
  15163. fullOptions.format = Engine.TEXTUREFORMAT_RGBA;
  15164. }
  15165. if (fullOptions.type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloatLinearFiltering) {
  15166. // if floating point linear (gl.FLOAT) then force to NEAREST_SAMPLINGMODE
  15167. fullOptions.samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE;
  15168. }
  15169. else if (fullOptions.type === Engine.TEXTURETYPE_HALF_FLOAT && !this._caps.textureHalfFloatLinearFiltering) {
  15170. // if floating point linear (HALF_FLOAT) then force to NEAREST_SAMPLINGMODE
  15171. fullOptions.samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE;
  15172. }
  15173. var gl = this._gl;
  15174. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_RENDERTARGET);
  15175. this._bindTextureDirectly(gl.TEXTURE_2D, texture, true);
  15176. var width = size.width || size;
  15177. var height = size.height || size;
  15178. var filters = getSamplingParameters(fullOptions.samplingMode, fullOptions.generateMipMaps ? true : false, gl);
  15179. if (fullOptions.type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloat) {
  15180. fullOptions.type = Engine.TEXTURETYPE_UNSIGNED_INT;
  15181. BABYLON.Tools.Warn("Float textures are not supported. Render target forced to TEXTURETYPE_UNSIGNED_BYTE type");
  15182. }
  15183. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, filters.mag);
  15184. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, filters.min);
  15185. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  15186. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  15187. gl.texImage2D(gl.TEXTURE_2D, 0, this._getRGBABufferInternalSizedFormat(fullOptions.type, fullOptions.format), width, height, 0, this._getInternalFormat(fullOptions.format), this._getWebGLTextureType(fullOptions.type), null);
  15188. // Create the framebuffer
  15189. var framebuffer = gl.createFramebuffer();
  15190. this.bindUnboundFramebuffer(framebuffer);
  15191. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, texture._webGLTexture, 0);
  15192. texture._depthStencilBuffer = this._setupFramebufferDepthAttachments(fullOptions.generateStencilBuffer ? true : false, fullOptions.generateDepthBuffer, width, height);
  15193. if (fullOptions.generateMipMaps) {
  15194. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  15195. }
  15196. // Unbind
  15197. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  15198. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  15199. this.bindUnboundFramebuffer(null);
  15200. texture._framebuffer = framebuffer;
  15201. texture.baseWidth = width;
  15202. texture.baseHeight = height;
  15203. texture.width = width;
  15204. texture.height = height;
  15205. texture.isReady = true;
  15206. texture.samples = 1;
  15207. texture.generateMipMaps = fullOptions.generateMipMaps ? true : false;
  15208. texture.samplingMode = fullOptions.samplingMode;
  15209. texture.type = fullOptions.type;
  15210. texture._generateDepthBuffer = fullOptions.generateDepthBuffer;
  15211. texture._generateStencilBuffer = fullOptions.generateStencilBuffer ? true : false;
  15212. // this.resetTextureCache();
  15213. this._internalTexturesCache.push(texture);
  15214. return texture;
  15215. };
  15216. /**
  15217. * Create a multi render target texture
  15218. * @see http://doc.babylonjs.com/features/webgl2#multiple-render-target
  15219. * @param size defines the size of the texture
  15220. * @param options defines the creation options
  15221. * @returns the cube texture as an InternalTexture
  15222. */
  15223. Engine.prototype.createMultipleRenderTarget = function (size, options) {
  15224. var generateMipMaps = false;
  15225. var generateDepthBuffer = true;
  15226. var generateStencilBuffer = false;
  15227. var generateDepthTexture = false;
  15228. var textureCount = 1;
  15229. var defaultType = Engine.TEXTURETYPE_UNSIGNED_INT;
  15230. var defaultSamplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE;
  15231. var types = new Array();
  15232. var samplingModes = new Array();
  15233. if (options !== undefined) {
  15234. generateMipMaps = options.generateMipMaps === undefined ? false : options.generateMipMaps;
  15235. generateDepthBuffer = options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  15236. generateStencilBuffer = options.generateStencilBuffer === undefined ? false : options.generateStencilBuffer;
  15237. generateDepthTexture = options.generateDepthTexture === undefined ? false : options.generateDepthTexture;
  15238. textureCount = options.textureCount || 1;
  15239. if (options.types) {
  15240. types = options.types;
  15241. }
  15242. if (options.samplingModes) {
  15243. samplingModes = options.samplingModes;
  15244. }
  15245. }
  15246. var gl = this._gl;
  15247. // Create the framebuffer
  15248. var framebuffer = gl.createFramebuffer();
  15249. this.bindUnboundFramebuffer(framebuffer);
  15250. var width = size.width || size;
  15251. var height = size.height || size;
  15252. var textures = [];
  15253. var attachments = [];
  15254. var depthStencilBuffer = this._setupFramebufferDepthAttachments(generateStencilBuffer, generateDepthBuffer, width, height);
  15255. for (var i = 0; i < textureCount; i++) {
  15256. var samplingMode = samplingModes[i] || defaultSamplingMode;
  15257. var type = types[i] || defaultType;
  15258. if (type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloatLinearFiltering) {
  15259. // if floating point linear (gl.FLOAT) then force to NEAREST_SAMPLINGMODE
  15260. samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE;
  15261. }
  15262. else if (type === Engine.TEXTURETYPE_HALF_FLOAT && !this._caps.textureHalfFloatLinearFiltering) {
  15263. // if floating point linear (HALF_FLOAT) then force to NEAREST_SAMPLINGMODE
  15264. samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE;
  15265. }
  15266. var filters = getSamplingParameters(samplingMode, generateMipMaps, gl);
  15267. if (type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloat) {
  15268. type = Engine.TEXTURETYPE_UNSIGNED_INT;
  15269. BABYLON.Tools.Warn("Float textures are not supported. Render target forced to TEXTURETYPE_UNSIGNED_BYTE type");
  15270. }
  15271. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_MULTIRENDERTARGET);
  15272. var attachment = gl[this.webGLVersion > 1 ? "COLOR_ATTACHMENT" + i : "COLOR_ATTACHMENT" + i + "_WEBGL"];
  15273. textures.push(texture);
  15274. attachments.push(attachment);
  15275. gl.activeTexture(gl["TEXTURE" + i]);
  15276. gl.bindTexture(gl.TEXTURE_2D, texture._webGLTexture);
  15277. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, filters.mag);
  15278. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, filters.min);
  15279. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  15280. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  15281. gl.texImage2D(gl.TEXTURE_2D, 0, this._getRGBABufferInternalSizedFormat(type), width, height, 0, gl.RGBA, this._getWebGLTextureType(type), null);
  15282. gl.framebufferTexture2D(gl.DRAW_FRAMEBUFFER, attachment, gl.TEXTURE_2D, texture._webGLTexture, 0);
  15283. if (generateMipMaps) {
  15284. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  15285. }
  15286. // Unbind
  15287. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  15288. texture._framebuffer = framebuffer;
  15289. texture._depthStencilBuffer = depthStencilBuffer;
  15290. texture.baseWidth = width;
  15291. texture.baseHeight = height;
  15292. texture.width = width;
  15293. texture.height = height;
  15294. texture.isReady = true;
  15295. texture.samples = 1;
  15296. texture.generateMipMaps = generateMipMaps;
  15297. texture.samplingMode = samplingMode;
  15298. texture.type = type;
  15299. texture._generateDepthBuffer = generateDepthBuffer;
  15300. texture._generateStencilBuffer = generateStencilBuffer;
  15301. texture._attachments = attachments;
  15302. this._internalTexturesCache.push(texture);
  15303. }
  15304. if (generateDepthTexture && this._caps.depthTextureExtension) {
  15305. // Depth texture
  15306. var depthTexture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_MULTIRENDERTARGET);
  15307. gl.activeTexture(gl.TEXTURE0);
  15308. gl.bindTexture(gl.TEXTURE_2D, depthTexture._webGLTexture);
  15309. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
  15310. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
  15311. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  15312. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  15313. 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);
  15314. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.TEXTURE_2D, depthTexture._webGLTexture, 0);
  15315. depthTexture._framebuffer = framebuffer;
  15316. depthTexture.baseWidth = width;
  15317. depthTexture.baseHeight = height;
  15318. depthTexture.width = width;
  15319. depthTexture.height = height;
  15320. depthTexture.isReady = true;
  15321. depthTexture.samples = 1;
  15322. depthTexture.generateMipMaps = generateMipMaps;
  15323. depthTexture.samplingMode = gl.NEAREST;
  15324. depthTexture._generateDepthBuffer = generateDepthBuffer;
  15325. depthTexture._generateStencilBuffer = generateStencilBuffer;
  15326. textures.push(depthTexture);
  15327. this._internalTexturesCache.push(depthTexture);
  15328. }
  15329. gl.drawBuffers(attachments);
  15330. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  15331. this.bindUnboundFramebuffer(null);
  15332. this.resetTextureCache();
  15333. return textures;
  15334. };
  15335. Engine.prototype._setupFramebufferDepthAttachments = function (generateStencilBuffer, generateDepthBuffer, width, height, samples) {
  15336. if (samples === void 0) { samples = 1; }
  15337. var depthStencilBuffer = null;
  15338. var gl = this._gl;
  15339. // Create the depth/stencil buffer
  15340. if (generateStencilBuffer) {
  15341. depthStencilBuffer = gl.createRenderbuffer();
  15342. gl.bindRenderbuffer(gl.RENDERBUFFER, depthStencilBuffer);
  15343. if (samples > 1) {
  15344. gl.renderbufferStorageMultisample(gl.RENDERBUFFER, samples, gl.DEPTH24_STENCIL8, width, height);
  15345. }
  15346. else {
  15347. gl.renderbufferStorage(gl.RENDERBUFFER, gl.DEPTH_STENCIL, width, height);
  15348. }
  15349. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.DEPTH_STENCIL_ATTACHMENT, gl.RENDERBUFFER, depthStencilBuffer);
  15350. }
  15351. else if (generateDepthBuffer) {
  15352. depthStencilBuffer = gl.createRenderbuffer();
  15353. gl.bindRenderbuffer(gl.RENDERBUFFER, depthStencilBuffer);
  15354. if (samples > 1) {
  15355. gl.renderbufferStorageMultisample(gl.RENDERBUFFER, samples, gl.DEPTH_COMPONENT16, width, height);
  15356. }
  15357. else {
  15358. gl.renderbufferStorage(gl.RENDERBUFFER, gl.DEPTH_COMPONENT16, width, height);
  15359. }
  15360. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.RENDERBUFFER, depthStencilBuffer);
  15361. }
  15362. return depthStencilBuffer;
  15363. };
  15364. /**
  15365. * Updates the sample count of a render target texture
  15366. * @see http://doc.babylonjs.com/features/webgl2#multisample-render-targets
  15367. * @param texture defines the texture to update
  15368. * @param samples defines the sample count to set
  15369. * @returns the effective sample count (could be 0 if multisample render targets are not supported)
  15370. */
  15371. Engine.prototype.updateRenderTargetTextureSampleCount = function (texture, samples) {
  15372. if (this.webGLVersion < 2 || !texture) {
  15373. return 1;
  15374. }
  15375. if (texture.samples === samples) {
  15376. return samples;
  15377. }
  15378. var gl = this._gl;
  15379. samples = Math.min(samples, gl.getParameter(gl.MAX_SAMPLES));
  15380. // Dispose previous render buffers
  15381. if (texture._depthStencilBuffer) {
  15382. gl.deleteRenderbuffer(texture._depthStencilBuffer);
  15383. texture._depthStencilBuffer = null;
  15384. }
  15385. if (texture._MSAAFramebuffer) {
  15386. gl.deleteFramebuffer(texture._MSAAFramebuffer);
  15387. texture._MSAAFramebuffer = null;
  15388. }
  15389. if (texture._MSAARenderBuffer) {
  15390. gl.deleteRenderbuffer(texture._MSAARenderBuffer);
  15391. texture._MSAARenderBuffer = null;
  15392. }
  15393. if (samples > 1) {
  15394. var framebuffer = gl.createFramebuffer();
  15395. if (!framebuffer) {
  15396. throw new Error("Unable to create multi sampled framebuffer");
  15397. }
  15398. texture._MSAAFramebuffer = framebuffer;
  15399. this.bindUnboundFramebuffer(texture._MSAAFramebuffer);
  15400. var colorRenderbuffer = gl.createRenderbuffer();
  15401. if (!colorRenderbuffer) {
  15402. throw new Error("Unable to create multi sampled framebuffer");
  15403. }
  15404. gl.bindRenderbuffer(gl.RENDERBUFFER, colorRenderbuffer);
  15405. gl.renderbufferStorageMultisample(gl.RENDERBUFFER, samples, this._getRGBAMultiSampleBufferFormat(texture.type), texture.width, texture.height);
  15406. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.RENDERBUFFER, colorRenderbuffer);
  15407. texture._MSAARenderBuffer = colorRenderbuffer;
  15408. }
  15409. else {
  15410. this.bindUnboundFramebuffer(texture._framebuffer);
  15411. }
  15412. texture.samples = samples;
  15413. texture._depthStencilBuffer = this._setupFramebufferDepthAttachments(texture._generateStencilBuffer, texture._generateDepthBuffer, texture.width, texture.height, samples);
  15414. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  15415. this.bindUnboundFramebuffer(null);
  15416. return samples;
  15417. };
  15418. /**
  15419. * Update the sample count for a given multiple render target texture
  15420. * @see http://doc.babylonjs.com/features/webgl2#multisample-render-targets
  15421. * @param textures defines the textures to update
  15422. * @param samples defines the sample count to set
  15423. * @returns the effective sample count (could be 0 if multisample render targets are not supported)
  15424. */
  15425. Engine.prototype.updateMultipleRenderTargetTextureSampleCount = function (textures, samples) {
  15426. if (this.webGLVersion < 2 || !textures || textures.length == 0) {
  15427. return 1;
  15428. }
  15429. if (textures[0].samples === samples) {
  15430. return samples;
  15431. }
  15432. var gl = this._gl;
  15433. samples = Math.min(samples, gl.getParameter(gl.MAX_SAMPLES));
  15434. // Dispose previous render buffers
  15435. if (textures[0]._depthStencilBuffer) {
  15436. gl.deleteRenderbuffer(textures[0]._depthStencilBuffer);
  15437. textures[0]._depthStencilBuffer = null;
  15438. }
  15439. if (textures[0]._MSAAFramebuffer) {
  15440. gl.deleteFramebuffer(textures[0]._MSAAFramebuffer);
  15441. textures[0]._MSAAFramebuffer = null;
  15442. }
  15443. for (var i = 0; i < textures.length; i++) {
  15444. if (textures[i]._MSAARenderBuffer) {
  15445. gl.deleteRenderbuffer(textures[i]._MSAARenderBuffer);
  15446. textures[i]._MSAARenderBuffer = null;
  15447. }
  15448. }
  15449. if (samples > 1) {
  15450. var framebuffer = gl.createFramebuffer();
  15451. if (!framebuffer) {
  15452. throw new Error("Unable to create multi sampled framebuffer");
  15453. }
  15454. this.bindUnboundFramebuffer(framebuffer);
  15455. var depthStencilBuffer = this._setupFramebufferDepthAttachments(textures[0]._generateStencilBuffer, textures[0]._generateDepthBuffer, textures[0].width, textures[0].height, samples);
  15456. var attachments = [];
  15457. for (var i = 0; i < textures.length; i++) {
  15458. var texture = textures[i];
  15459. var attachment = gl[this.webGLVersion > 1 ? "COLOR_ATTACHMENT" + i : "COLOR_ATTACHMENT" + i + "_WEBGL"];
  15460. var colorRenderbuffer = gl.createRenderbuffer();
  15461. if (!colorRenderbuffer) {
  15462. throw new Error("Unable to create multi sampled framebuffer");
  15463. }
  15464. gl.bindRenderbuffer(gl.RENDERBUFFER, colorRenderbuffer);
  15465. gl.renderbufferStorageMultisample(gl.RENDERBUFFER, samples, this._getRGBAMultiSampleBufferFormat(texture.type), texture.width, texture.height);
  15466. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, attachment, gl.RENDERBUFFER, colorRenderbuffer);
  15467. texture._MSAAFramebuffer = framebuffer;
  15468. texture._MSAARenderBuffer = colorRenderbuffer;
  15469. texture.samples = samples;
  15470. texture._depthStencilBuffer = depthStencilBuffer;
  15471. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  15472. attachments.push(attachment);
  15473. }
  15474. gl.drawBuffers(attachments);
  15475. }
  15476. else {
  15477. this.bindUnboundFramebuffer(textures[0]._framebuffer);
  15478. }
  15479. this.bindUnboundFramebuffer(null);
  15480. return samples;
  15481. };
  15482. /** @hidden */
  15483. Engine.prototype._uploadDataToTexture = function (target, lod, internalFormat, width, height, format, type, data) {
  15484. this._gl.texImage2D(target, lod, internalFormat, width, height, 0, format, type, data);
  15485. };
  15486. /** @hidden */
  15487. Engine.prototype._uploadCompressedDataToTexture = function (target, lod, internalFormat, width, height, data) {
  15488. this._gl.compressedTexImage2D(target, lod, internalFormat, width, height, 0, data);
  15489. };
  15490. /**
  15491. * Creates a new render target cube texture
  15492. * @param size defines the size of the texture
  15493. * @param options defines the options used to create the texture
  15494. * @returns a new render target cube texture stored in an InternalTexture
  15495. */
  15496. Engine.prototype.createRenderTargetCubeTexture = function (size, options) {
  15497. var fullOptions = __assign({ generateMipMaps: true, generateDepthBuffer: true, generateStencilBuffer: false, type: Engine.TEXTURETYPE_UNSIGNED_INT, samplingMode: BABYLON.Texture.TRILINEAR_SAMPLINGMODE, format: Engine.TEXTUREFORMAT_RGBA }, options);
  15498. fullOptions.generateStencilBuffer = fullOptions.generateDepthBuffer && fullOptions.generateStencilBuffer;
  15499. if (fullOptions.type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloatLinearFiltering) {
  15500. // if floating point linear (gl.FLOAT) then force to NEAREST_SAMPLINGMODE
  15501. fullOptions.samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE;
  15502. }
  15503. else if (fullOptions.type === Engine.TEXTURETYPE_HALF_FLOAT && !this._caps.textureHalfFloatLinearFiltering) {
  15504. // if floating point linear (HALF_FLOAT) then force to NEAREST_SAMPLINGMODE
  15505. fullOptions.samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE;
  15506. }
  15507. var gl = this._gl;
  15508. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_RENDERTARGET);
  15509. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  15510. var filters = getSamplingParameters(fullOptions.samplingMode, fullOptions.generateMipMaps, gl);
  15511. if (fullOptions.type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloat) {
  15512. fullOptions.type = Engine.TEXTURETYPE_UNSIGNED_INT;
  15513. BABYLON.Tools.Warn("Float textures are not supported. Cube render target forced to TEXTURETYPE_UNESIGNED_BYTE type");
  15514. }
  15515. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, filters.mag);
  15516. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, filters.min);
  15517. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  15518. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  15519. for (var face = 0; face < 6; face++) {
  15520. 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);
  15521. }
  15522. // Create the framebuffer
  15523. var framebuffer = gl.createFramebuffer();
  15524. this.bindUnboundFramebuffer(framebuffer);
  15525. texture._depthStencilBuffer = this._setupFramebufferDepthAttachments(fullOptions.generateStencilBuffer, fullOptions.generateDepthBuffer, size, size);
  15526. // MipMaps
  15527. if (fullOptions.generateMipMaps) {
  15528. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  15529. }
  15530. // Unbind
  15531. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  15532. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  15533. this.bindUnboundFramebuffer(null);
  15534. texture._framebuffer = framebuffer;
  15535. texture.width = size;
  15536. texture.height = size;
  15537. texture.isReady = true;
  15538. texture.isCube = true;
  15539. texture.samples = 1;
  15540. texture.generateMipMaps = fullOptions.generateMipMaps;
  15541. texture.samplingMode = fullOptions.samplingMode;
  15542. texture.type = fullOptions.type;
  15543. texture._generateDepthBuffer = fullOptions.generateDepthBuffer;
  15544. texture._generateStencilBuffer = fullOptions.generateStencilBuffer;
  15545. this._internalTexturesCache.push(texture);
  15546. return texture;
  15547. };
  15548. /**
  15549. * Create a cube texture from prefiltered data (ie. the mipmaps contain ready to use data for PBR reflection)
  15550. * @param rootUrl defines the url where the file to load is located
  15551. * @param scene defines the current scene
  15552. * @param scale defines scale to apply to the mip map selection
  15553. * @param offset defines offset to apply to the mip map selection
  15554. * @param onLoad defines an optional callback raised when the texture is loaded
  15555. * @param onError defines an optional callback raised if there is an issue to load the texture
  15556. * @param format defines the format of the data
  15557. * @param forcedExtension defines the extension to use to pick the right loader
  15558. * @returns the cube texture as an InternalTexture
  15559. */
  15560. Engine.prototype.createPrefilteredCubeTexture = function (rootUrl, scene, scale, offset, onLoad, onError, format, forcedExtension) {
  15561. var _this = this;
  15562. if (onLoad === void 0) { onLoad = null; }
  15563. if (onError === void 0) { onError = null; }
  15564. if (forcedExtension === void 0) { forcedExtension = null; }
  15565. var callback = function (loadData) {
  15566. if (!loadData) {
  15567. if (onLoad) {
  15568. onLoad(null);
  15569. }
  15570. return;
  15571. }
  15572. var texture = loadData.texture;
  15573. if (loadData.info.sphericalPolynomial) {
  15574. texture._sphericalPolynomial = loadData.info.sphericalPolynomial;
  15575. }
  15576. texture._dataSource = BABYLON.InternalTexture.DATASOURCE_CUBEPREFILTERED;
  15577. texture._lodGenerationScale = scale;
  15578. texture._lodGenerationOffset = offset;
  15579. if (_this._caps.textureLOD) {
  15580. // Do not add extra process if texture lod is supported.
  15581. if (onLoad) {
  15582. onLoad(texture);
  15583. }
  15584. return;
  15585. }
  15586. var mipSlices = 3;
  15587. var gl = _this._gl;
  15588. var width = loadData.width;
  15589. if (!width) {
  15590. return;
  15591. }
  15592. var textures = [];
  15593. for (var i = 0; i < mipSlices; i++) {
  15594. //compute LOD from even spacing in smoothness (matching shader calculation)
  15595. var smoothness = i / (mipSlices - 1);
  15596. var roughness = 1 - smoothness;
  15597. var minLODIndex = offset; // roughness = 0
  15598. var maxLODIndex = BABYLON.Scalar.Log2(width) * scale + offset; // roughness = 1
  15599. var lodIndex = minLODIndex + (maxLODIndex - minLODIndex) * roughness;
  15600. var mipmapIndex = Math.round(Math.min(Math.max(lodIndex, 0), maxLODIndex));
  15601. var glTextureFromLod = new BABYLON.InternalTexture(_this, BABYLON.InternalTexture.DATASOURCE_TEMP);
  15602. glTextureFromLod.isCube = true;
  15603. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, glTextureFromLod, true);
  15604. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  15605. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, gl.LINEAR);
  15606. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  15607. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  15608. if (loadData.isDDS) {
  15609. var info = loadData.info;
  15610. var data = loadData.data;
  15611. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, info.isCompressed ? 1 : 0);
  15612. BABYLON.DDSTools.UploadDDSLevels(_this, _this._gl, data, info, true, 6, mipmapIndex);
  15613. }
  15614. else {
  15615. BABYLON.Tools.Warn("DDS is the only prefiltered cube map supported so far.");
  15616. }
  15617. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  15618. // Wrap in a base texture for easy binding.
  15619. var lodTexture = new BABYLON.BaseTexture(scene);
  15620. lodTexture.isCube = true;
  15621. lodTexture._texture = glTextureFromLod;
  15622. glTextureFromLod.isReady = true;
  15623. textures.push(lodTexture);
  15624. }
  15625. texture._lodTextureHigh = textures[2];
  15626. texture._lodTextureMid = textures[1];
  15627. texture._lodTextureLow = textures[0];
  15628. if (onLoad) {
  15629. onLoad(texture);
  15630. }
  15631. };
  15632. return this.createCubeTexture(rootUrl, scene, null, false, callback, onError, format, forcedExtension, true);
  15633. };
  15634. /**
  15635. * Creates a cube texture
  15636. * @param rootUrl defines the url where the files to load is located
  15637. * @param scene defines the current scene
  15638. * @param files defines the list of files to load (1 per face)
  15639. * @param noMipmap defines a boolean indicating that no mipmaps shall be generated (false by default)
  15640. * @param onLoad defines an optional callback raised when the texture is loaded
  15641. * @param onError defines an optional callback raised if there is an issue to load the texture
  15642. * @param format defines the format of the data
  15643. * @param forcedExtension defines the extension to use to pick the right loader
  15644. * @param createPolynomials if a polynomial sphere should be created for the cube texture
  15645. * @returns the cube texture as an InternalTexture
  15646. */
  15647. Engine.prototype.createCubeTexture = function (rootUrl, scene, files, noMipmap, onLoad, onError, format, forcedExtension, createPolynomials) {
  15648. var _this = this;
  15649. if (onLoad === void 0) { onLoad = null; }
  15650. if (onError === void 0) { onError = null; }
  15651. if (forcedExtension === void 0) { forcedExtension = null; }
  15652. if (createPolynomials === void 0) { createPolynomials = false; }
  15653. var gl = this._gl;
  15654. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_CUBE);
  15655. texture.isCube = true;
  15656. texture.url = rootUrl;
  15657. texture.generateMipMaps = !noMipmap;
  15658. if (!this._doNotHandleContextLost) {
  15659. texture._extension = forcedExtension;
  15660. texture._files = files;
  15661. }
  15662. var isKTX = false;
  15663. var isDDS = false;
  15664. var lastDot = rootUrl.lastIndexOf('.');
  15665. var extension = forcedExtension ? forcedExtension : (lastDot > -1 ? rootUrl.substring(lastDot).toLowerCase() : "");
  15666. if (this._textureFormatInUse) {
  15667. extension = this._textureFormatInUse;
  15668. rootUrl = (lastDot > -1 ? rootUrl.substring(0, lastDot) : rootUrl) + this._textureFormatInUse;
  15669. isKTX = true;
  15670. }
  15671. else {
  15672. isDDS = (extension === ".dds");
  15673. }
  15674. var onerror = function (request, exception) {
  15675. if (onError && request) {
  15676. onError(request.status + " " + request.statusText, exception);
  15677. }
  15678. };
  15679. if (isKTX) {
  15680. this._loadFile(rootUrl, function (data) {
  15681. var ktx = new BABYLON.KhronosTextureContainer(data, 6);
  15682. var loadMipmap = ktx.numberOfMipmapLevels > 1 && !noMipmap;
  15683. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  15684. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, 1);
  15685. ktx.uploadLevels(_this._gl, !noMipmap);
  15686. _this.setCubeMapTextureParams(gl, loadMipmap);
  15687. texture.width = ktx.pixelWidth;
  15688. texture.height = ktx.pixelHeight;
  15689. texture.isReady = true;
  15690. }, undefined, undefined, true, onerror);
  15691. }
  15692. else if (isDDS) {
  15693. if (files && files.length === 6) {
  15694. this._cascadeLoadFiles(scene, function (imgs) {
  15695. var info;
  15696. var loadMipmap = false;
  15697. var width = 0;
  15698. for (var index = 0; index < imgs.length; index++) {
  15699. var data = imgs[index];
  15700. info = BABYLON.DDSTools.GetDDSInfo(data);
  15701. loadMipmap = (info.isRGB || info.isLuminance || info.mipmapCount > 1) && !noMipmap;
  15702. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  15703. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, info.isCompressed ? 1 : 0);
  15704. BABYLON.DDSTools.UploadDDSLevels(_this, _this._gl, data, info, loadMipmap, 6, -1, index);
  15705. if (!noMipmap && !info.isFourCC && info.mipmapCount === 1) {
  15706. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  15707. }
  15708. texture.width = info.width;
  15709. texture.height = info.height;
  15710. texture.type = info.textureType;
  15711. width = info.width;
  15712. }
  15713. _this.setCubeMapTextureParams(gl, loadMipmap);
  15714. texture.isReady = true;
  15715. if (onLoad) {
  15716. onLoad({ isDDS: true, width: width, info: info, imgs: imgs, texture: texture });
  15717. }
  15718. }, files, onError);
  15719. }
  15720. else {
  15721. this._loadFile(rootUrl, function (data) {
  15722. var info = BABYLON.DDSTools.GetDDSInfo(data);
  15723. if (createPolynomials) {
  15724. info.sphericalPolynomial = new BABYLON.SphericalPolynomial();
  15725. }
  15726. var loadMipmap = (info.isRGB || info.isLuminance || info.mipmapCount > 1) && !noMipmap;
  15727. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  15728. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, info.isCompressed ? 1 : 0);
  15729. BABYLON.DDSTools.UploadDDSLevels(_this, _this._gl, data, info, loadMipmap, 6);
  15730. if (!noMipmap && !info.isFourCC && info.mipmapCount === 1) {
  15731. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  15732. }
  15733. _this.setCubeMapTextureParams(gl, loadMipmap);
  15734. texture.width = info.width;
  15735. texture.height = info.height;
  15736. texture.isReady = true;
  15737. texture.type = info.textureType;
  15738. if (onLoad) {
  15739. onLoad({ isDDS: true, width: info.width, info: info, data: data, texture: texture });
  15740. }
  15741. }, undefined, undefined, true, onerror);
  15742. }
  15743. }
  15744. else {
  15745. if (!files) {
  15746. throw new Error("Cannot load cubemap because files were not defined");
  15747. }
  15748. cascadeLoadImgs(rootUrl, scene, function (imgs) {
  15749. var width = _this.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(imgs[0].width, _this._caps.maxCubemapTextureSize) : imgs[0].width;
  15750. var height = width;
  15751. _this._prepareWorkingCanvas();
  15752. if (!_this._workingCanvas || !_this._workingContext) {
  15753. return;
  15754. }
  15755. _this._workingCanvas.width = width;
  15756. _this._workingCanvas.height = height;
  15757. var faces = [
  15758. gl.TEXTURE_CUBE_MAP_POSITIVE_X, gl.TEXTURE_CUBE_MAP_POSITIVE_Y, gl.TEXTURE_CUBE_MAP_POSITIVE_Z,
  15759. gl.TEXTURE_CUBE_MAP_NEGATIVE_X, gl.TEXTURE_CUBE_MAP_NEGATIVE_Y, gl.TEXTURE_CUBE_MAP_NEGATIVE_Z
  15760. ];
  15761. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  15762. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, 0);
  15763. var internalFormat = format ? _this._getInternalFormat(format) : _this._gl.RGBA;
  15764. for (var index = 0; index < faces.length; index++) {
  15765. _this._workingContext.drawImage(imgs[index], 0, 0, imgs[index].width, imgs[index].height, 0, 0, width, height);
  15766. gl.texImage2D(faces[index], 0, internalFormat, internalFormat, gl.UNSIGNED_BYTE, _this._workingCanvas);
  15767. }
  15768. if (!noMipmap) {
  15769. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  15770. }
  15771. _this.setCubeMapTextureParams(gl, !noMipmap);
  15772. texture.width = width;
  15773. texture.height = height;
  15774. texture.isReady = true;
  15775. if (format) {
  15776. texture.format = format;
  15777. }
  15778. texture.onLoadedObservable.notifyObservers(texture);
  15779. texture.onLoadedObservable.clear();
  15780. if (onLoad) {
  15781. onLoad();
  15782. }
  15783. }, files, onError);
  15784. }
  15785. this._internalTexturesCache.push(texture);
  15786. return texture;
  15787. };
  15788. Engine.prototype.setCubeMapTextureParams = function (gl, loadMipmap) {
  15789. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  15790. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, loadMipmap ? gl.LINEAR_MIPMAP_LINEAR : gl.LINEAR);
  15791. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  15792. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  15793. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  15794. // this.resetTextureCache();
  15795. };
  15796. /**
  15797. * Update a raw cube texture
  15798. * @param texture defines the texture to udpdate
  15799. * @param data defines the data to store
  15800. * @param format defines the data format
  15801. * @param type defines the type fo the data (BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT by default)
  15802. * @param invertY defines if data must be stored with Y axis inverted
  15803. * @param compression defines the compression used (null by default)
  15804. * @param level defines which level of the texture to update
  15805. */
  15806. Engine.prototype.updateRawCubeTexture = function (texture, data, format, type, invertY, compression, level) {
  15807. if (compression === void 0) { compression = null; }
  15808. if (level === void 0) { level = 0; }
  15809. texture._bufferViewArray = data;
  15810. texture.format = format;
  15811. texture.type = type;
  15812. texture.invertY = invertY;
  15813. texture._compression = compression;
  15814. var gl = this._gl;
  15815. var textureType = this._getWebGLTextureType(type);
  15816. var internalFormat = this._getInternalFormat(format);
  15817. var internalSizedFomat = this._getRGBABufferInternalSizedFormat(type);
  15818. var needConversion = false;
  15819. if (internalFormat === gl.RGB) {
  15820. internalFormat = gl.RGBA;
  15821. needConversion = true;
  15822. }
  15823. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  15824. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, invertY === undefined ? 1 : (invertY ? 1 : 0));
  15825. if (texture.width % 4 !== 0) {
  15826. gl.pixelStorei(gl.UNPACK_ALIGNMENT, 1);
  15827. }
  15828. // Data are known to be in +X +Y +Z -X -Y -Z
  15829. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  15830. var faceData = data[faceIndex];
  15831. if (compression) {
  15832. gl.compressedTexImage2D(gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, level, (this.getCaps().s3tc)[compression], texture.width, texture.height, 0, faceData);
  15833. }
  15834. else {
  15835. if (needConversion) {
  15836. faceData = this._convertRGBtoRGBATextureData(faceData, texture.width, texture.height, type);
  15837. }
  15838. gl.texImage2D(gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, level, internalSizedFomat, texture.width, texture.height, 0, internalFormat, textureType, faceData);
  15839. }
  15840. }
  15841. var isPot = !this.needPOTTextures || (BABYLON.Tools.IsExponentOfTwo(texture.width) && BABYLON.Tools.IsExponentOfTwo(texture.height));
  15842. if (isPot && texture.generateMipMaps && level === 0) {
  15843. this._gl.generateMipmap(this._gl.TEXTURE_CUBE_MAP);
  15844. }
  15845. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  15846. // this.resetTextureCache();
  15847. texture.isReady = true;
  15848. };
  15849. /**
  15850. * Creates a new raw cube texture
  15851. * @param data defines the array of data to use to create each face
  15852. * @param size defines the size of the textures
  15853. * @param format defines the format of the data
  15854. * @param type defines the type fo the data (like BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT)
  15855. * @param generateMipMaps defines if the engine should generate the mip levels
  15856. * @param invertY defines if data must be stored with Y axis inverted
  15857. * @param samplingMode defines the required sampling mode (like BABYLON.Texture.NEAREST_SAMPLINGMODE)
  15858. * @param compression defines the compression used (null by default)
  15859. * @returns the cube texture as an InternalTexture
  15860. */
  15861. Engine.prototype.createRawCubeTexture = function (data, size, format, type, generateMipMaps, invertY, samplingMode, compression) {
  15862. if (compression === void 0) { compression = null; }
  15863. var gl = this._gl;
  15864. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_CUBERAW);
  15865. texture.isCube = true;
  15866. texture.generateMipMaps = generateMipMaps;
  15867. texture.format = format;
  15868. texture.type = type;
  15869. if (!this._doNotHandleContextLost) {
  15870. texture._bufferViewArray = data;
  15871. }
  15872. var textureType = this._getWebGLTextureType(type);
  15873. var internalFormat = this._getInternalFormat(format);
  15874. if (internalFormat === gl.RGB) {
  15875. internalFormat = gl.RGBA;
  15876. }
  15877. var width = size;
  15878. var height = width;
  15879. texture.width = width;
  15880. texture.height = height;
  15881. // Double check on POT to generate Mips.
  15882. var isPot = !this.needPOTTextures || (BABYLON.Tools.IsExponentOfTwo(texture.width) && BABYLON.Tools.IsExponentOfTwo(texture.height));
  15883. if (!isPot) {
  15884. generateMipMaps = false;
  15885. }
  15886. // Upload data if needed. The texture won't be ready until then.
  15887. if (data) {
  15888. this.updateRawCubeTexture(texture, data, format, type, invertY, compression);
  15889. }
  15890. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, texture, true);
  15891. // Filters
  15892. if (data && generateMipMaps) {
  15893. this._gl.generateMipmap(this._gl.TEXTURE_CUBE_MAP);
  15894. }
  15895. if (textureType === gl.FLOAT && !this._caps.textureFloatLinearFiltering) {
  15896. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
  15897. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
  15898. }
  15899. else if (textureType === this._gl.HALF_FLOAT_OES && !this._caps.textureHalfFloatLinearFiltering) {
  15900. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
  15901. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
  15902. }
  15903. else {
  15904. var filters = getSamplingParameters(samplingMode, generateMipMaps, gl);
  15905. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, filters.mag);
  15906. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, filters.min);
  15907. }
  15908. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  15909. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  15910. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  15911. return texture;
  15912. };
  15913. /**
  15914. * Creates a new raw cube texture from a specified url
  15915. * @param url defines the url where the data is located
  15916. * @param scene defines the current scene
  15917. * @param size defines the size of the textures
  15918. * @param format defines the format of the data
  15919. * @param type defines the type fo the data (like BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT)
  15920. * @param noMipmap defines if the engine should avoid generating the mip levels
  15921. * @param callback defines a callback used to extract texture data from loaded data
  15922. * @param mipmapGenerator defines to provide an optional tool to generate mip levels
  15923. * @param onLoad defines a callback called when texture is loaded
  15924. * @param onError defines a callback called if there is an error
  15925. * @param samplingMode defines the required sampling mode (like BABYLON.Texture.NEAREST_SAMPLINGMODE)
  15926. * @param invertY defines if data must be stored with Y axis inverted
  15927. * @returns the cube texture as an InternalTexture
  15928. */
  15929. Engine.prototype.createRawCubeTextureFromUrl = function (url, scene, size, format, type, noMipmap, callback, mipmapGenerator, onLoad, onError, samplingMode, invertY) {
  15930. var _this = this;
  15931. if (onLoad === void 0) { onLoad = null; }
  15932. if (onError === void 0) { onError = null; }
  15933. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  15934. if (invertY === void 0) { invertY = false; }
  15935. var gl = this._gl;
  15936. var texture = this.createRawCubeTexture(null, size, format, type, !noMipmap, invertY, samplingMode);
  15937. scene._addPendingData(texture);
  15938. texture.url = url;
  15939. this._internalTexturesCache.push(texture);
  15940. var onerror = function (request, exception) {
  15941. scene._removePendingData(texture);
  15942. if (onError && request) {
  15943. onError(request.status + " " + request.statusText, exception);
  15944. }
  15945. };
  15946. var internalCallback = function (data) {
  15947. var width = texture.width;
  15948. var faceDataArrays = callback(data);
  15949. if (!faceDataArrays) {
  15950. return;
  15951. }
  15952. if (mipmapGenerator) {
  15953. var textureType = _this._getWebGLTextureType(type);
  15954. var internalFormat = _this._getInternalFormat(format);
  15955. var internalSizedFomat = _this._getRGBABufferInternalSizedFormat(type);
  15956. var needConversion = false;
  15957. if (internalFormat === gl.RGB) {
  15958. internalFormat = gl.RGBA;
  15959. needConversion = true;
  15960. }
  15961. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  15962. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, 0);
  15963. var mipData = mipmapGenerator(faceDataArrays);
  15964. for (var level = 0; level < mipData.length; level++) {
  15965. var mipSize = width >> level;
  15966. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  15967. var mipFaceData = mipData[level][faceIndex];
  15968. if (needConversion) {
  15969. mipFaceData = _this._convertRGBtoRGBATextureData(mipFaceData, mipSize, mipSize, type);
  15970. }
  15971. gl.texImage2D(faceIndex, level, internalSizedFomat, mipSize, mipSize, 0, internalFormat, textureType, mipFaceData);
  15972. }
  15973. }
  15974. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  15975. }
  15976. else {
  15977. texture.generateMipMaps = !noMipmap;
  15978. _this.updateRawCubeTexture(texture, faceDataArrays, format, type, invertY);
  15979. }
  15980. texture.isReady = true;
  15981. // this.resetTextureCache();
  15982. scene._removePendingData(texture);
  15983. if (onLoad) {
  15984. onLoad();
  15985. }
  15986. };
  15987. this._loadFile(url, function (data) {
  15988. internalCallback(data);
  15989. }, undefined, scene.database, true, onerror);
  15990. return texture;
  15991. };
  15992. ;
  15993. /**
  15994. * Update a raw 3D texture
  15995. * @param texture defines the texture to update
  15996. * @param data defines the data to store
  15997. * @param format defines the data format
  15998. * @param invertY defines if data must be stored with Y axis inverted
  15999. * @param compression defines the used compression (can be null)
  16000. */
  16001. Engine.prototype.updateRawTexture3D = function (texture, data, format, invertY, compression) {
  16002. if (compression === void 0) { compression = null; }
  16003. var internalFormat = this._getInternalFormat(format);
  16004. this._bindTextureDirectly(this._gl.TEXTURE_3D, texture, true);
  16005. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY === undefined ? 1 : (invertY ? 1 : 0));
  16006. if (!this._doNotHandleContextLost) {
  16007. texture._bufferView = data;
  16008. texture.format = format;
  16009. texture.invertY = invertY;
  16010. texture._compression = compression;
  16011. }
  16012. if (texture.width % 4 !== 0) {
  16013. this._gl.pixelStorei(this._gl.UNPACK_ALIGNMENT, 1);
  16014. }
  16015. if (compression && data) {
  16016. this._gl.compressedTexImage3D(this._gl.TEXTURE_3D, 0, this.getCaps().s3tc[compression], texture.width, texture.height, texture.depth, 0, data);
  16017. }
  16018. else {
  16019. this._gl.texImage3D(this._gl.TEXTURE_3D, 0, internalFormat, texture.width, texture.height, texture.depth, 0, internalFormat, this._gl.UNSIGNED_BYTE, data);
  16020. }
  16021. if (texture.generateMipMaps) {
  16022. this._gl.generateMipmap(this._gl.TEXTURE_3D);
  16023. }
  16024. this._bindTextureDirectly(this._gl.TEXTURE_3D, null);
  16025. // this.resetTextureCache();
  16026. texture.isReady = true;
  16027. };
  16028. /**
  16029. * Creates a new raw 3D texture
  16030. * @param data defines the data used to create the texture
  16031. * @param width defines the width of the texture
  16032. * @param height defines the height of the texture
  16033. * @param depth defines the depth of the texture
  16034. * @param format defines the format of the texture
  16035. * @param generateMipMaps defines if the engine must generate mip levels
  16036. * @param invertY defines if data must be stored with Y axis inverted
  16037. * @param samplingMode defines the required sampling mode (like BABYLON.Texture.NEAREST_SAMPLINGMODE)
  16038. * @param compression defines the compressed used (can be null)
  16039. * @returns a new raw 3D texture (stored in an InternalTexture)
  16040. */
  16041. Engine.prototype.createRawTexture3D = function (data, width, height, depth, format, generateMipMaps, invertY, samplingMode, compression) {
  16042. if (compression === void 0) { compression = null; }
  16043. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_RAW3D);
  16044. texture.baseWidth = width;
  16045. texture.baseHeight = height;
  16046. texture.baseDepth = depth;
  16047. texture.width = width;
  16048. texture.height = height;
  16049. texture.depth = depth;
  16050. texture.format = format;
  16051. texture.generateMipMaps = generateMipMaps;
  16052. texture.samplingMode = samplingMode;
  16053. texture.is3D = true;
  16054. if (!this._doNotHandleContextLost) {
  16055. texture._bufferView = data;
  16056. }
  16057. this.updateRawTexture3D(texture, data, format, invertY, compression);
  16058. this._bindTextureDirectly(this._gl.TEXTURE_3D, texture, true);
  16059. // Filters
  16060. var filters = getSamplingParameters(samplingMode, generateMipMaps, this._gl);
  16061. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  16062. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  16063. if (generateMipMaps) {
  16064. this._gl.generateMipmap(this._gl.TEXTURE_3D);
  16065. }
  16066. this._bindTextureDirectly(this._gl.TEXTURE_3D, null);
  16067. this._internalTexturesCache.push(texture);
  16068. return texture;
  16069. };
  16070. Engine.prototype._prepareWebGLTextureContinuation = function (texture, scene, noMipmap, isCompressed, samplingMode) {
  16071. var gl = this._gl;
  16072. if (!gl) {
  16073. return;
  16074. }
  16075. var filters = getSamplingParameters(samplingMode, !noMipmap, gl);
  16076. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, filters.mag);
  16077. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, filters.min);
  16078. if (!noMipmap && !isCompressed) {
  16079. gl.generateMipmap(gl.TEXTURE_2D);
  16080. }
  16081. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  16082. // this.resetTextureCache();
  16083. if (scene) {
  16084. scene._removePendingData(texture);
  16085. }
  16086. texture.onLoadedObservable.notifyObservers(texture);
  16087. texture.onLoadedObservable.clear();
  16088. };
  16089. Engine.prototype._prepareWebGLTexture = function (texture, scene, width, height, invertY, noMipmap, isCompressed, processFunction, samplingMode) {
  16090. var _this = this;
  16091. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  16092. var potWidth = this.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(width, this.getCaps().maxTextureSize) : width;
  16093. var potHeight = this.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(height, this.getCaps().maxTextureSize) : height;
  16094. var gl = this._gl;
  16095. if (!gl) {
  16096. return;
  16097. }
  16098. if (!texture._webGLTexture) {
  16099. // this.resetTextureCache();
  16100. if (scene) {
  16101. scene._removePendingData(texture);
  16102. }
  16103. return;
  16104. }
  16105. this._bindTextureDirectly(gl.TEXTURE_2D, texture, true);
  16106. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, invertY === undefined ? 1 : (invertY ? 1 : 0));
  16107. texture.baseWidth = width;
  16108. texture.baseHeight = height;
  16109. texture.width = potWidth;
  16110. texture.height = potHeight;
  16111. texture.isReady = true;
  16112. if (processFunction(potWidth, potHeight, function () {
  16113. _this._prepareWebGLTextureContinuation(texture, scene, noMipmap, isCompressed, samplingMode);
  16114. })) {
  16115. // Returning as texture needs extra async steps
  16116. return;
  16117. }
  16118. this._prepareWebGLTextureContinuation(texture, scene, noMipmap, isCompressed, samplingMode);
  16119. };
  16120. Engine.prototype._convertRGBtoRGBATextureData = function (rgbData, width, height, textureType) {
  16121. // Create new RGBA data container.
  16122. var rgbaData;
  16123. if (textureType === Engine.TEXTURETYPE_FLOAT) {
  16124. rgbaData = new Float32Array(width * height * 4);
  16125. }
  16126. else {
  16127. rgbaData = new Uint32Array(width * height * 4);
  16128. }
  16129. // Convert each pixel.
  16130. for (var x = 0; x < width; x++) {
  16131. for (var y = 0; y < height; y++) {
  16132. var index = (y * width + x) * 3;
  16133. var newIndex = (y * width + x) * 4;
  16134. // Map Old Value to new value.
  16135. rgbaData[newIndex + 0] = rgbData[index + 0];
  16136. rgbaData[newIndex + 1] = rgbData[index + 1];
  16137. rgbaData[newIndex + 2] = rgbData[index + 2];
  16138. // Add fully opaque alpha channel.
  16139. rgbaData[newIndex + 3] = 1;
  16140. }
  16141. }
  16142. return rgbaData;
  16143. };
  16144. /** @hidden */
  16145. Engine.prototype._releaseFramebufferObjects = function (texture) {
  16146. var gl = this._gl;
  16147. if (texture._framebuffer) {
  16148. gl.deleteFramebuffer(texture._framebuffer);
  16149. texture._framebuffer = null;
  16150. }
  16151. if (texture._depthStencilBuffer) {
  16152. gl.deleteRenderbuffer(texture._depthStencilBuffer);
  16153. texture._depthStencilBuffer = null;
  16154. }
  16155. if (texture._MSAAFramebuffer) {
  16156. gl.deleteFramebuffer(texture._MSAAFramebuffer);
  16157. texture._MSAAFramebuffer = null;
  16158. }
  16159. if (texture._MSAARenderBuffer) {
  16160. gl.deleteRenderbuffer(texture._MSAARenderBuffer);
  16161. texture._MSAARenderBuffer = null;
  16162. }
  16163. };
  16164. /** @hidden */
  16165. Engine.prototype._releaseTexture = function (texture) {
  16166. var gl = this._gl;
  16167. this._releaseFramebufferObjects(texture);
  16168. gl.deleteTexture(texture._webGLTexture);
  16169. // Unbind channels
  16170. this.unbindAllTextures();
  16171. var index = this._internalTexturesCache.indexOf(texture);
  16172. if (index !== -1) {
  16173. this._internalTexturesCache.splice(index, 1);
  16174. }
  16175. // Integrated fixed lod samplers.
  16176. if (texture._lodTextureHigh) {
  16177. texture._lodTextureHigh.dispose();
  16178. }
  16179. if (texture._lodTextureMid) {
  16180. texture._lodTextureMid.dispose();
  16181. }
  16182. if (texture._lodTextureLow) {
  16183. texture._lodTextureLow.dispose();
  16184. }
  16185. // Set output texture of post process to null if the texture has been released/disposed
  16186. this.scenes.forEach(function (scene) {
  16187. scene.postProcesses.forEach(function (postProcess) {
  16188. if (postProcess._outputTexture == texture) {
  16189. postProcess._outputTexture = null;
  16190. }
  16191. });
  16192. scene.cameras.forEach(function (camera) {
  16193. camera._postProcesses.forEach(function (postProcess) {
  16194. if (postProcess) {
  16195. if (postProcess._outputTexture == texture) {
  16196. postProcess._outputTexture = null;
  16197. }
  16198. }
  16199. });
  16200. });
  16201. });
  16202. };
  16203. Engine.prototype.setProgram = function (program) {
  16204. if (this._currentProgram !== program) {
  16205. this._gl.useProgram(program);
  16206. this._currentProgram = program;
  16207. }
  16208. };
  16209. /**
  16210. * Binds an effect to the webGL context
  16211. * @param effect defines the effect to bind
  16212. */
  16213. Engine.prototype.bindSamplers = function (effect) {
  16214. this.setProgram(effect.getProgram());
  16215. var samplers = effect.getSamplers();
  16216. for (var index = 0; index < samplers.length; index++) {
  16217. var uniform = effect.getUniform(samplers[index]);
  16218. if (uniform) {
  16219. this._boundUniforms[index] = uniform;
  16220. }
  16221. }
  16222. this._currentEffect = null;
  16223. };
  16224. Engine.prototype._moveBoundTextureOnTop = function (internalTexture) {
  16225. if (this.disableTextureBindingOptimization || this._lastBoundInternalTextureTracker.previous === internalTexture) {
  16226. return;
  16227. }
  16228. // Remove
  16229. this._linkTrackers(internalTexture.previous, internalTexture.next);
  16230. // Bind last to it
  16231. this._linkTrackers(this._lastBoundInternalTextureTracker.previous, internalTexture);
  16232. // Bind to dummy
  16233. this._linkTrackers(internalTexture, this._lastBoundInternalTextureTracker);
  16234. };
  16235. Engine.prototype._getCorrectTextureChannel = function (channel, internalTexture) {
  16236. if (!internalTexture) {
  16237. return -1;
  16238. }
  16239. internalTexture._initialSlot = channel;
  16240. if (this.disableTextureBindingOptimization) { // We want texture sampler ID === texture channel
  16241. if (channel !== internalTexture._designatedSlot) {
  16242. this._textureCollisions.addCount(1, false);
  16243. }
  16244. }
  16245. else {
  16246. if (channel !== internalTexture._designatedSlot) {
  16247. if (internalTexture._designatedSlot > -1) { // Texture is already assigned to a slot
  16248. return internalTexture._designatedSlot;
  16249. }
  16250. else {
  16251. // No slot for this texture, let's pick a new one (if we find a free slot)
  16252. if (this._nextFreeTextureSlots.length) {
  16253. return this._nextFreeTextureSlots[0];
  16254. }
  16255. // We need to recycle the oldest bound texture, sorry.
  16256. this._textureCollisions.addCount(1, false);
  16257. return this._removeDesignatedSlot(this._firstBoundInternalTextureTracker.next);
  16258. }
  16259. }
  16260. }
  16261. return channel;
  16262. };
  16263. Engine.prototype._linkTrackers = function (previous, next) {
  16264. previous.next = next;
  16265. next.previous = previous;
  16266. };
  16267. Engine.prototype._removeDesignatedSlot = function (internalTexture) {
  16268. var currentSlot = internalTexture._designatedSlot;
  16269. if (currentSlot === -1) {
  16270. return -1;
  16271. }
  16272. internalTexture._designatedSlot = -1;
  16273. if (this.disableTextureBindingOptimization) {
  16274. return -1;
  16275. }
  16276. // Remove from bound list
  16277. this._linkTrackers(internalTexture.previous, internalTexture.next);
  16278. // Free the slot
  16279. this._boundTexturesCache[currentSlot] = null;
  16280. this._nextFreeTextureSlots.push(currentSlot);
  16281. return currentSlot;
  16282. };
  16283. Engine.prototype._activateCurrentTexture = function () {
  16284. if (this._currentTextureChannel !== this._activeChannel) {
  16285. this._gl.activeTexture(this._gl.TEXTURE0 + this._activeChannel);
  16286. this._currentTextureChannel = this._activeChannel;
  16287. }
  16288. };
  16289. /** @hidden */
  16290. Engine.prototype._bindTextureDirectly = function (target, texture, forTextureDataUpdate, force) {
  16291. if (forTextureDataUpdate === void 0) { forTextureDataUpdate = false; }
  16292. if (force === void 0) { force = false; }
  16293. if (forTextureDataUpdate && texture && texture._designatedSlot > -1) {
  16294. this._activeChannel = texture._designatedSlot;
  16295. }
  16296. var currentTextureBound = this._boundTexturesCache[this._activeChannel];
  16297. var isTextureForRendering = texture && texture._initialSlot > -1;
  16298. if (currentTextureBound !== texture || force) {
  16299. if (currentTextureBound) {
  16300. this._removeDesignatedSlot(currentTextureBound);
  16301. }
  16302. this._activateCurrentTexture();
  16303. this._gl.bindTexture(target, texture ? texture._webGLTexture : null);
  16304. this._boundTexturesCache[this._activeChannel] = texture;
  16305. if (texture) {
  16306. if (!this.disableTextureBindingOptimization) {
  16307. var slotIndex = this._nextFreeTextureSlots.indexOf(this._activeChannel);
  16308. if (slotIndex > -1) {
  16309. this._nextFreeTextureSlots.splice(slotIndex, 1);
  16310. }
  16311. this._linkTrackers(this._lastBoundInternalTextureTracker.previous, texture);
  16312. this._linkTrackers(texture, this._lastBoundInternalTextureTracker);
  16313. }
  16314. texture._designatedSlot = this._activeChannel;
  16315. }
  16316. }
  16317. else if (forTextureDataUpdate) {
  16318. this._activateCurrentTexture();
  16319. }
  16320. if (isTextureForRendering && !forTextureDataUpdate) {
  16321. this._bindSamplerUniformToChannel(texture._initialSlot, this._activeChannel);
  16322. }
  16323. };
  16324. /** @hidden */
  16325. Engine.prototype._bindTexture = function (channel, texture) {
  16326. if (channel < 0) {
  16327. return;
  16328. }
  16329. if (texture) {
  16330. channel = this._getCorrectTextureChannel(channel, texture);
  16331. }
  16332. this._activeChannel = channel;
  16333. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture);
  16334. };
  16335. /**
  16336. * Sets a texture to the webGL context from a postprocess
  16337. * @param channel defines the channel to use
  16338. * @param postProcess defines the source postprocess
  16339. */
  16340. Engine.prototype.setTextureFromPostProcess = function (channel, postProcess) {
  16341. this._bindTexture(channel, postProcess ? postProcess._textures.data[postProcess._currentRenderTextureInd] : null);
  16342. };
  16343. /**
  16344. * Binds the output of the passed in post process to the texture channel specified
  16345. * @param channel The channel the texture should be bound to
  16346. * @param postProcess The post process which's output should be bound
  16347. */
  16348. Engine.prototype.setTextureFromPostProcessOutput = function (channel, postProcess) {
  16349. this._bindTexture(channel, postProcess ? postProcess._outputTexture : null);
  16350. };
  16351. /**
  16352. * Unbind all textures from the webGL context
  16353. */
  16354. Engine.prototype.unbindAllTextures = function () {
  16355. for (var channel = 0; channel < this._maxSimultaneousTextures; channel++) {
  16356. this._activeChannel = channel;
  16357. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  16358. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  16359. if (this.webGLVersion > 1) {
  16360. this._bindTextureDirectly(this._gl.TEXTURE_3D, null);
  16361. }
  16362. }
  16363. };
  16364. /**
  16365. * Sets a texture to the according uniform.
  16366. * @param channel The texture channel
  16367. * @param uniform The uniform to set
  16368. * @param texture The texture to apply
  16369. */
  16370. Engine.prototype.setTexture = function (channel, uniform, texture) {
  16371. if (channel < 0) {
  16372. return;
  16373. }
  16374. if (uniform) {
  16375. this._boundUniforms[channel] = uniform;
  16376. }
  16377. this._setTexture(channel, texture);
  16378. };
  16379. /**
  16380. * Sets a depth stencil texture from a render target to the according uniform.
  16381. * @param channel The texture channel
  16382. * @param uniform The uniform to set
  16383. * @param texture The render target texture containing the depth stencil texture to apply
  16384. */
  16385. Engine.prototype.setDepthStencilTexture = function (channel, uniform, texture) {
  16386. if (channel < 0) {
  16387. return;
  16388. }
  16389. if (uniform) {
  16390. this._boundUniforms[channel] = uniform;
  16391. }
  16392. if (!texture || !texture.depthStencilTexture) {
  16393. this._setTexture(channel, null);
  16394. }
  16395. else {
  16396. this._setTexture(channel, texture, false, true);
  16397. }
  16398. };
  16399. Engine.prototype._bindSamplerUniformToChannel = function (sourceSlot, destination) {
  16400. var uniform = this._boundUniforms[sourceSlot];
  16401. if (uniform._currentState === destination) {
  16402. return;
  16403. }
  16404. this._gl.uniform1i(uniform, destination);
  16405. uniform._currentState = destination;
  16406. };
  16407. Engine.prototype._getTextureWrapMode = function (mode) {
  16408. switch (mode) {
  16409. case BABYLON.Texture.WRAP_ADDRESSMODE:
  16410. return this._gl.REPEAT;
  16411. case BABYLON.Texture.CLAMP_ADDRESSMODE:
  16412. return this._gl.CLAMP_TO_EDGE;
  16413. case BABYLON.Texture.MIRROR_ADDRESSMODE:
  16414. return this._gl.MIRRORED_REPEAT;
  16415. }
  16416. return this._gl.REPEAT;
  16417. };
  16418. Engine.prototype._setTexture = function (channel, texture, isPartOfTextureArray, depthStencilTexture) {
  16419. if (isPartOfTextureArray === void 0) { isPartOfTextureArray = false; }
  16420. if (depthStencilTexture === void 0) { depthStencilTexture = false; }
  16421. // Not ready?
  16422. if (!texture) {
  16423. if (this._boundTexturesCache[channel] != null) {
  16424. this._activeChannel = channel;
  16425. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  16426. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  16427. if (this.webGLVersion > 1) {
  16428. this._bindTextureDirectly(this._gl.TEXTURE_3D, null);
  16429. }
  16430. }
  16431. return false;
  16432. }
  16433. // Video
  16434. if (texture.video) {
  16435. this._activeChannel = channel;
  16436. texture.update();
  16437. }
  16438. else if (texture.delayLoadState === Engine.DELAYLOADSTATE_NOTLOADED) { // Delay loading
  16439. texture.delayLoad();
  16440. return false;
  16441. }
  16442. var internalTexture;
  16443. if (depthStencilTexture) {
  16444. internalTexture = texture.depthStencilTexture;
  16445. }
  16446. else if (texture.isReady()) {
  16447. internalTexture = texture.getInternalTexture();
  16448. }
  16449. else if (texture.isCube) {
  16450. internalTexture = this.emptyCubeTexture;
  16451. }
  16452. else if (texture.is3D) {
  16453. internalTexture = this.emptyTexture3D;
  16454. }
  16455. else {
  16456. internalTexture = this.emptyTexture;
  16457. }
  16458. if (!isPartOfTextureArray) {
  16459. channel = this._getCorrectTextureChannel(channel, internalTexture);
  16460. }
  16461. var needToBind = true;
  16462. if (this._boundTexturesCache[channel] === internalTexture) {
  16463. this._moveBoundTextureOnTop(internalTexture);
  16464. if (!isPartOfTextureArray) {
  16465. this._bindSamplerUniformToChannel(internalTexture._initialSlot, channel);
  16466. }
  16467. needToBind = false;
  16468. }
  16469. this._activeChannel = channel;
  16470. if (internalTexture && internalTexture.is3D) {
  16471. if (needToBind) {
  16472. this._bindTextureDirectly(this._gl.TEXTURE_3D, internalTexture, isPartOfTextureArray);
  16473. }
  16474. if (internalTexture && internalTexture._cachedWrapU !== texture.wrapU) {
  16475. internalTexture._cachedWrapU = texture.wrapU;
  16476. this._setTextureParameterInteger(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_S, this._getTextureWrapMode(texture.wrapU), internalTexture);
  16477. }
  16478. if (internalTexture && internalTexture._cachedWrapV !== texture.wrapV) {
  16479. internalTexture._cachedWrapV = texture.wrapV;
  16480. this._setTextureParameterInteger(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_T, this._getTextureWrapMode(texture.wrapV), internalTexture);
  16481. }
  16482. if (internalTexture && internalTexture._cachedWrapR !== texture.wrapR) {
  16483. internalTexture._cachedWrapR = texture.wrapR;
  16484. this._setTextureParameterInteger(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_R, this._getTextureWrapMode(texture.wrapR), internalTexture);
  16485. }
  16486. this._setAnisotropicLevel(this._gl.TEXTURE_3D, texture);
  16487. }
  16488. else if (internalTexture && internalTexture.isCube) {
  16489. if (needToBind) {
  16490. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, internalTexture, isPartOfTextureArray);
  16491. }
  16492. if (internalTexture._cachedCoordinatesMode !== texture.coordinatesMode) {
  16493. internalTexture._cachedCoordinatesMode = texture.coordinatesMode;
  16494. // CUBIC_MODE and SKYBOX_MODE both require CLAMP_TO_EDGE. All other modes use REPEAT.
  16495. var textureWrapMode = (texture.coordinatesMode !== BABYLON.Texture.CUBIC_MODE && texture.coordinatesMode !== BABYLON.Texture.SKYBOX_MODE) ? this._gl.REPEAT : this._gl.CLAMP_TO_EDGE;
  16496. this._setTextureParameterInteger(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_WRAP_S, textureWrapMode, internalTexture);
  16497. this._setTextureParameterInteger(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_WRAP_T, textureWrapMode);
  16498. }
  16499. this._setAnisotropicLevel(this._gl.TEXTURE_CUBE_MAP, texture);
  16500. }
  16501. else {
  16502. if (needToBind) {
  16503. this._bindTextureDirectly(this._gl.TEXTURE_2D, internalTexture, isPartOfTextureArray);
  16504. }
  16505. if (internalTexture && internalTexture._cachedWrapU !== texture.wrapU) {
  16506. internalTexture._cachedWrapU = texture.wrapU;
  16507. this._setTextureParameterInteger(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_S, this._getTextureWrapMode(texture.wrapU), internalTexture);
  16508. }
  16509. if (internalTexture && internalTexture._cachedWrapV !== texture.wrapV) {
  16510. internalTexture._cachedWrapV = texture.wrapV;
  16511. this._setTextureParameterInteger(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_T, this._getTextureWrapMode(texture.wrapV), internalTexture);
  16512. }
  16513. this._setAnisotropicLevel(this._gl.TEXTURE_2D, texture);
  16514. }
  16515. return true;
  16516. };
  16517. /**
  16518. * Sets an array of texture to the webGL context
  16519. * @param channel defines the channel where the texture array must be set
  16520. * @param uniform defines the associated uniform location
  16521. * @param textures defines the array of textures to bind
  16522. */
  16523. Engine.prototype.setTextureArray = function (channel, uniform, textures) {
  16524. if (channel < 0 || !uniform) {
  16525. return;
  16526. }
  16527. if (!this._textureUnits || this._textureUnits.length !== textures.length) {
  16528. this._textureUnits = new Int32Array(textures.length);
  16529. }
  16530. for (var i = 0; i < textures.length; i++) {
  16531. this._textureUnits[i] = this._getCorrectTextureChannel(channel + i, textures[i].getInternalTexture());
  16532. }
  16533. this._gl.uniform1iv(uniform, this._textureUnits);
  16534. for (var index = 0; index < textures.length; index++) {
  16535. this._setTexture(this._textureUnits[index], textures[index], true);
  16536. }
  16537. };
  16538. /** @hidden */
  16539. Engine.prototype._setAnisotropicLevel = function (target, texture) {
  16540. var internalTexture = texture.getInternalTexture();
  16541. if (!internalTexture) {
  16542. return;
  16543. }
  16544. var anisotropicFilterExtension = this._caps.textureAnisotropicFilterExtension;
  16545. var value = texture.anisotropicFilteringLevel;
  16546. if (internalTexture.samplingMode !== BABYLON.Texture.LINEAR_LINEAR_MIPNEAREST
  16547. && internalTexture.samplingMode !== BABYLON.Texture.LINEAR_LINEAR_MIPLINEAR
  16548. && internalTexture.samplingMode !== BABYLON.Texture.LINEAR_LINEAR) {
  16549. value = 1; // Forcing the anisotropic to 1 because else webgl will force filters to linear
  16550. }
  16551. if (anisotropicFilterExtension && internalTexture._cachedAnisotropicFilteringLevel !== value) {
  16552. this._setTextureParameterFloat(target, anisotropicFilterExtension.TEXTURE_MAX_ANISOTROPY_EXT, Math.min(value, this._caps.maxAnisotropy), internalTexture);
  16553. internalTexture._cachedAnisotropicFilteringLevel = value;
  16554. }
  16555. };
  16556. Engine.prototype._setTextureParameterFloat = function (target, parameter, value, texture) {
  16557. this._bindTextureDirectly(target, texture, true, true);
  16558. this._gl.texParameterf(target, parameter, value);
  16559. };
  16560. Engine.prototype._setTextureParameterInteger = function (target, parameter, value, texture) {
  16561. if (texture) {
  16562. this._bindTextureDirectly(target, texture, true, true);
  16563. }
  16564. this._gl.texParameteri(target, parameter, value);
  16565. };
  16566. /**
  16567. * Reads pixels from the current frame buffer. Please note that this function can be slow
  16568. * @param x defines the x coordinate of the rectangle where pixels must be read
  16569. * @param y defines the y coordinate of the rectangle where pixels must be read
  16570. * @param width defines the width of the rectangle where pixels must be read
  16571. * @param height defines the height of the rectangle where pixels must be read
  16572. * @returns a Uint8Array containing RGBA colors
  16573. */
  16574. Engine.prototype.readPixels = function (x, y, width, height) {
  16575. var data = new Uint8Array(height * width * 4);
  16576. this._gl.readPixels(x, y, width, height, this._gl.RGBA, this._gl.UNSIGNED_BYTE, data);
  16577. return data;
  16578. };
  16579. /**
  16580. * Add an externaly attached data from its key.
  16581. * This method call will fail and return false, if such key already exists.
  16582. * If you don't care and just want to get the data no matter what, use the more convenient getOrAddExternalDataWithFactory() method.
  16583. * @param key the unique key that identifies the data
  16584. * @param data the data object to associate to the key for this Engine instance
  16585. * @return true if no such key were already present and the data was added successfully, false otherwise
  16586. */
  16587. Engine.prototype.addExternalData = function (key, data) {
  16588. if (!this._externalData) {
  16589. this._externalData = new BABYLON.StringDictionary();
  16590. }
  16591. return this._externalData.add(key, data);
  16592. };
  16593. /**
  16594. * Get an externaly attached data from its key
  16595. * @param key the unique key that identifies the data
  16596. * @return the associated data, if present (can be null), or undefined if not present
  16597. */
  16598. Engine.prototype.getExternalData = function (key) {
  16599. if (!this._externalData) {
  16600. this._externalData = new BABYLON.StringDictionary();
  16601. }
  16602. return this._externalData.get(key);
  16603. };
  16604. /**
  16605. * Get an externaly attached data from its key, create it using a factory if it's not already present
  16606. * @param key the unique key that identifies the data
  16607. * @param factory the factory that will be called to create the instance if and only if it doesn't exists
  16608. * @return the associated data, can be null if the factory returned null.
  16609. */
  16610. Engine.prototype.getOrAddExternalDataWithFactory = function (key, factory) {
  16611. if (!this._externalData) {
  16612. this._externalData = new BABYLON.StringDictionary();
  16613. }
  16614. return this._externalData.getOrAddWithFactory(key, factory);
  16615. };
  16616. /**
  16617. * Remove an externaly attached data from the Engine instance
  16618. * @param key the unique key that identifies the data
  16619. * @return true if the data was successfully removed, false if it doesn't exist
  16620. */
  16621. Engine.prototype.removeExternalData = function (key) {
  16622. if (!this._externalData) {
  16623. this._externalData = new BABYLON.StringDictionary();
  16624. }
  16625. return this._externalData.remove(key);
  16626. };
  16627. /**
  16628. * Unbind all vertex attributes from the webGL context
  16629. */
  16630. Engine.prototype.unbindAllAttributes = function () {
  16631. if (this._mustWipeVertexAttributes) {
  16632. this._mustWipeVertexAttributes = false;
  16633. for (var i = 0; i < this._caps.maxVertexAttribs; i++) {
  16634. this._gl.disableVertexAttribArray(i);
  16635. this._vertexAttribArraysEnabled[i] = false;
  16636. this._currentBufferPointers[i].active = false;
  16637. }
  16638. return;
  16639. }
  16640. for (var i = 0, ul = this._vertexAttribArraysEnabled.length; i < ul; i++) {
  16641. if (i >= this._caps.maxVertexAttribs || !this._vertexAttribArraysEnabled[i]) {
  16642. continue;
  16643. }
  16644. this._gl.disableVertexAttribArray(i);
  16645. this._vertexAttribArraysEnabled[i] = false;
  16646. this._currentBufferPointers[i].active = false;
  16647. }
  16648. };
  16649. /**
  16650. * 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
  16651. */
  16652. Engine.prototype.releaseEffects = function () {
  16653. for (var name in this._compiledEffects) {
  16654. this._deleteProgram(this._compiledEffects[name]._program);
  16655. }
  16656. this._compiledEffects = {};
  16657. };
  16658. /**
  16659. * Dispose and release all associated resources
  16660. */
  16661. Engine.prototype.dispose = function () {
  16662. this.hideLoadingUI();
  16663. this.stopRenderLoop();
  16664. // Release postProcesses
  16665. while (this.postProcesses.length) {
  16666. this.postProcesses[0].dispose();
  16667. }
  16668. // Empty texture
  16669. if (this._emptyTexture) {
  16670. this._releaseTexture(this._emptyTexture);
  16671. this._emptyTexture = null;
  16672. }
  16673. if (this._emptyCubeTexture) {
  16674. this._releaseTexture(this._emptyCubeTexture);
  16675. this._emptyCubeTexture = null;
  16676. }
  16677. // Rescale PP
  16678. if (this._rescalePostProcess) {
  16679. this._rescalePostProcess.dispose();
  16680. }
  16681. // Release scenes
  16682. while (this.scenes.length) {
  16683. this.scenes[0].dispose();
  16684. }
  16685. // Release audio engine
  16686. if (Engine.audioEngine) {
  16687. Engine.audioEngine.dispose();
  16688. }
  16689. // Release effects
  16690. this.releaseEffects();
  16691. // Unbind
  16692. this.unbindAllAttributes();
  16693. this._boundUniforms = [];
  16694. if (this._dummyFramebuffer) {
  16695. this._gl.deleteFramebuffer(this._dummyFramebuffer);
  16696. }
  16697. //WebVR
  16698. this.disableVR();
  16699. // Events
  16700. if (BABYLON.Tools.IsWindowObjectExist()) {
  16701. window.removeEventListener("blur", this._onBlur);
  16702. window.removeEventListener("focus", this._onFocus);
  16703. window.removeEventListener('vrdisplaypointerrestricted', this._onVRDisplayPointerRestricted);
  16704. window.removeEventListener('vrdisplaypointerunrestricted', this._onVRDisplayPointerUnrestricted);
  16705. if (this._renderingCanvas) {
  16706. this._renderingCanvas.removeEventListener("focus", this._onCanvasFocus);
  16707. this._renderingCanvas.removeEventListener("blur", this._onCanvasBlur);
  16708. this._renderingCanvas.removeEventListener("pointerout", this._onCanvasPointerOut);
  16709. if (!this._doNotHandleContextLost) {
  16710. this._renderingCanvas.removeEventListener("webglcontextlost", this._onContextLost);
  16711. this._renderingCanvas.removeEventListener("webglcontextrestored", this._onContextRestored);
  16712. }
  16713. }
  16714. document.removeEventListener("fullscreenchange", this._onFullscreenChange);
  16715. document.removeEventListener("mozfullscreenchange", this._onFullscreenChange);
  16716. document.removeEventListener("webkitfullscreenchange", this._onFullscreenChange);
  16717. document.removeEventListener("msfullscreenchange", this._onFullscreenChange);
  16718. document.removeEventListener("pointerlockchange", this._onPointerLockChange);
  16719. document.removeEventListener("mspointerlockchange", this._onPointerLockChange);
  16720. document.removeEventListener("mozpointerlockchange", this._onPointerLockChange);
  16721. document.removeEventListener("webkitpointerlockchange", this._onPointerLockChange);
  16722. if (this._onVrDisplayConnect) {
  16723. window.removeEventListener('vrdisplayconnect', this._onVrDisplayConnect);
  16724. if (this._onVrDisplayDisconnect) {
  16725. window.removeEventListener('vrdisplaydisconnect', this._onVrDisplayDisconnect);
  16726. }
  16727. if (this._onVrDisplayPresentChange) {
  16728. window.removeEventListener('vrdisplaypresentchange', this._onVrDisplayPresentChange);
  16729. }
  16730. this._onVrDisplayConnect = null;
  16731. this._onVrDisplayDisconnect = null;
  16732. }
  16733. }
  16734. // Remove from Instances
  16735. var index = Engine.Instances.indexOf(this);
  16736. if (index >= 0) {
  16737. Engine.Instances.splice(index, 1);
  16738. }
  16739. this._workingCanvas = null;
  16740. this._workingContext = null;
  16741. this._currentBufferPointers = [];
  16742. this._renderingCanvas = null;
  16743. this._currentProgram = null;
  16744. this._bindedRenderFunction = null;
  16745. this.onResizeObservable.clear();
  16746. this.onCanvasBlurObservable.clear();
  16747. this.onCanvasFocusObservable.clear();
  16748. this.onCanvasPointerOutObservable.clear();
  16749. this.onBeginFrameObservable.clear();
  16750. this.onEndFrameObservable.clear();
  16751. BABYLON.Effect.ResetCache();
  16752. // Abort active requests
  16753. for (var _i = 0, _a = this._activeRequests; _i < _a.length; _i++) {
  16754. var request = _a[_i];
  16755. request.abort();
  16756. }
  16757. };
  16758. // Loading screen
  16759. /**
  16760. * Display the loading screen
  16761. * @see http://doc.babylonjs.com/how_to/creating_a_custom_loading_screen
  16762. */
  16763. Engine.prototype.displayLoadingUI = function () {
  16764. if (!BABYLON.Tools.IsWindowObjectExist()) {
  16765. return;
  16766. }
  16767. var loadingScreen = this.loadingScreen;
  16768. if (loadingScreen) {
  16769. loadingScreen.displayLoadingUI();
  16770. }
  16771. };
  16772. /**
  16773. * Hide the loading screen
  16774. * @see http://doc.babylonjs.com/how_to/creating_a_custom_loading_screen
  16775. */
  16776. Engine.prototype.hideLoadingUI = function () {
  16777. if (!BABYLON.Tools.IsWindowObjectExist()) {
  16778. return;
  16779. }
  16780. var loadingScreen = this.loadingScreen;
  16781. if (loadingScreen) {
  16782. loadingScreen.hideLoadingUI();
  16783. }
  16784. };
  16785. Object.defineProperty(Engine.prototype, "loadingScreen", {
  16786. /**
  16787. * Gets the current loading screen object
  16788. * @see http://doc.babylonjs.com/how_to/creating_a_custom_loading_screen
  16789. */
  16790. get: function () {
  16791. if (!this._loadingScreen && BABYLON.DefaultLoadingScreen && this._renderingCanvas)
  16792. this._loadingScreen = new BABYLON.DefaultLoadingScreen(this._renderingCanvas);
  16793. return this._loadingScreen;
  16794. },
  16795. /**
  16796. * Sets the current loading screen object
  16797. * @see http://doc.babylonjs.com/how_to/creating_a_custom_loading_screen
  16798. */
  16799. set: function (loadingScreen) {
  16800. this._loadingScreen = loadingScreen;
  16801. },
  16802. enumerable: true,
  16803. configurable: true
  16804. });
  16805. Object.defineProperty(Engine.prototype, "loadingUIText", {
  16806. /**
  16807. * Sets the current loading screen text
  16808. * @see http://doc.babylonjs.com/how_to/creating_a_custom_loading_screen
  16809. */
  16810. set: function (text) {
  16811. this.loadingScreen.loadingUIText = text;
  16812. },
  16813. enumerable: true,
  16814. configurable: true
  16815. });
  16816. Object.defineProperty(Engine.prototype, "loadingUIBackgroundColor", {
  16817. /**
  16818. * Sets the current loading screen background color
  16819. * @see http://doc.babylonjs.com/how_to/creating_a_custom_loading_screen
  16820. */
  16821. set: function (color) {
  16822. this.loadingScreen.loadingUIBackgroundColor = color;
  16823. },
  16824. enumerable: true,
  16825. configurable: true
  16826. });
  16827. /**
  16828. * Attach a new callback raised when context lost event is fired
  16829. * @param callback defines the callback to call
  16830. */
  16831. Engine.prototype.attachContextLostEvent = function (callback) {
  16832. if (this._renderingCanvas) {
  16833. this._renderingCanvas.addEventListener("webglcontextlost", callback, false);
  16834. }
  16835. };
  16836. /**
  16837. * Attach a new callback raised when context restored event is fired
  16838. * @param callback defines the callback to call
  16839. */
  16840. Engine.prototype.attachContextRestoredEvent = function (callback) {
  16841. if (this._renderingCanvas) {
  16842. this._renderingCanvas.addEventListener("webglcontextrestored", callback, false);
  16843. }
  16844. };
  16845. /**
  16846. * Gets the source code of the vertex shader associated with a specific webGL program
  16847. * @param program defines the program to use
  16848. * @returns a string containing the source code of the vertex shader associated with the program
  16849. */
  16850. Engine.prototype.getVertexShaderSource = function (program) {
  16851. var shaders = this._gl.getAttachedShaders(program);
  16852. if (!shaders) {
  16853. return null;
  16854. }
  16855. return this._gl.getShaderSource(shaders[0]);
  16856. };
  16857. /**
  16858. * Gets the source code of the fragment shader associated with a specific webGL program
  16859. * @param program defines the program to use
  16860. * @returns a string containing the source code of the fragment shader associated with the program
  16861. */
  16862. Engine.prototype.getFragmentShaderSource = function (program) {
  16863. var shaders = this._gl.getAttachedShaders(program);
  16864. if (!shaders) {
  16865. return null;
  16866. }
  16867. return this._gl.getShaderSource(shaders[1]);
  16868. };
  16869. /**
  16870. * Get the current error code of the webGL context
  16871. * @returns the error code
  16872. * @see https://developer.mozilla.org/en-US/docs/Web/API/WebGLRenderingContext/getError
  16873. */
  16874. Engine.prototype.getError = function () {
  16875. return this._gl.getError();
  16876. };
  16877. // FPS
  16878. /**
  16879. * Gets the current framerate
  16880. * @returns a number representing the framerate
  16881. */
  16882. Engine.prototype.getFps = function () {
  16883. return this._fps;
  16884. };
  16885. /**
  16886. * Gets the time spent between current and previous frame
  16887. * @returns a number representing the delta time in ms
  16888. */
  16889. Engine.prototype.getDeltaTime = function () {
  16890. return this._deltaTime;
  16891. };
  16892. Engine.prototype._measureFps = function () {
  16893. this._performanceMonitor.sampleFrame();
  16894. this._fps = this._performanceMonitor.averageFPS;
  16895. this._deltaTime = this._performanceMonitor.instantaneousFrameTime || 0;
  16896. };
  16897. /** @hidden */
  16898. Engine.prototype._readTexturePixels = function (texture, width, height, faceIndex) {
  16899. if (faceIndex === void 0) { faceIndex = -1; }
  16900. var gl = this._gl;
  16901. if (!this._dummyFramebuffer) {
  16902. var dummy = gl.createFramebuffer();
  16903. if (!dummy) {
  16904. throw new Error("Unable to create dummy framebuffer");
  16905. }
  16906. this._dummyFramebuffer = dummy;
  16907. }
  16908. gl.bindFramebuffer(gl.FRAMEBUFFER, this._dummyFramebuffer);
  16909. if (faceIndex > -1) {
  16910. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, texture._webGLTexture, 0);
  16911. }
  16912. else {
  16913. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, texture._webGLTexture, 0);
  16914. }
  16915. var readType = (texture.type !== undefined) ? this._getWebGLTextureType(texture.type) : gl.UNSIGNED_BYTE;
  16916. var buffer;
  16917. switch (readType) {
  16918. case gl.UNSIGNED_BYTE:
  16919. buffer = new Uint8Array(4 * width * height);
  16920. readType = gl.UNSIGNED_BYTE;
  16921. break;
  16922. default:
  16923. buffer = new Float32Array(4 * width * height);
  16924. readType = gl.FLOAT;
  16925. break;
  16926. }
  16927. gl.readPixels(0, 0, width, height, gl.RGBA, readType, buffer);
  16928. gl.bindFramebuffer(gl.FRAMEBUFFER, this._currentFramebuffer);
  16929. return buffer;
  16930. };
  16931. Engine.prototype._canRenderToFloatFramebuffer = function () {
  16932. if (this._webGLVersion > 1) {
  16933. return this._caps.colorBufferFloat;
  16934. }
  16935. return this._canRenderToFramebuffer(Engine.TEXTURETYPE_FLOAT);
  16936. };
  16937. Engine.prototype._canRenderToHalfFloatFramebuffer = function () {
  16938. if (this._webGLVersion > 1) {
  16939. return this._caps.colorBufferFloat;
  16940. }
  16941. return this._canRenderToFramebuffer(Engine.TEXTURETYPE_HALF_FLOAT);
  16942. };
  16943. // Thank you : http://stackoverflow.com/questions/28827511/webgl-ios-render-to-floating-point-texture
  16944. Engine.prototype._canRenderToFramebuffer = function (type) {
  16945. var gl = this._gl;
  16946. //clear existing errors
  16947. while (gl.getError() !== gl.NO_ERROR) { }
  16948. var successful = true;
  16949. var texture = gl.createTexture();
  16950. gl.bindTexture(gl.TEXTURE_2D, texture);
  16951. gl.texImage2D(gl.TEXTURE_2D, 0, this._getRGBABufferInternalSizedFormat(type), 1, 1, 0, gl.RGBA, this._getWebGLTextureType(type), null);
  16952. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
  16953. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
  16954. var fb = gl.createFramebuffer();
  16955. gl.bindFramebuffer(gl.FRAMEBUFFER, fb);
  16956. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, texture, 0);
  16957. var status = gl.checkFramebufferStatus(gl.FRAMEBUFFER);
  16958. successful = successful && (status === gl.FRAMEBUFFER_COMPLETE);
  16959. successful = successful && (gl.getError() === gl.NO_ERROR);
  16960. //try render by clearing frame buffer's color buffer
  16961. if (successful) {
  16962. gl.clear(gl.COLOR_BUFFER_BIT);
  16963. successful = successful && (gl.getError() === gl.NO_ERROR);
  16964. }
  16965. //try reading from frame to ensure render occurs (just creating the FBO is not sufficient to determine if rendering is supported)
  16966. if (successful) {
  16967. //in practice it's sufficient to just read from the backbuffer rather than handle potentially issues reading from the texture
  16968. gl.bindFramebuffer(gl.FRAMEBUFFER, null);
  16969. var readFormat = gl.RGBA;
  16970. var readType = gl.UNSIGNED_BYTE;
  16971. var buffer = new Uint8Array(4);
  16972. gl.readPixels(0, 0, 1, 1, readFormat, readType, buffer);
  16973. successful = successful && (gl.getError() === gl.NO_ERROR);
  16974. }
  16975. //clean up
  16976. gl.deleteTexture(texture);
  16977. gl.deleteFramebuffer(fb);
  16978. gl.bindFramebuffer(gl.FRAMEBUFFER, null);
  16979. //clear accumulated errors
  16980. while (!successful && (gl.getError() !== gl.NO_ERROR)) { }
  16981. return successful;
  16982. };
  16983. /** @hidden */
  16984. Engine.prototype._getWebGLTextureType = function (type) {
  16985. if (type === Engine.TEXTURETYPE_FLOAT) {
  16986. return this._gl.FLOAT;
  16987. }
  16988. else if (type === Engine.TEXTURETYPE_HALF_FLOAT) {
  16989. // Add Half Float Constant.
  16990. return this._gl.HALF_FLOAT_OES;
  16991. }
  16992. return this._gl.UNSIGNED_BYTE;
  16993. };
  16994. ;
  16995. Engine.prototype._getInternalFormat = function (format) {
  16996. var internalFormat = this._gl.RGBA;
  16997. switch (format) {
  16998. case Engine.TEXTUREFORMAT_ALPHA:
  16999. internalFormat = this._gl.ALPHA;
  17000. break;
  17001. case Engine.TEXTUREFORMAT_LUMINANCE:
  17002. internalFormat = this._gl.LUMINANCE;
  17003. break;
  17004. case Engine.TEXTUREFORMAT_LUMINANCE_ALPHA:
  17005. internalFormat = this._gl.LUMINANCE_ALPHA;
  17006. break;
  17007. case Engine.TEXTUREFORMAT_RGB:
  17008. case Engine.TEXTUREFORMAT_RGB32F:
  17009. internalFormat = this._gl.RGB;
  17010. break;
  17011. case Engine.TEXTUREFORMAT_RGBA:
  17012. case Engine.TEXTUREFORMAT_RGBA32F:
  17013. internalFormat = this._gl.RGBA;
  17014. break;
  17015. case Engine.TEXTUREFORMAT_R32F:
  17016. internalFormat = this._gl.RED;
  17017. break;
  17018. case Engine.TEXTUREFORMAT_RG32F:
  17019. internalFormat = this._gl.RG;
  17020. break;
  17021. }
  17022. return internalFormat;
  17023. };
  17024. /** @hidden */
  17025. Engine.prototype._getRGBABufferInternalSizedFormat = function (type, format) {
  17026. if (this._webGLVersion === 1) {
  17027. if (format) {
  17028. switch (format) {
  17029. case Engine.TEXTUREFORMAT_LUMINANCE:
  17030. return this._gl.LUMINANCE;
  17031. }
  17032. }
  17033. return this._gl.RGBA;
  17034. }
  17035. if (type === Engine.TEXTURETYPE_FLOAT) {
  17036. if (format) {
  17037. switch (format) {
  17038. case Engine.TEXTUREFORMAT_R32F:
  17039. return this._gl.R32F;
  17040. case Engine.TEXTUREFORMAT_RG32F:
  17041. return this._gl.RG32F;
  17042. case Engine.TEXTUREFORMAT_RGB32F:
  17043. return this._gl.RGB32F;
  17044. }
  17045. }
  17046. return this._gl.RGBA32F;
  17047. }
  17048. else if (type === Engine.TEXTURETYPE_HALF_FLOAT) {
  17049. return this._gl.RGBA16F;
  17050. }
  17051. if (format) {
  17052. switch (format) {
  17053. case Engine.TEXTUREFORMAT_LUMINANCE:
  17054. return this._gl.LUMINANCE;
  17055. case Engine.TEXTUREFORMAT_RGB:
  17056. return this._gl.RGB;
  17057. }
  17058. }
  17059. return this._gl.RGBA;
  17060. };
  17061. ;
  17062. /** @hidden */
  17063. Engine.prototype._getRGBAMultiSampleBufferFormat = function (type) {
  17064. if (type === Engine.TEXTURETYPE_FLOAT) {
  17065. return this._gl.RGBA32F;
  17066. }
  17067. else if (type === Engine.TEXTURETYPE_HALF_FLOAT) {
  17068. return this._gl.RGBA16F;
  17069. }
  17070. return this._gl.RGBA8;
  17071. };
  17072. ;
  17073. /**
  17074. * Create a new webGL query (you must be sure that queries are supported by checking getCaps() function)
  17075. * @return the new query
  17076. */
  17077. Engine.prototype.createQuery = function () {
  17078. return this._gl.createQuery();
  17079. };
  17080. /**
  17081. * Delete and release a webGL query
  17082. * @param query defines the query to delete
  17083. * @return the current engine
  17084. */
  17085. Engine.prototype.deleteQuery = function (query) {
  17086. this._gl.deleteQuery(query);
  17087. return this;
  17088. };
  17089. /**
  17090. * Check if a given query has resolved and got its value
  17091. * @param query defines the query to check
  17092. * @returns true if the query got its value
  17093. */
  17094. Engine.prototype.isQueryResultAvailable = function (query) {
  17095. return this._gl.getQueryParameter(query, this._gl.QUERY_RESULT_AVAILABLE);
  17096. };
  17097. /**
  17098. * Gets the value of a given query
  17099. * @param query defines the query to check
  17100. * @returns the value of the query
  17101. */
  17102. Engine.prototype.getQueryResult = function (query) {
  17103. return this._gl.getQueryParameter(query, this._gl.QUERY_RESULT);
  17104. };
  17105. /**
  17106. * Initiates an occlusion query
  17107. * @param algorithmType defines the algorithm to use
  17108. * @param query defines the query to use
  17109. * @returns the current engine
  17110. * @see http://doc.babylonjs.com/features/occlusionquery
  17111. */
  17112. Engine.prototype.beginOcclusionQuery = function (algorithmType, query) {
  17113. var glAlgorithm = this.getGlAlgorithmType(algorithmType);
  17114. this._gl.beginQuery(glAlgorithm, query);
  17115. return this;
  17116. };
  17117. /**
  17118. * Ends an occlusion query
  17119. * @see http://doc.babylonjs.com/features/occlusionquery
  17120. * @param algorithmType defines the algorithm to use
  17121. * @returns the current engine
  17122. */
  17123. Engine.prototype.endOcclusionQuery = function (algorithmType) {
  17124. var glAlgorithm = this.getGlAlgorithmType(algorithmType);
  17125. this._gl.endQuery(glAlgorithm);
  17126. return this;
  17127. };
  17128. /* Time queries */
  17129. Engine.prototype._createTimeQuery = function () {
  17130. var timerQuery = this._caps.timerQuery;
  17131. if (timerQuery.createQueryEXT) {
  17132. return timerQuery.createQueryEXT();
  17133. }
  17134. return this.createQuery();
  17135. };
  17136. Engine.prototype._deleteTimeQuery = function (query) {
  17137. var timerQuery = this._caps.timerQuery;
  17138. if (timerQuery.deleteQueryEXT) {
  17139. timerQuery.deleteQueryEXT(query);
  17140. return;
  17141. }
  17142. this.deleteQuery(query);
  17143. };
  17144. Engine.prototype._getTimeQueryResult = function (query) {
  17145. var timerQuery = this._caps.timerQuery;
  17146. if (timerQuery.getQueryObjectEXT) {
  17147. return timerQuery.getQueryObjectEXT(query, timerQuery.QUERY_RESULT_EXT);
  17148. }
  17149. return this.getQueryResult(query);
  17150. };
  17151. Engine.prototype._getTimeQueryAvailability = function (query) {
  17152. var timerQuery = this._caps.timerQuery;
  17153. if (timerQuery.getQueryObjectEXT) {
  17154. return timerQuery.getQueryObjectEXT(query, timerQuery.QUERY_RESULT_AVAILABLE_EXT);
  17155. }
  17156. return this.isQueryResultAvailable(query);
  17157. };
  17158. /**
  17159. * Starts a time query (used to measure time spent by the GPU on a specific frame)
  17160. * Please note that only one query can be issued at a time
  17161. * @returns a time token used to track the time span
  17162. */
  17163. Engine.prototype.startTimeQuery = function () {
  17164. var timerQuery = this._caps.timerQuery;
  17165. if (!timerQuery) {
  17166. return null;
  17167. }
  17168. var token = new BABYLON._TimeToken();
  17169. this._gl.getParameter(timerQuery.GPU_DISJOINT_EXT);
  17170. if (this._caps.canUseTimestampForTimerQuery) {
  17171. token._startTimeQuery = this._createTimeQuery();
  17172. timerQuery.queryCounterEXT(token._startTimeQuery, timerQuery.TIMESTAMP_EXT);
  17173. }
  17174. else {
  17175. if (this._currentNonTimestampToken) {
  17176. return this._currentNonTimestampToken;
  17177. }
  17178. token._timeElapsedQuery = this._createTimeQuery();
  17179. if (timerQuery.beginQueryEXT) {
  17180. timerQuery.beginQueryEXT(timerQuery.TIME_ELAPSED_EXT, token._timeElapsedQuery);
  17181. }
  17182. else {
  17183. this._gl.beginQuery(timerQuery.TIME_ELAPSED_EXT, token._timeElapsedQuery);
  17184. }
  17185. this._currentNonTimestampToken = token;
  17186. }
  17187. return token;
  17188. };
  17189. /**
  17190. * Ends a time query
  17191. * @param token defines the token used to measure the time span
  17192. * @returns the time spent (in ns)
  17193. */
  17194. Engine.prototype.endTimeQuery = function (token) {
  17195. var timerQuery = this._caps.timerQuery;
  17196. if (!timerQuery || !token) {
  17197. return -1;
  17198. }
  17199. if (this._caps.canUseTimestampForTimerQuery) {
  17200. if (!token._startTimeQuery) {
  17201. return -1;
  17202. }
  17203. if (!token._endTimeQuery) {
  17204. token._endTimeQuery = this._createTimeQuery();
  17205. timerQuery.queryCounterEXT(token._endTimeQuery, timerQuery.TIMESTAMP_EXT);
  17206. }
  17207. }
  17208. else if (!token._timeElapsedQueryEnded) {
  17209. if (!token._timeElapsedQuery) {
  17210. return -1;
  17211. }
  17212. if (timerQuery.endQueryEXT) {
  17213. timerQuery.endQueryEXT(timerQuery.TIME_ELAPSED_EXT);
  17214. }
  17215. else {
  17216. this._gl.endQuery(timerQuery.TIME_ELAPSED_EXT);
  17217. }
  17218. token._timeElapsedQueryEnded = true;
  17219. }
  17220. var disjoint = this._gl.getParameter(timerQuery.GPU_DISJOINT_EXT);
  17221. var available = false;
  17222. if (token._endTimeQuery) {
  17223. available = this._getTimeQueryAvailability(token._endTimeQuery);
  17224. }
  17225. else if (token._timeElapsedQuery) {
  17226. available = this._getTimeQueryAvailability(token._timeElapsedQuery);
  17227. }
  17228. if (available && !disjoint) {
  17229. var result = 0;
  17230. if (this._caps.canUseTimestampForTimerQuery) {
  17231. if (!token._startTimeQuery || !token._endTimeQuery) {
  17232. return -1;
  17233. }
  17234. var timeStart = this._getTimeQueryResult(token._startTimeQuery);
  17235. var timeEnd = this._getTimeQueryResult(token._endTimeQuery);
  17236. result = timeEnd - timeStart;
  17237. this._deleteTimeQuery(token._startTimeQuery);
  17238. this._deleteTimeQuery(token._endTimeQuery);
  17239. token._startTimeQuery = null;
  17240. token._endTimeQuery = null;
  17241. }
  17242. else {
  17243. if (!token._timeElapsedQuery) {
  17244. return -1;
  17245. }
  17246. result = this._getTimeQueryResult(token._timeElapsedQuery);
  17247. this._deleteTimeQuery(token._timeElapsedQuery);
  17248. token._timeElapsedQuery = null;
  17249. token._timeElapsedQueryEnded = false;
  17250. this._currentNonTimestampToken = null;
  17251. }
  17252. return result;
  17253. }
  17254. return -1;
  17255. };
  17256. Engine.prototype.getGlAlgorithmType = function (algorithmType) {
  17257. return algorithmType === BABYLON.AbstractMesh.OCCLUSION_ALGORITHM_TYPE_CONSERVATIVE ? this._gl.ANY_SAMPLES_PASSED_CONSERVATIVE : this._gl.ANY_SAMPLES_PASSED;
  17258. };
  17259. // Transform feedback
  17260. /**
  17261. * Creates a webGL transform feedback object
  17262. * Please makes sure to check webGLVersion property to check if you are running webGL 2+
  17263. * @returns the webGL transform feedback object
  17264. */
  17265. Engine.prototype.createTransformFeedback = function () {
  17266. return this._gl.createTransformFeedback();
  17267. };
  17268. /**
  17269. * Delete a webGL transform feedback object
  17270. * @param value defines the webGL transform feedback object to delete
  17271. */
  17272. Engine.prototype.deleteTransformFeedback = function (value) {
  17273. this._gl.deleteTransformFeedback(value);
  17274. };
  17275. /**
  17276. * Bind a webGL transform feedback object to the webgl context
  17277. * @param value defines the webGL transform feedback object to bind
  17278. */
  17279. Engine.prototype.bindTransformFeedback = function (value) {
  17280. this._gl.bindTransformFeedback(this._gl.TRANSFORM_FEEDBACK, value);
  17281. };
  17282. /**
  17283. * Begins a transform feedback operation
  17284. * @param usePoints defines if points or triangles must be used
  17285. */
  17286. Engine.prototype.beginTransformFeedback = function (usePoints) {
  17287. if (usePoints === void 0) { usePoints = true; }
  17288. this._gl.beginTransformFeedback(usePoints ? this._gl.POINTS : this._gl.TRIANGLES);
  17289. };
  17290. /**
  17291. * Ends a transform feedback operation
  17292. */
  17293. Engine.prototype.endTransformFeedback = function () {
  17294. this._gl.endTransformFeedback();
  17295. };
  17296. /**
  17297. * Specify the varyings to use with transform feedback
  17298. * @param program defines the associated webGL program
  17299. * @param value defines the list of strings representing the varying names
  17300. */
  17301. Engine.prototype.setTranformFeedbackVaryings = function (program, value) {
  17302. this._gl.transformFeedbackVaryings(program, value, this._gl.INTERLEAVED_ATTRIBS);
  17303. };
  17304. /**
  17305. * Bind a webGL buffer for a transform feedback operation
  17306. * @param value defines the webGL buffer to bind
  17307. */
  17308. Engine.prototype.bindTransformFeedbackBuffer = function (value) {
  17309. this._gl.bindBufferBase(this._gl.TRANSFORM_FEEDBACK_BUFFER, 0, value);
  17310. };
  17311. /** @hidden */
  17312. Engine.prototype._loadFile = function (url, onSuccess, onProgress, database, useArrayBuffer, onError) {
  17313. var _this = this;
  17314. var request = BABYLON.Tools.LoadFile(url, onSuccess, onProgress, database, useArrayBuffer, onError);
  17315. this._activeRequests.push(request);
  17316. request.onCompleteObservable.add(function (request) {
  17317. _this._activeRequests.splice(_this._activeRequests.indexOf(request), 1);
  17318. });
  17319. return request;
  17320. };
  17321. /** @hidden */
  17322. Engine.prototype._loadFileAsync = function (url, database, useArrayBuffer) {
  17323. var _this = this;
  17324. return new Promise(function (resolve, reject) {
  17325. _this._loadFile(url, function (data) {
  17326. resolve(data);
  17327. }, undefined, database, useArrayBuffer, function (request, exception) {
  17328. reject(exception);
  17329. });
  17330. });
  17331. };
  17332. Engine.prototype._partialLoadFile = function (url, index, loadedFiles, scene, onfinish, onErrorCallBack) {
  17333. if (onErrorCallBack === void 0) { onErrorCallBack = null; }
  17334. var onload = function (data) {
  17335. loadedFiles[index] = data;
  17336. loadedFiles._internalCount++;
  17337. if (loadedFiles._internalCount === 6) {
  17338. onfinish(loadedFiles);
  17339. }
  17340. };
  17341. var onerror = function (request, exception) {
  17342. if (onErrorCallBack && request) {
  17343. onErrorCallBack(request.status + " " + request.statusText, exception);
  17344. }
  17345. };
  17346. this._loadFile(url, onload, undefined, undefined, true, onerror);
  17347. };
  17348. Engine.prototype._cascadeLoadFiles = function (scene, onfinish, files, onError) {
  17349. if (onError === void 0) { onError = null; }
  17350. var loadedFiles = [];
  17351. loadedFiles._internalCount = 0;
  17352. for (var index = 0; index < 6; index++) {
  17353. this._partialLoadFile(files[index], index, loadedFiles, scene, onfinish, onError);
  17354. }
  17355. };
  17356. // Statics
  17357. /**
  17358. * Gets a boolean indicating if the engine can be instanciated (ie. if a webGL context can be found)
  17359. * @returns true if the engine can be created
  17360. * @ignorenaming
  17361. */
  17362. Engine.isSupported = function () {
  17363. try {
  17364. var tempcanvas = document.createElement("canvas");
  17365. var gl = tempcanvas.getContext("webgl") || tempcanvas.getContext("experimental-webgl");
  17366. return gl != null && !!window.WebGLRenderingContext;
  17367. }
  17368. catch (e) {
  17369. return false;
  17370. }
  17371. };
  17372. /** Use this array to turn off some WebGL2 features on known buggy browsers version */
  17373. Engine.ExceptionList = [
  17374. { key: "Chrome/63.0", capture: "63\\.0\\.3239\\.(\\d+)", captureConstraint: 108, targets: ["uniformBuffer"] },
  17375. { key: "Firefox/58", capture: null, captureConstraint: null, targets: ["uniformBuffer"] },
  17376. { key: "Firefox/59", capture: null, captureConstraint: null, targets: ["uniformBuffer"] },
  17377. { key: "Macintosh", capture: null, captureConstraint: null, targets: ["textureBindingOptimization"] },
  17378. { key: "iPhone", capture: null, captureConstraint: null, targets: ["textureBindingOptimization"] },
  17379. { key: "iPad", capture: null, captureConstraint: null, targets: ["textureBindingOptimization"] }
  17380. ];
  17381. /** Gets the list of created engines */
  17382. Engine.Instances = new Array();
  17383. // Const statics
  17384. Engine._ALPHA_DISABLE = 0;
  17385. Engine._ALPHA_ADD = 1;
  17386. Engine._ALPHA_COMBINE = 2;
  17387. Engine._ALPHA_SUBTRACT = 3;
  17388. Engine._ALPHA_MULTIPLY = 4;
  17389. Engine._ALPHA_MAXIMIZED = 5;
  17390. Engine._ALPHA_ONEONE = 6;
  17391. Engine._ALPHA_PREMULTIPLIED = 7;
  17392. Engine._ALPHA_PREMULTIPLIED_PORTERDUFF = 8;
  17393. Engine._ALPHA_INTERPOLATE = 9;
  17394. Engine._ALPHA_SCREENMODE = 10;
  17395. Engine._DELAYLOADSTATE_NONE = 0;
  17396. Engine._DELAYLOADSTATE_LOADED = 1;
  17397. Engine._DELAYLOADSTATE_LOADING = 2;
  17398. Engine._DELAYLOADSTATE_NOTLOADED = 4;
  17399. Engine._TEXTUREFORMAT_ALPHA = 0;
  17400. Engine._TEXTUREFORMAT_LUMINANCE = 1;
  17401. Engine._TEXTUREFORMAT_LUMINANCE_ALPHA = 2;
  17402. Engine._TEXTUREFORMAT_RGB = 4;
  17403. Engine._TEXTUREFORMAT_RGBA = 5;
  17404. Engine._TEXTUREFORMAT_R32F = 6;
  17405. Engine._TEXTUREFORMAT_RG32F = 7;
  17406. Engine._TEXTUREFORMAT_RGB32F = 8;
  17407. Engine._TEXTUREFORMAT_RGBA32F = 9;
  17408. Engine._TEXTURETYPE_UNSIGNED_INT = 0;
  17409. Engine._TEXTURETYPE_FLOAT = 1;
  17410. Engine._TEXTURETYPE_HALF_FLOAT = 2;
  17411. // Depht or Stencil test Constants.
  17412. Engine._NEVER = 0x0200; // Passed to depthFunction or stencilFunction to specify depth or stencil tests will never pass. i.e. Nothing will be drawn.
  17413. 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.
  17414. 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.
  17415. 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.
  17416. 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.
  17417. 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.
  17418. 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.
  17419. 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.
  17420. // Stencil Actions Constants.
  17421. Engine._KEEP = 0x1E00;
  17422. Engine._REPLACE = 0x1E01;
  17423. Engine._INCR = 0x1E02;
  17424. Engine._DECR = 0x1E03;
  17425. Engine._INVERT = 0x150A;
  17426. Engine._INCR_WRAP = 0x8507;
  17427. Engine._DECR_WRAP = 0x8508;
  17428. // Texture rescaling mode
  17429. Engine._SCALEMODE_FLOOR = 1;
  17430. Engine._SCALEMODE_NEAREST = 2;
  17431. Engine._SCALEMODE_CEILING = 3;
  17432. // Updatable statics so stick with vars here
  17433. /**
  17434. * Gets or sets the epsilon value used by collision engine
  17435. */
  17436. Engine.CollisionsEpsilon = 0.001;
  17437. /**
  17438. * Gets or sets the relative url used to load code if using the engine in non-minified mode
  17439. */
  17440. Engine.CodeRepository = "src/";
  17441. /**
  17442. * Gets or sets the relative url used to load shaders if using the engine in non-minified mode
  17443. */
  17444. Engine.ShadersRepository = "src/Shaders/";
  17445. return Engine;
  17446. }());
  17447. BABYLON.Engine = Engine;
  17448. })(BABYLON || (BABYLON = {}));
  17449. //# sourceMappingURL=babylon.engine.js.map
  17450. var BABYLON;
  17451. (function (BABYLON) {
  17452. /**
  17453. * Node is the basic class for all scene objects (Mesh, Light Camera).
  17454. */
  17455. var Node = /** @class */ (function () {
  17456. /**
  17457. * Creates a new Node
  17458. * @param {string} name - the name and id to be given to this node
  17459. * @param {BABYLON.Scene} the scene this node will be added to
  17460. */
  17461. function Node(name, scene) {
  17462. if (scene === void 0) { scene = null; }
  17463. /**
  17464. * Gets or sets a string used to store user defined state for the node
  17465. */
  17466. this.state = "";
  17467. /**
  17468. * Gets or sets an object used to store user defined information for the node
  17469. */
  17470. this.metadata = null;
  17471. /**
  17472. * Gets or sets a boolean used to define if the node must be serialized
  17473. */
  17474. this.doNotSerialize = false;
  17475. /** @hidden */
  17476. this._isDisposed = false;
  17477. /**
  17478. * Gets a list of Animations associated with the node
  17479. */
  17480. this.animations = new Array();
  17481. this._ranges = {};
  17482. this._isEnabled = true;
  17483. this._isReady = true;
  17484. /** @hidden */
  17485. this._currentRenderId = -1;
  17486. this._parentRenderId = -1;
  17487. this._childRenderId = -1;
  17488. this._animationPropertiesOverride = null;
  17489. /**
  17490. * An event triggered when the mesh is disposed
  17491. */
  17492. this.onDisposeObservable = new BABYLON.Observable();
  17493. // Behaviors
  17494. this._behaviors = new Array();
  17495. this.name = name;
  17496. this.id = name;
  17497. this._scene = (scene || BABYLON.Engine.LastCreatedScene);
  17498. this.uniqueId = this._scene.getUniqueId();
  17499. this._initCache();
  17500. }
  17501. /**
  17502. * Gets a boolean indicating if the node has been disposed
  17503. * @returns true if the node was disposed
  17504. */
  17505. Node.prototype.isDisposed = function () {
  17506. return this._isDisposed;
  17507. };
  17508. Object.defineProperty(Node.prototype, "parent", {
  17509. get: function () {
  17510. return this._parentNode;
  17511. },
  17512. /**
  17513. * Gets or sets the parent of the node
  17514. */
  17515. set: function (parent) {
  17516. if (this._parentNode === parent) {
  17517. return;
  17518. }
  17519. // Remove self from list of children of parent
  17520. if (this._parentNode && this._parentNode._children !== undefined && this._parentNode._children !== null) {
  17521. var index = this._parentNode._children.indexOf(this);
  17522. if (index !== -1) {
  17523. this._parentNode._children.splice(index, 1);
  17524. }
  17525. }
  17526. // Store new parent
  17527. this._parentNode = parent;
  17528. // Add as child to new parent
  17529. if (this._parentNode) {
  17530. if (this._parentNode._children === undefined || this._parentNode._children === null) {
  17531. this._parentNode._children = new Array();
  17532. }
  17533. this._parentNode._children.push(this);
  17534. }
  17535. },
  17536. enumerable: true,
  17537. configurable: true
  17538. });
  17539. Object.defineProperty(Node.prototype, "animationPropertiesOverride", {
  17540. /**
  17541. * Gets or sets the animation properties override
  17542. */
  17543. get: function () {
  17544. if (!this._animationPropertiesOverride) {
  17545. return this._scene.animationPropertiesOverride;
  17546. }
  17547. return this._animationPropertiesOverride;
  17548. },
  17549. set: function (value) {
  17550. this._animationPropertiesOverride = value;
  17551. },
  17552. enumerable: true,
  17553. configurable: true
  17554. });
  17555. /**
  17556. * Gets a string idenfifying the name of the class
  17557. * @returns "Node" string
  17558. */
  17559. Node.prototype.getClassName = function () {
  17560. return "Node";
  17561. };
  17562. Object.defineProperty(Node.prototype, "onDispose", {
  17563. /**
  17564. * Sets a callback that will be raised when the node will be disposed
  17565. */
  17566. set: function (callback) {
  17567. if (this._onDisposeObserver) {
  17568. this.onDisposeObservable.remove(this._onDisposeObserver);
  17569. }
  17570. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  17571. },
  17572. enumerable: true,
  17573. configurable: true
  17574. });
  17575. /**
  17576. * Gets the scene of the node
  17577. * @returns a {BABYLON.Scene}
  17578. */
  17579. Node.prototype.getScene = function () {
  17580. return this._scene;
  17581. };
  17582. /**
  17583. * Gets the engine of the node
  17584. * @returns a {BABYLON.Engine}
  17585. */
  17586. Node.prototype.getEngine = function () {
  17587. return this._scene.getEngine();
  17588. };
  17589. /**
  17590. * Attach a behavior to the node
  17591. * @see http://doc.babylonjs.com/features/behaviour
  17592. * @param behavior defines the behavior to attach
  17593. * @returns the current Node
  17594. */
  17595. Node.prototype.addBehavior = function (behavior) {
  17596. var _this = this;
  17597. var index = this._behaviors.indexOf(behavior);
  17598. if (index !== -1) {
  17599. return this;
  17600. }
  17601. behavior.init();
  17602. if (this._scene.isLoading) {
  17603. // We defer the attach when the scene will be loaded
  17604. var observer = this._scene.onDataLoadedObservable.add(function () {
  17605. behavior.attach(_this);
  17606. setTimeout(function () {
  17607. // Need to use a timeout to avoid removing an observer while iterating the list of observers
  17608. _this._scene.onDataLoadedObservable.remove(observer);
  17609. }, 0);
  17610. });
  17611. }
  17612. else {
  17613. behavior.attach(this);
  17614. }
  17615. this._behaviors.push(behavior);
  17616. return this;
  17617. };
  17618. /**
  17619. * Remove an attached behavior
  17620. * @see http://doc.babylonjs.com/features/behaviour
  17621. * @param behavior defines the behavior to attach
  17622. * @returns the current Node
  17623. */
  17624. Node.prototype.removeBehavior = function (behavior) {
  17625. var index = this._behaviors.indexOf(behavior);
  17626. if (index === -1) {
  17627. return this;
  17628. }
  17629. this._behaviors[index].detach();
  17630. this._behaviors.splice(index, 1);
  17631. return this;
  17632. };
  17633. Object.defineProperty(Node.prototype, "behaviors", {
  17634. /**
  17635. * Gets the list of attached behaviors
  17636. * @see http://doc.babylonjs.com/features/behaviour
  17637. */
  17638. get: function () {
  17639. return this._behaviors;
  17640. },
  17641. enumerable: true,
  17642. configurable: true
  17643. });
  17644. /**
  17645. * Gets an attached behavior by name
  17646. * @param name defines the name of the behavior to look for
  17647. * @see http://doc.babylonjs.com/features/behaviour
  17648. * @returns null if behavior was not found else the requested behavior
  17649. */
  17650. Node.prototype.getBehaviorByName = function (name) {
  17651. for (var _i = 0, _a = this._behaviors; _i < _a.length; _i++) {
  17652. var behavior = _a[_i];
  17653. if (behavior.name === name) {
  17654. return behavior;
  17655. }
  17656. }
  17657. return null;
  17658. };
  17659. /**
  17660. * Returns the world matrix of the node
  17661. * @returns a matrix containing the node's world matrix
  17662. */
  17663. Node.prototype.getWorldMatrix = function () {
  17664. return BABYLON.Matrix.Identity();
  17665. };
  17666. /** @hidden */
  17667. Node.prototype._getWorldMatrixDeterminant = function () {
  17668. return 1;
  17669. };
  17670. // override it in derived class if you add new variables to the cache
  17671. // and call the parent class method
  17672. /** @hidden */
  17673. Node.prototype._initCache = function () {
  17674. this._cache = {};
  17675. this._cache.parent = undefined;
  17676. };
  17677. /** @hidden */
  17678. Node.prototype.updateCache = function (force) {
  17679. if (!force && this.isSynchronized())
  17680. return;
  17681. this._cache.parent = this.parent;
  17682. this._updateCache();
  17683. };
  17684. // override it in derived class if you add new variables to the cache
  17685. // and call the parent class method if !ignoreParentClass
  17686. /** @hidden */
  17687. Node.prototype._updateCache = function (ignoreParentClass) {
  17688. };
  17689. // override it in derived class if you add new variables to the cache
  17690. /** @hidden */
  17691. Node.prototype._isSynchronized = function () {
  17692. return true;
  17693. };
  17694. /** @hidden */
  17695. Node.prototype._markSyncedWithParent = function () {
  17696. if (this.parent) {
  17697. this._parentRenderId = this.parent._childRenderId;
  17698. }
  17699. };
  17700. /** @hidden */
  17701. Node.prototype.isSynchronizedWithParent = function () {
  17702. if (!this.parent) {
  17703. return true;
  17704. }
  17705. if (this._parentRenderId !== this.parent._childRenderId) {
  17706. return false;
  17707. }
  17708. return this.parent.isSynchronized();
  17709. };
  17710. /** @hidden */
  17711. Node.prototype.isSynchronized = function (updateCache) {
  17712. var check = this.hasNewParent();
  17713. check = check || !this.isSynchronizedWithParent();
  17714. check = check || !this._isSynchronized();
  17715. if (updateCache)
  17716. this.updateCache(true);
  17717. return !check;
  17718. };
  17719. /** @hidden */
  17720. Node.prototype.hasNewParent = function (update) {
  17721. if (this._cache.parent === this.parent)
  17722. return false;
  17723. if (update)
  17724. this._cache.parent = this.parent;
  17725. return true;
  17726. };
  17727. /**
  17728. * Is this node ready to be used/rendered
  17729. * @param completeCheck defines if a complete check (including materials and lights) has to be done (false by default)
  17730. * @return true if the node is ready
  17731. */
  17732. Node.prototype.isReady = function (completeCheck) {
  17733. if (completeCheck === void 0) { completeCheck = false; }
  17734. return this._isReady;
  17735. };
  17736. /**
  17737. * Is this node enabled?
  17738. * 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
  17739. * @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
  17740. * @return whether this node (and its parent) is enabled
  17741. */
  17742. Node.prototype.isEnabled = function (checkAncestors) {
  17743. if (checkAncestors === void 0) { checkAncestors = true; }
  17744. if (checkAncestors === false) {
  17745. return this._isEnabled;
  17746. }
  17747. if (this._isEnabled === false) {
  17748. return false;
  17749. }
  17750. if (this.parent !== undefined && this.parent !== null) {
  17751. return this.parent.isEnabled(checkAncestors);
  17752. }
  17753. return true;
  17754. };
  17755. /**
  17756. * Set the enabled state of this node
  17757. * @param value defines the new enabled state
  17758. */
  17759. Node.prototype.setEnabled = function (value) {
  17760. this._isEnabled = value;
  17761. };
  17762. /**
  17763. * Is this node a descendant of the given node?
  17764. * The function will iterate up the hierarchy until the ancestor was found or no more parents defined
  17765. * @param ancestor defines the parent node to inspect
  17766. * @returns a boolean indicating if this node is a descendant of the given node
  17767. */
  17768. Node.prototype.isDescendantOf = function (ancestor) {
  17769. if (this.parent) {
  17770. if (this.parent === ancestor) {
  17771. return true;
  17772. }
  17773. return this.parent.isDescendantOf(ancestor);
  17774. }
  17775. return false;
  17776. };
  17777. /** @hidden */
  17778. Node.prototype._getDescendants = function (results, directDescendantsOnly, predicate) {
  17779. if (directDescendantsOnly === void 0) { directDescendantsOnly = false; }
  17780. if (!this._children) {
  17781. return;
  17782. }
  17783. for (var index = 0; index < this._children.length; index++) {
  17784. var item = this._children[index];
  17785. if (!predicate || predicate(item)) {
  17786. results.push(item);
  17787. }
  17788. if (!directDescendantsOnly) {
  17789. item._getDescendants(results, false, predicate);
  17790. }
  17791. }
  17792. };
  17793. /**
  17794. * Will return all nodes that have this node as ascendant
  17795. * @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
  17796. * @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
  17797. * @return all children nodes of all types
  17798. */
  17799. Node.prototype.getDescendants = function (directDescendantsOnly, predicate) {
  17800. var results = new Array();
  17801. this._getDescendants(results, directDescendantsOnly, predicate);
  17802. return results;
  17803. };
  17804. /**
  17805. * Get all child-meshes of this node
  17806. * @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
  17807. * @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
  17808. * @returns an array of {BABYLON.AbstractMesh}
  17809. */
  17810. Node.prototype.getChildMeshes = function (directDescendantsOnly, predicate) {
  17811. var results = [];
  17812. this._getDescendants(results, directDescendantsOnly, function (node) {
  17813. return ((!predicate || predicate(node)) && (node instanceof BABYLON.AbstractMesh));
  17814. });
  17815. return results;
  17816. };
  17817. /**
  17818. * Get all child-transformNodes of this node
  17819. * @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
  17820. * @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
  17821. * @returns an array of {BABYLON.TransformNode}
  17822. */
  17823. Node.prototype.getChildTransformNodes = function (directDescendantsOnly, predicate) {
  17824. var results = [];
  17825. this._getDescendants(results, directDescendantsOnly, function (node) {
  17826. return ((!predicate || predicate(node)) && (node instanceof BABYLON.TransformNode));
  17827. });
  17828. return results;
  17829. };
  17830. /**
  17831. * Get all direct children of this node
  17832. * @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
  17833. * @returns an array of {BABYLON.Node}
  17834. */
  17835. Node.prototype.getChildren = function (predicate) {
  17836. return this.getDescendants(true, predicate);
  17837. };
  17838. /** @hidden */
  17839. Node.prototype._setReady = function (state) {
  17840. if (state === this._isReady) {
  17841. return;
  17842. }
  17843. if (!state) {
  17844. this._isReady = false;
  17845. return;
  17846. }
  17847. if (this.onReady) {
  17848. this.onReady(this);
  17849. }
  17850. this._isReady = true;
  17851. };
  17852. /**
  17853. * Get an animation by name
  17854. * @param name defines the name of the animation to look for
  17855. * @returns null if not found else the requested animation
  17856. */
  17857. Node.prototype.getAnimationByName = function (name) {
  17858. for (var i = 0; i < this.animations.length; i++) {
  17859. var animation = this.animations[i];
  17860. if (animation.name === name) {
  17861. return animation;
  17862. }
  17863. }
  17864. return null;
  17865. };
  17866. /**
  17867. * Creates an animation range for this node
  17868. * @param name defines the name of the range
  17869. * @param from defines the starting key
  17870. * @param to defines the end key
  17871. */
  17872. Node.prototype.createAnimationRange = function (name, from, to) {
  17873. // check name not already in use
  17874. if (!this._ranges[name]) {
  17875. this._ranges[name] = new BABYLON.AnimationRange(name, from, to);
  17876. for (var i = 0, nAnimations = this.animations.length; i < nAnimations; i++) {
  17877. if (this.animations[i]) {
  17878. this.animations[i].createRange(name, from, to);
  17879. }
  17880. }
  17881. }
  17882. };
  17883. /**
  17884. * Delete a specific animation range
  17885. * @param name defines the name of the range to delete
  17886. * @param deleteFrames defines if animation frames from the range must be deleted as well
  17887. */
  17888. Node.prototype.deleteAnimationRange = function (name, deleteFrames) {
  17889. if (deleteFrames === void 0) { deleteFrames = true; }
  17890. for (var i = 0, nAnimations = this.animations.length; i < nAnimations; i++) {
  17891. if (this.animations[i]) {
  17892. this.animations[i].deleteRange(name, deleteFrames);
  17893. }
  17894. }
  17895. this._ranges[name] = null; // said much faster than 'delete this._range[name]'
  17896. };
  17897. /**
  17898. * Get an animation range by name
  17899. * @param name defines the name of the animation range to look for
  17900. * @returns null if not found else the requested animation range
  17901. */
  17902. Node.prototype.getAnimationRange = function (name) {
  17903. return this._ranges[name];
  17904. };
  17905. /**
  17906. * Will start the animation sequence
  17907. * @param name defines the range frames for animation sequence
  17908. * @param loop defines if the animation should loop (false by default)
  17909. * @param speedRatio defines the speed factor in which to run the animation (1 by default)
  17910. * @param onAnimationEnd defines a function to be executed when the animation ended (undefined by default)
  17911. * @returns the object created for this animation. If range does not exist, it will return null
  17912. */
  17913. Node.prototype.beginAnimation = function (name, loop, speedRatio, onAnimationEnd) {
  17914. var range = this.getAnimationRange(name);
  17915. if (!range) {
  17916. return null;
  17917. }
  17918. return this._scene.beginAnimation(this, range.from, range.to, loop, speedRatio, onAnimationEnd);
  17919. };
  17920. /**
  17921. * Serialize animation ranges into a JSON compatible object
  17922. * @returns serialization object
  17923. */
  17924. Node.prototype.serializeAnimationRanges = function () {
  17925. var serializationRanges = [];
  17926. for (var name in this._ranges) {
  17927. var localRange = this._ranges[name];
  17928. if (!localRange) {
  17929. continue;
  17930. }
  17931. var range = {};
  17932. range.name = name;
  17933. range.from = localRange.from;
  17934. range.to = localRange.to;
  17935. serializationRanges.push(range);
  17936. }
  17937. return serializationRanges;
  17938. };
  17939. /**
  17940. * Computes the world matrix of the node
  17941. * @param force defines if the cache version should be invalidated forcing the world matrix to be created from scratch
  17942. * @returns the world matrix
  17943. */
  17944. Node.prototype.computeWorldMatrix = function (force) {
  17945. return BABYLON.Matrix.Identity();
  17946. };
  17947. /**
  17948. * Releases resources associated with this node.
  17949. * @param doNotRecurse Set to true to not recurse into each children (recurse into each children by default)
  17950. * @param disposeMaterialAndTextures Set to true to also dispose referenced materials and textures (false by default)
  17951. */
  17952. Node.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  17953. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  17954. if (!doNotRecurse) {
  17955. var nodes = this.getDescendants(true);
  17956. for (var _i = 0, nodes_1 = nodes; _i < nodes_1.length; _i++) {
  17957. var node = nodes_1[_i];
  17958. node.dispose(doNotRecurse, disposeMaterialAndTextures);
  17959. }
  17960. }
  17961. else {
  17962. var transformNodes = this.getChildTransformNodes(true);
  17963. for (var _a = 0, transformNodes_1 = transformNodes; _a < transformNodes_1.length; _a++) {
  17964. var transformNode = transformNodes_1[_a];
  17965. transformNode.parent = null;
  17966. transformNode.computeWorldMatrix(true);
  17967. }
  17968. }
  17969. this.parent = null;
  17970. // Callback
  17971. this.onDisposeObservable.notifyObservers(this);
  17972. this.onDisposeObservable.clear();
  17973. // Behaviors
  17974. for (var _b = 0, _c = this._behaviors; _b < _c.length; _b++) {
  17975. var behavior = _c[_b];
  17976. behavior.detach();
  17977. }
  17978. this._behaviors = [];
  17979. this._isDisposed = true;
  17980. };
  17981. /**
  17982. * Parse animation range data from a serialization object and store them into a given node
  17983. * @param node defines where to store the animation ranges
  17984. * @param parsedNode defines the serialization object to read data from
  17985. * @param scene defines the hosting scene
  17986. */
  17987. Node.ParseAnimationRanges = function (node, parsedNode, scene) {
  17988. if (parsedNode.ranges) {
  17989. for (var index = 0; index < parsedNode.ranges.length; index++) {
  17990. var data = parsedNode.ranges[index];
  17991. node.createAnimationRange(data.name, data.from, data.to);
  17992. }
  17993. }
  17994. };
  17995. __decorate([
  17996. BABYLON.serialize()
  17997. ], Node.prototype, "name", void 0);
  17998. __decorate([
  17999. BABYLON.serialize()
  18000. ], Node.prototype, "id", void 0);
  18001. __decorate([
  18002. BABYLON.serialize()
  18003. ], Node.prototype, "uniqueId", void 0);
  18004. __decorate([
  18005. BABYLON.serialize()
  18006. ], Node.prototype, "state", void 0);
  18007. __decorate([
  18008. BABYLON.serialize()
  18009. ], Node.prototype, "metadata", void 0);
  18010. return Node;
  18011. }());
  18012. BABYLON.Node = Node;
  18013. })(BABYLON || (BABYLON = {}));
  18014. //# sourceMappingURL=babylon.node.js.map
  18015. var BABYLON;
  18016. (function (BABYLON) {
  18017. var BoundingSphere = /** @class */ (function () {
  18018. /**
  18019. * Creates a new bounding sphere
  18020. * @param min defines the minimum vector (in local space)
  18021. * @param max defines the maximum vector (in local space)
  18022. */
  18023. function BoundingSphere(min, max) {
  18024. this._tempRadiusVector = BABYLON.Vector3.Zero();
  18025. this.reConstruct(min, max);
  18026. }
  18027. /**
  18028. * Recreates the entire bounding sphere from scratch
  18029. * @param min defines the new minimum vector (in local space)
  18030. * @param max defines the new maximum vector (in local space)
  18031. */
  18032. BoundingSphere.prototype.reConstruct = function (min, max) {
  18033. this.minimum = min.clone();
  18034. this.maximum = max.clone();
  18035. var distance = BABYLON.Vector3.Distance(min, max);
  18036. this.center = BABYLON.Vector3.Lerp(min, max, 0.5);
  18037. this.radius = distance * 0.5;
  18038. this.centerWorld = BABYLON.Vector3.Zero();
  18039. this._update(BABYLON.Matrix.Identity());
  18040. };
  18041. // Methods
  18042. BoundingSphere.prototype._update = function (world) {
  18043. BABYLON.Vector3.TransformCoordinatesToRef(this.center, world, this.centerWorld);
  18044. BABYLON.Vector3.TransformNormalFromFloatsToRef(1.0, 1.0, 1.0, world, this._tempRadiusVector);
  18045. this.radiusWorld = Math.max(Math.abs(this._tempRadiusVector.x), Math.abs(this._tempRadiusVector.y), Math.abs(this._tempRadiusVector.z)) * this.radius;
  18046. };
  18047. BoundingSphere.prototype.isInFrustum = function (frustumPlanes) {
  18048. for (var i = 0; i < 6; i++) {
  18049. if (frustumPlanes[i].dotCoordinate(this.centerWorld) <= -this.radiusWorld)
  18050. return false;
  18051. }
  18052. return true;
  18053. };
  18054. BoundingSphere.prototype.intersectsPoint = function (point) {
  18055. var x = this.centerWorld.x - point.x;
  18056. var y = this.centerWorld.y - point.y;
  18057. var z = this.centerWorld.z - point.z;
  18058. var distance = Math.sqrt((x * x) + (y * y) + (z * z));
  18059. if (Math.abs(this.radiusWorld - distance) < BABYLON.Epsilon)
  18060. return false;
  18061. return true;
  18062. };
  18063. // Statics
  18064. BoundingSphere.Intersects = function (sphere0, sphere1) {
  18065. var x = sphere0.centerWorld.x - sphere1.centerWorld.x;
  18066. var y = sphere0.centerWorld.y - sphere1.centerWorld.y;
  18067. var z = sphere0.centerWorld.z - sphere1.centerWorld.z;
  18068. var distance = Math.sqrt((x * x) + (y * y) + (z * z));
  18069. if (sphere0.radiusWorld + sphere1.radiusWorld < distance)
  18070. return false;
  18071. return true;
  18072. };
  18073. return BoundingSphere;
  18074. }());
  18075. BABYLON.BoundingSphere = BoundingSphere;
  18076. })(BABYLON || (BABYLON = {}));
  18077. //# sourceMappingURL=babylon.boundingSphere.js.map
  18078. var BABYLON;
  18079. (function (BABYLON) {
  18080. var BoundingBox = /** @class */ (function () {
  18081. /**
  18082. * Creates a new bounding box
  18083. * @param min defines the minimum vector (in local space)
  18084. * @param max defines the maximum vector (in local space)
  18085. */
  18086. function BoundingBox(min, max) {
  18087. this.vectorsWorld = new Array();
  18088. this.reConstruct(min, max);
  18089. }
  18090. // Methods
  18091. /**
  18092. * Recreates the entire bounding box from scratch
  18093. * @param min defines the new minimum vector (in local space)
  18094. * @param max defines the new maximum vector (in local space)
  18095. */
  18096. BoundingBox.prototype.reConstruct = function (min, max) {
  18097. this.minimum = min.clone();
  18098. this.maximum = max.clone();
  18099. // Bounding vectors
  18100. this.vectors = new Array();
  18101. this.vectors.push(this.minimum.clone());
  18102. this.vectors.push(this.maximum.clone());
  18103. this.vectors.push(this.minimum.clone());
  18104. this.vectors[2].x = this.maximum.x;
  18105. this.vectors.push(this.minimum.clone());
  18106. this.vectors[3].y = this.maximum.y;
  18107. this.vectors.push(this.minimum.clone());
  18108. this.vectors[4].z = this.maximum.z;
  18109. this.vectors.push(this.maximum.clone());
  18110. this.vectors[5].z = this.minimum.z;
  18111. this.vectors.push(this.maximum.clone());
  18112. this.vectors[6].x = this.minimum.x;
  18113. this.vectors.push(this.maximum.clone());
  18114. this.vectors[7].y = this.minimum.y;
  18115. // OBB
  18116. this.center = this.maximum.add(this.minimum).scale(0.5);
  18117. this.extendSize = this.maximum.subtract(this.minimum).scale(0.5);
  18118. this.directions = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  18119. // World
  18120. for (var index = 0; index < this.vectors.length; index++) {
  18121. this.vectorsWorld[index] = BABYLON.Vector3.Zero();
  18122. }
  18123. this.minimumWorld = BABYLON.Vector3.Zero();
  18124. this.maximumWorld = BABYLON.Vector3.Zero();
  18125. this.centerWorld = BABYLON.Vector3.Zero();
  18126. this.extendSizeWorld = BABYLON.Vector3.Zero();
  18127. this._update(this._worldMatrix || BABYLON.Matrix.Identity());
  18128. };
  18129. BoundingBox.prototype.getWorldMatrix = function () {
  18130. return this._worldMatrix;
  18131. };
  18132. BoundingBox.prototype.setWorldMatrix = function (matrix) {
  18133. this._worldMatrix.copyFrom(matrix);
  18134. return this;
  18135. };
  18136. BoundingBox.prototype._update = function (world) {
  18137. BABYLON.Vector3.FromFloatsToRef(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, this.minimumWorld);
  18138. BABYLON.Vector3.FromFloatsToRef(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE, this.maximumWorld);
  18139. for (var index = 0; index < this.vectors.length; index++) {
  18140. var v = this.vectorsWorld[index];
  18141. BABYLON.Vector3.TransformCoordinatesToRef(this.vectors[index], world, v);
  18142. if (v.x < this.minimumWorld.x)
  18143. this.minimumWorld.x = v.x;
  18144. if (v.y < this.minimumWorld.y)
  18145. this.minimumWorld.y = v.y;
  18146. if (v.z < this.minimumWorld.z)
  18147. this.minimumWorld.z = v.z;
  18148. if (v.x > this.maximumWorld.x)
  18149. this.maximumWorld.x = v.x;
  18150. if (v.y > this.maximumWorld.y)
  18151. this.maximumWorld.y = v.y;
  18152. if (v.z > this.maximumWorld.z)
  18153. this.maximumWorld.z = v.z;
  18154. }
  18155. // Extend
  18156. this.maximumWorld.subtractToRef(this.minimumWorld, this.extendSizeWorld);
  18157. this.extendSizeWorld.scaleInPlace(0.5);
  18158. // OBB
  18159. this.maximumWorld.addToRef(this.minimumWorld, this.centerWorld);
  18160. this.centerWorld.scaleInPlace(0.5);
  18161. BABYLON.Vector3.FromFloatArrayToRef(world.m, 0, this.directions[0]);
  18162. BABYLON.Vector3.FromFloatArrayToRef(world.m, 4, this.directions[1]);
  18163. BABYLON.Vector3.FromFloatArrayToRef(world.m, 8, this.directions[2]);
  18164. this._worldMatrix = world;
  18165. };
  18166. BoundingBox.prototype.isInFrustum = function (frustumPlanes) {
  18167. return BoundingBox.IsInFrustum(this.vectorsWorld, frustumPlanes);
  18168. };
  18169. BoundingBox.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  18170. return BoundingBox.IsCompletelyInFrustum(this.vectorsWorld, frustumPlanes);
  18171. };
  18172. BoundingBox.prototype.intersectsPoint = function (point) {
  18173. var delta = -BABYLON.Epsilon;
  18174. if (this.maximumWorld.x - point.x < delta || delta > point.x - this.minimumWorld.x)
  18175. return false;
  18176. if (this.maximumWorld.y - point.y < delta || delta > point.y - this.minimumWorld.y)
  18177. return false;
  18178. if (this.maximumWorld.z - point.z < delta || delta > point.z - this.minimumWorld.z)
  18179. return false;
  18180. return true;
  18181. };
  18182. BoundingBox.prototype.intersectsSphere = function (sphere) {
  18183. return BoundingBox.IntersectsSphere(this.minimumWorld, this.maximumWorld, sphere.centerWorld, sphere.radiusWorld);
  18184. };
  18185. BoundingBox.prototype.intersectsMinMax = function (min, max) {
  18186. if (this.maximumWorld.x < min.x || this.minimumWorld.x > max.x)
  18187. return false;
  18188. if (this.maximumWorld.y < min.y || this.minimumWorld.y > max.y)
  18189. return false;
  18190. if (this.maximumWorld.z < min.z || this.minimumWorld.z > max.z)
  18191. return false;
  18192. return true;
  18193. };
  18194. // Statics
  18195. BoundingBox.Intersects = function (box0, box1) {
  18196. if (box0.maximumWorld.x < box1.minimumWorld.x || box0.minimumWorld.x > box1.maximumWorld.x)
  18197. return false;
  18198. if (box0.maximumWorld.y < box1.minimumWorld.y || box0.minimumWorld.y > box1.maximumWorld.y)
  18199. return false;
  18200. if (box0.maximumWorld.z < box1.minimumWorld.z || box0.minimumWorld.z > box1.maximumWorld.z)
  18201. return false;
  18202. return true;
  18203. };
  18204. BoundingBox.IntersectsSphere = function (minPoint, maxPoint, sphereCenter, sphereRadius) {
  18205. var vector = BABYLON.Vector3.Clamp(sphereCenter, minPoint, maxPoint);
  18206. var num = BABYLON.Vector3.DistanceSquared(sphereCenter, vector);
  18207. return (num <= (sphereRadius * sphereRadius));
  18208. };
  18209. BoundingBox.IsCompletelyInFrustum = function (boundingVectors, frustumPlanes) {
  18210. for (var p = 0; p < 6; p++) {
  18211. for (var i = 0; i < 8; i++) {
  18212. if (frustumPlanes[p].dotCoordinate(boundingVectors[i]) < 0) {
  18213. return false;
  18214. }
  18215. }
  18216. }
  18217. return true;
  18218. };
  18219. BoundingBox.IsInFrustum = function (boundingVectors, frustumPlanes) {
  18220. for (var p = 0; p < 6; p++) {
  18221. var inCount = 8;
  18222. for (var i = 0; i < 8; i++) {
  18223. if (frustumPlanes[p].dotCoordinate(boundingVectors[i]) < 0) {
  18224. --inCount;
  18225. }
  18226. else {
  18227. break;
  18228. }
  18229. }
  18230. if (inCount === 0)
  18231. return false;
  18232. }
  18233. return true;
  18234. };
  18235. return BoundingBox;
  18236. }());
  18237. BABYLON.BoundingBox = BoundingBox;
  18238. })(BABYLON || (BABYLON = {}));
  18239. //# sourceMappingURL=babylon.boundingBox.js.map
  18240. var BABYLON;
  18241. (function (BABYLON) {
  18242. var computeBoxExtents = function (axis, box) {
  18243. var p = BABYLON.Vector3.Dot(box.centerWorld, axis);
  18244. var r0 = Math.abs(BABYLON.Vector3.Dot(box.directions[0], axis)) * box.extendSize.x;
  18245. var r1 = Math.abs(BABYLON.Vector3.Dot(box.directions[1], axis)) * box.extendSize.y;
  18246. var r2 = Math.abs(BABYLON.Vector3.Dot(box.directions[2], axis)) * box.extendSize.z;
  18247. var r = r0 + r1 + r2;
  18248. return {
  18249. min: p - r,
  18250. max: p + r
  18251. };
  18252. };
  18253. var extentsOverlap = function (min0, max0, min1, max1) { return !(min0 > max1 || min1 > max0); };
  18254. var axisOverlap = function (axis, box0, box1) {
  18255. var result0 = computeBoxExtents(axis, box0);
  18256. var result1 = computeBoxExtents(axis, box1);
  18257. return extentsOverlap(result0.min, result0.max, result1.min, result1.max);
  18258. };
  18259. var BoundingInfo = /** @class */ (function () {
  18260. function BoundingInfo(minimum, maximum) {
  18261. this.minimum = minimum;
  18262. this.maximum = maximum;
  18263. this._isLocked = false;
  18264. this.boundingBox = new BABYLON.BoundingBox(minimum, maximum);
  18265. this.boundingSphere = new BABYLON.BoundingSphere(minimum, maximum);
  18266. }
  18267. Object.defineProperty(BoundingInfo.prototype, "isLocked", {
  18268. get: function () {
  18269. return this._isLocked;
  18270. },
  18271. set: function (value) {
  18272. this._isLocked = value;
  18273. },
  18274. enumerable: true,
  18275. configurable: true
  18276. });
  18277. // Methods
  18278. BoundingInfo.prototype.update = function (world) {
  18279. if (this._isLocked) {
  18280. return;
  18281. }
  18282. this.boundingBox._update(world);
  18283. this.boundingSphere._update(world);
  18284. };
  18285. /**
  18286. * Recreate the bounding info to be centered around a specific point given a specific extend.
  18287. * @param center New center of the bounding info
  18288. * @param extend New extend of the bounding info
  18289. */
  18290. BoundingInfo.prototype.centerOn = function (center, extend) {
  18291. this.minimum = center.subtract(extend);
  18292. this.maximum = center.add(extend);
  18293. this.boundingBox = new BABYLON.BoundingBox(this.minimum, this.maximum);
  18294. this.boundingSphere = new BABYLON.BoundingSphere(this.minimum, this.maximum);
  18295. return this;
  18296. };
  18297. BoundingInfo.prototype.isInFrustum = function (frustumPlanes) {
  18298. if (!this.boundingSphere.isInFrustum(frustumPlanes))
  18299. return false;
  18300. return this.boundingBox.isInFrustum(frustumPlanes);
  18301. };
  18302. Object.defineProperty(BoundingInfo.prototype, "diagonalLength", {
  18303. /**
  18304. * Gets the world distance between the min and max points of the bounding box
  18305. */
  18306. get: function () {
  18307. var boundingBox = this.boundingBox;
  18308. var size = boundingBox.maximumWorld.subtract(boundingBox.minimumWorld);
  18309. return size.length();
  18310. },
  18311. enumerable: true,
  18312. configurable: true
  18313. });
  18314. BoundingInfo.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  18315. return this.boundingBox.isCompletelyInFrustum(frustumPlanes);
  18316. };
  18317. BoundingInfo.prototype._checkCollision = function (collider) {
  18318. return collider._canDoCollision(this.boundingSphere.centerWorld, this.boundingSphere.radiusWorld, this.boundingBox.minimumWorld, this.boundingBox.maximumWorld);
  18319. };
  18320. BoundingInfo.prototype.intersectsPoint = function (point) {
  18321. if (!this.boundingSphere.centerWorld) {
  18322. return false;
  18323. }
  18324. if (!this.boundingSphere.intersectsPoint(point)) {
  18325. return false;
  18326. }
  18327. if (!this.boundingBox.intersectsPoint(point)) {
  18328. return false;
  18329. }
  18330. return true;
  18331. };
  18332. BoundingInfo.prototype.intersects = function (boundingInfo, precise) {
  18333. if (!this.boundingSphere.centerWorld || !boundingInfo.boundingSphere.centerWorld) {
  18334. return false;
  18335. }
  18336. if (!BABYLON.BoundingSphere.Intersects(this.boundingSphere, boundingInfo.boundingSphere)) {
  18337. return false;
  18338. }
  18339. if (!BABYLON.BoundingBox.Intersects(this.boundingBox, boundingInfo.boundingBox)) {
  18340. return false;
  18341. }
  18342. if (!precise) {
  18343. return true;
  18344. }
  18345. var box0 = this.boundingBox;
  18346. var box1 = boundingInfo.boundingBox;
  18347. if (!axisOverlap(box0.directions[0], box0, box1))
  18348. return false;
  18349. if (!axisOverlap(box0.directions[1], box0, box1))
  18350. return false;
  18351. if (!axisOverlap(box0.directions[2], box0, box1))
  18352. return false;
  18353. if (!axisOverlap(box1.directions[0], box0, box1))
  18354. return false;
  18355. if (!axisOverlap(box1.directions[1], box0, box1))
  18356. return false;
  18357. if (!axisOverlap(box1.directions[2], box0, box1))
  18358. return false;
  18359. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[0]), box0, box1))
  18360. return false;
  18361. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[1]), box0, box1))
  18362. return false;
  18363. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[2]), box0, box1))
  18364. return false;
  18365. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[0]), box0, box1))
  18366. return false;
  18367. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[1]), box0, box1))
  18368. return false;
  18369. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[2]), box0, box1))
  18370. return false;
  18371. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[0]), box0, box1))
  18372. return false;
  18373. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[1]), box0, box1))
  18374. return false;
  18375. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[2]), box0, box1))
  18376. return false;
  18377. return true;
  18378. };
  18379. return BoundingInfo;
  18380. }());
  18381. BABYLON.BoundingInfo = BoundingInfo;
  18382. })(BABYLON || (BABYLON = {}));
  18383. //# sourceMappingURL=babylon.boundingInfo.js.map
  18384. var BABYLON;
  18385. (function (BABYLON) {
  18386. var TransformNode = /** @class */ (function (_super) {
  18387. __extends(TransformNode, _super);
  18388. function TransformNode(name, scene, isPure) {
  18389. if (scene === void 0) { scene = null; }
  18390. if (isPure === void 0) { isPure = true; }
  18391. var _this = _super.call(this, name, scene) || this;
  18392. _this._forward = new BABYLON.Vector3(0, 0, 1);
  18393. _this._forwardInverted = new BABYLON.Vector3(0, 0, -1);
  18394. _this._up = new BABYLON.Vector3(0, 1, 0);
  18395. _this._right = new BABYLON.Vector3(1, 0, 0);
  18396. _this._rightInverted = new BABYLON.Vector3(-1, 0, 0);
  18397. // Properties
  18398. _this._rotation = BABYLON.Vector3.Zero();
  18399. _this._scaling = BABYLON.Vector3.One();
  18400. _this._isDirty = false;
  18401. _this.billboardMode = TransformNode.BILLBOARDMODE_NONE;
  18402. _this.scalingDeterminant = 1;
  18403. _this.infiniteDistance = false;
  18404. _this.position = BABYLON.Vector3.Zero();
  18405. _this._localWorld = BABYLON.Matrix.Zero();
  18406. _this._worldMatrix = BABYLON.Matrix.Zero();
  18407. _this._worldMatrixDeterminant = 0;
  18408. _this._absolutePosition = BABYLON.Vector3.Zero();
  18409. _this._pivotMatrix = BABYLON.Matrix.Identity();
  18410. _this._postMultiplyPivotMatrix = false;
  18411. _this._isWorldMatrixFrozen = false;
  18412. /**
  18413. * An event triggered after the world matrix is updated
  18414. */
  18415. _this.onAfterWorldMatrixUpdateObservable = new BABYLON.Observable();
  18416. _this._nonUniformScaling = false;
  18417. if (isPure) {
  18418. _this.getScene().addTransformNode(_this);
  18419. }
  18420. return _this;
  18421. }
  18422. /**
  18423. * Gets a string idenfifying the name of the class
  18424. * @returns "TransformNode" string
  18425. */
  18426. TransformNode.prototype.getClassName = function () {
  18427. return "TransformNode";
  18428. };
  18429. Object.defineProperty(TransformNode.prototype, "rotation", {
  18430. /**
  18431. * Rotation property : a Vector3 depicting the rotation value in radians around each local axis X, Y, Z.
  18432. * If rotation quaternion is set, this Vector3 will (almost always) be the Zero vector!
  18433. * Default : (0.0, 0.0, 0.0)
  18434. */
  18435. get: function () {
  18436. return this._rotation;
  18437. },
  18438. set: function (newRotation) {
  18439. this._rotation = newRotation;
  18440. },
  18441. enumerable: true,
  18442. configurable: true
  18443. });
  18444. Object.defineProperty(TransformNode.prototype, "scaling", {
  18445. /**
  18446. * Scaling property : a Vector3 depicting the mesh scaling along each local axis X, Y, Z.
  18447. * Default : (1.0, 1.0, 1.0)
  18448. */
  18449. get: function () {
  18450. return this._scaling;
  18451. },
  18452. /**
  18453. * Scaling property : a Vector3 depicting the mesh scaling along each local axis X, Y, Z.
  18454. * Default : (1.0, 1.0, 1.0)
  18455. */
  18456. set: function (newScaling) {
  18457. this._scaling = newScaling;
  18458. },
  18459. enumerable: true,
  18460. configurable: true
  18461. });
  18462. Object.defineProperty(TransformNode.prototype, "rotationQuaternion", {
  18463. /**
  18464. * Rotation Quaternion property : this a Quaternion object depicting the mesh rotation by using a unit quaternion.
  18465. * It's null by default.
  18466. * 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)
  18467. */
  18468. get: function () {
  18469. return this._rotationQuaternion;
  18470. },
  18471. set: function (quaternion) {
  18472. this._rotationQuaternion = quaternion;
  18473. //reset the rotation vector.
  18474. if (quaternion && this.rotation.length()) {
  18475. this.rotation.copyFromFloats(0.0, 0.0, 0.0);
  18476. }
  18477. },
  18478. enumerable: true,
  18479. configurable: true
  18480. });
  18481. Object.defineProperty(TransformNode.prototype, "forward", {
  18482. /**
  18483. * The forward direction of that transform in world space.
  18484. */
  18485. get: function () {
  18486. return BABYLON.Vector3.Normalize(BABYLON.Vector3.TransformNormal(this.getScene().useRightHandedSystem ? this._forwardInverted : this._forward, this.getWorldMatrix()));
  18487. },
  18488. enumerable: true,
  18489. configurable: true
  18490. });
  18491. Object.defineProperty(TransformNode.prototype, "up", {
  18492. /**
  18493. * The up direction of that transform in world space.
  18494. */
  18495. get: function () {
  18496. return BABYLON.Vector3.Normalize(BABYLON.Vector3.TransformNormal(this._up, this.getWorldMatrix()));
  18497. },
  18498. enumerable: true,
  18499. configurable: true
  18500. });
  18501. Object.defineProperty(TransformNode.prototype, "right", {
  18502. /**
  18503. * The right direction of that transform in world space.
  18504. */
  18505. get: function () {
  18506. return BABYLON.Vector3.Normalize(BABYLON.Vector3.TransformNormal(this.getScene().useRightHandedSystem ? this._rightInverted : this._right, this.getWorldMatrix()));
  18507. },
  18508. enumerable: true,
  18509. configurable: true
  18510. });
  18511. /**
  18512. * Returns the latest update of the World matrix
  18513. * Returns a Matrix.
  18514. */
  18515. TransformNode.prototype.getWorldMatrix = function () {
  18516. if (this._currentRenderId !== this.getScene().getRenderId()) {
  18517. this.computeWorldMatrix();
  18518. }
  18519. return this._worldMatrix;
  18520. };
  18521. /** @hidden */
  18522. TransformNode.prototype._getWorldMatrixDeterminant = function () {
  18523. return this._worldMatrixDeterminant;
  18524. };
  18525. Object.defineProperty(TransformNode.prototype, "worldMatrixFromCache", {
  18526. /**
  18527. * Returns directly the latest state of the mesh World matrix.
  18528. * A Matrix is returned.
  18529. */
  18530. get: function () {
  18531. return this._worldMatrix;
  18532. },
  18533. enumerable: true,
  18534. configurable: true
  18535. });
  18536. /**
  18537. * Copies the paramater passed Matrix into the mesh Pose matrix.
  18538. * Returns the TransformNode.
  18539. */
  18540. TransformNode.prototype.updatePoseMatrix = function (matrix) {
  18541. this._poseMatrix.copyFrom(matrix);
  18542. return this;
  18543. };
  18544. /**
  18545. * Returns the mesh Pose matrix.
  18546. * Returned object : Matrix
  18547. */
  18548. TransformNode.prototype.getPoseMatrix = function () {
  18549. return this._poseMatrix;
  18550. };
  18551. TransformNode.prototype._isSynchronized = function () {
  18552. if (this._isDirty) {
  18553. return false;
  18554. }
  18555. if (this.billboardMode !== this._cache.billboardMode || this.billboardMode !== TransformNode.BILLBOARDMODE_NONE)
  18556. return false;
  18557. if (this._cache.pivotMatrixUpdated) {
  18558. return false;
  18559. }
  18560. if (this.infiniteDistance) {
  18561. return false;
  18562. }
  18563. if (!this._cache.position.equals(this.position))
  18564. return false;
  18565. if (this.rotationQuaternion) {
  18566. if (!this._cache.rotationQuaternion.equals(this.rotationQuaternion))
  18567. return false;
  18568. }
  18569. if (!this._cache.rotation.equals(this.rotation))
  18570. return false;
  18571. if (!this._cache.scaling.equals(this.scaling))
  18572. return false;
  18573. return true;
  18574. };
  18575. TransformNode.prototype._initCache = function () {
  18576. _super.prototype._initCache.call(this);
  18577. this._cache.localMatrixUpdated = false;
  18578. this._cache.position = BABYLON.Vector3.Zero();
  18579. this._cache.scaling = BABYLON.Vector3.Zero();
  18580. this._cache.rotation = BABYLON.Vector3.Zero();
  18581. this._cache.rotationQuaternion = new BABYLON.Quaternion(0, 0, 0, 0);
  18582. this._cache.billboardMode = -1;
  18583. };
  18584. TransformNode.prototype.markAsDirty = function (property) {
  18585. if (property === "rotation") {
  18586. this.rotationQuaternion = null;
  18587. }
  18588. this._currentRenderId = Number.MAX_VALUE;
  18589. this._isDirty = true;
  18590. return this;
  18591. };
  18592. Object.defineProperty(TransformNode.prototype, "absolutePosition", {
  18593. /**
  18594. * Returns the current mesh absolute position.
  18595. * Retuns a Vector3.
  18596. */
  18597. get: function () {
  18598. return this._absolutePosition;
  18599. },
  18600. enumerable: true,
  18601. configurable: true
  18602. });
  18603. /**
  18604. * Sets a new matrix to apply before all other transformation
  18605. * @param matrix defines the transform matrix
  18606. * @returns the current TransformNode
  18607. */
  18608. TransformNode.prototype.setPreTransformMatrix = function (matrix) {
  18609. return this.setPivotMatrix(matrix, false);
  18610. };
  18611. /**
  18612. * Sets a new pivot matrix to the current node
  18613. * @param matrix defines the new pivot matrix to use
  18614. * @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
  18615. * @returns the current TransformNode
  18616. */
  18617. TransformNode.prototype.setPivotMatrix = function (matrix, postMultiplyPivotMatrix) {
  18618. if (postMultiplyPivotMatrix === void 0) { postMultiplyPivotMatrix = true; }
  18619. this._pivotMatrix = matrix.clone();
  18620. this._cache.pivotMatrixUpdated = true;
  18621. this._postMultiplyPivotMatrix = postMultiplyPivotMatrix;
  18622. if (this._postMultiplyPivotMatrix) {
  18623. if (!this._pivotMatrixInverse) {
  18624. this._pivotMatrixInverse = BABYLON.Matrix.Invert(this._pivotMatrix);
  18625. }
  18626. else {
  18627. this._pivotMatrix.invertToRef(this._pivotMatrixInverse);
  18628. }
  18629. }
  18630. return this;
  18631. };
  18632. /**
  18633. * Returns the mesh pivot matrix.
  18634. * Default : Identity.
  18635. * A Matrix is returned.
  18636. */
  18637. TransformNode.prototype.getPivotMatrix = function () {
  18638. return this._pivotMatrix;
  18639. };
  18640. /**
  18641. * Prevents the World matrix to be computed any longer.
  18642. * Returns the TransformNode.
  18643. */
  18644. TransformNode.prototype.freezeWorldMatrix = function () {
  18645. this._isWorldMatrixFrozen = false; // no guarantee world is not already frozen, switch off temporarily
  18646. this.computeWorldMatrix(true);
  18647. this._isWorldMatrixFrozen = true;
  18648. return this;
  18649. };
  18650. /**
  18651. * Allows back the World matrix computation.
  18652. * Returns the TransformNode.
  18653. */
  18654. TransformNode.prototype.unfreezeWorldMatrix = function () {
  18655. this._isWorldMatrixFrozen = false;
  18656. this.computeWorldMatrix(true);
  18657. return this;
  18658. };
  18659. Object.defineProperty(TransformNode.prototype, "isWorldMatrixFrozen", {
  18660. /**
  18661. * True if the World matrix has been frozen.
  18662. * Returns a boolean.
  18663. */
  18664. get: function () {
  18665. return this._isWorldMatrixFrozen;
  18666. },
  18667. enumerable: true,
  18668. configurable: true
  18669. });
  18670. /**
  18671. * Retuns the mesh absolute position in the World.
  18672. * Returns a Vector3.
  18673. */
  18674. TransformNode.prototype.getAbsolutePosition = function () {
  18675. this.computeWorldMatrix();
  18676. return this._absolutePosition;
  18677. };
  18678. /**
  18679. * Sets the mesh absolute position in the World from a Vector3 or an Array(3).
  18680. * Returns the TransformNode.
  18681. */
  18682. TransformNode.prototype.setAbsolutePosition = function (absolutePosition) {
  18683. if (!absolutePosition) {
  18684. return this;
  18685. }
  18686. var absolutePositionX;
  18687. var absolutePositionY;
  18688. var absolutePositionZ;
  18689. if (absolutePosition.x === undefined) {
  18690. if (arguments.length < 3) {
  18691. return this;
  18692. }
  18693. absolutePositionX = arguments[0];
  18694. absolutePositionY = arguments[1];
  18695. absolutePositionZ = arguments[2];
  18696. }
  18697. else {
  18698. absolutePositionX = absolutePosition.x;
  18699. absolutePositionY = absolutePosition.y;
  18700. absolutePositionZ = absolutePosition.z;
  18701. }
  18702. if (this.parent) {
  18703. var invertParentWorldMatrix = this.parent.getWorldMatrix().clone();
  18704. invertParentWorldMatrix.invert();
  18705. var worldPosition = new BABYLON.Vector3(absolutePositionX, absolutePositionY, absolutePositionZ);
  18706. this.position = BABYLON.Vector3.TransformCoordinates(worldPosition, invertParentWorldMatrix);
  18707. }
  18708. else {
  18709. this.position.x = absolutePositionX;
  18710. this.position.y = absolutePositionY;
  18711. this.position.z = absolutePositionZ;
  18712. }
  18713. return this;
  18714. };
  18715. /**
  18716. * Sets the mesh position in its local space.
  18717. * Returns the TransformNode.
  18718. */
  18719. TransformNode.prototype.setPositionWithLocalVector = function (vector3) {
  18720. this.computeWorldMatrix();
  18721. this.position = BABYLON.Vector3.TransformNormal(vector3, this._localWorld);
  18722. return this;
  18723. };
  18724. /**
  18725. * Returns the mesh position in the local space from the current World matrix values.
  18726. * Returns a new Vector3.
  18727. */
  18728. TransformNode.prototype.getPositionExpressedInLocalSpace = function () {
  18729. this.computeWorldMatrix();
  18730. var invLocalWorldMatrix = this._localWorld.clone();
  18731. invLocalWorldMatrix.invert();
  18732. return BABYLON.Vector3.TransformNormal(this.position, invLocalWorldMatrix);
  18733. };
  18734. /**
  18735. * Translates the mesh along the passed Vector3 in its local space.
  18736. * Returns the TransformNode.
  18737. */
  18738. TransformNode.prototype.locallyTranslate = function (vector3) {
  18739. this.computeWorldMatrix(true);
  18740. this.position = BABYLON.Vector3.TransformCoordinates(vector3, this._localWorld);
  18741. return this;
  18742. };
  18743. /**
  18744. * Orients a mesh towards a target point. Mesh must be drawn facing user.
  18745. * @param targetPoint the position (must be in same space as current mesh) to look at
  18746. * @param yawCor optional yaw (y-axis) correction in radians
  18747. * @param pitchCor optional pitch (x-axis) correction in radians
  18748. * @param rollCor optional roll (z-axis) correction in radians
  18749. * @param space the choosen space of the target
  18750. * @returns the TransformNode.
  18751. */
  18752. TransformNode.prototype.lookAt = function (targetPoint, yawCor, pitchCor, rollCor, space) {
  18753. if (yawCor === void 0) { yawCor = 0; }
  18754. if (pitchCor === void 0) { pitchCor = 0; }
  18755. if (rollCor === void 0) { rollCor = 0; }
  18756. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  18757. var dv = TransformNode._lookAtVectorCache;
  18758. var pos = space === BABYLON.Space.LOCAL ? this.position : this.getAbsolutePosition();
  18759. targetPoint.subtractToRef(pos, dv);
  18760. var yaw = -Math.atan2(dv.z, dv.x) - Math.PI / 2;
  18761. var len = Math.sqrt(dv.x * dv.x + dv.z * dv.z);
  18762. var pitch = Math.atan2(dv.y, len);
  18763. if (this.rotationQuaternion) {
  18764. BABYLON.Quaternion.RotationYawPitchRollToRef(yaw + yawCor, pitch + pitchCor, rollCor, this.rotationQuaternion);
  18765. }
  18766. else {
  18767. this.rotation.x = pitch + pitchCor;
  18768. this.rotation.y = yaw + yawCor;
  18769. this.rotation.z = rollCor;
  18770. }
  18771. return this;
  18772. };
  18773. /**
  18774. * Returns a new Vector3 what is the localAxis, expressed in the mesh local space, rotated like the mesh.
  18775. * This Vector3 is expressed in the World space.
  18776. */
  18777. TransformNode.prototype.getDirection = function (localAxis) {
  18778. var result = BABYLON.Vector3.Zero();
  18779. this.getDirectionToRef(localAxis, result);
  18780. return result;
  18781. };
  18782. /**
  18783. * Sets the Vector3 "result" as the rotated Vector3 "localAxis" in the same rotation than the mesh.
  18784. * localAxis is expressed in the mesh local space.
  18785. * result is computed in the Wordl space from the mesh World matrix.
  18786. * Returns the TransformNode.
  18787. */
  18788. TransformNode.prototype.getDirectionToRef = function (localAxis, result) {
  18789. BABYLON.Vector3.TransformNormalToRef(localAxis, this.getWorldMatrix(), result);
  18790. return this;
  18791. };
  18792. /**
  18793. * Sets a new pivot point to the current node
  18794. * @param point defines the new pivot point to use
  18795. * @param space defines if the point is in world or local space (local by default)
  18796. * @returns the current TransformNode
  18797. */
  18798. TransformNode.prototype.setPivotPoint = function (point, space) {
  18799. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  18800. if (this.getScene().getRenderId() == 0) {
  18801. this.computeWorldMatrix(true);
  18802. }
  18803. var wm = this.getWorldMatrix();
  18804. if (space == BABYLON.Space.WORLD) {
  18805. var tmat = BABYLON.Tmp.Matrix[0];
  18806. wm.invertToRef(tmat);
  18807. point = BABYLON.Vector3.TransformCoordinates(point, tmat);
  18808. }
  18809. return this.setPivotMatrix(BABYLON.Matrix.Translation(-point.x, -point.y, -point.z), true);
  18810. };
  18811. /**
  18812. * Returns a new Vector3 set with the mesh pivot point coordinates in the local space.
  18813. */
  18814. TransformNode.prototype.getPivotPoint = function () {
  18815. var point = BABYLON.Vector3.Zero();
  18816. this.getPivotPointToRef(point);
  18817. return point;
  18818. };
  18819. /**
  18820. * Sets the passed Vector3 "result" with the coordinates of the mesh pivot point in the local space.
  18821. * Returns the TransformNode.
  18822. */
  18823. TransformNode.prototype.getPivotPointToRef = function (result) {
  18824. result.x = -this._pivotMatrix.m[12];
  18825. result.y = -this._pivotMatrix.m[13];
  18826. result.z = -this._pivotMatrix.m[14];
  18827. return this;
  18828. };
  18829. /**
  18830. * Returns a new Vector3 set with the mesh pivot point World coordinates.
  18831. */
  18832. TransformNode.prototype.getAbsolutePivotPoint = function () {
  18833. var point = BABYLON.Vector3.Zero();
  18834. this.getAbsolutePivotPointToRef(point);
  18835. return point;
  18836. };
  18837. /**
  18838. * Sets the Vector3 "result" coordinates with the mesh pivot point World coordinates.
  18839. * Returns the TransformNode.
  18840. */
  18841. TransformNode.prototype.getAbsolutePivotPointToRef = function (result) {
  18842. result.x = this._pivotMatrix.m[12];
  18843. result.y = this._pivotMatrix.m[13];
  18844. result.z = this._pivotMatrix.m[14];
  18845. this.getPivotPointToRef(result);
  18846. BABYLON.Vector3.TransformCoordinatesToRef(result, this.getWorldMatrix(), result);
  18847. return this;
  18848. };
  18849. /**
  18850. * Defines the passed node as the parent of the current node.
  18851. * The node will remain exactly where it is and its position / rotation will be updated accordingly
  18852. * Returns the TransformNode.
  18853. */
  18854. TransformNode.prototype.setParent = function (node) {
  18855. if (node === null) {
  18856. var rotation = BABYLON.Tmp.Quaternion[0];
  18857. var position = BABYLON.Tmp.Vector3[0];
  18858. var scale = BABYLON.Tmp.Vector3[1];
  18859. if (this.parent && this.parent.computeWorldMatrix) {
  18860. this.parent.computeWorldMatrix(true);
  18861. }
  18862. this.computeWorldMatrix(true);
  18863. this.getWorldMatrix().decompose(scale, rotation, position);
  18864. if (this.rotationQuaternion) {
  18865. this.rotationQuaternion.copyFrom(rotation);
  18866. }
  18867. else {
  18868. rotation.toEulerAnglesToRef(this.rotation);
  18869. }
  18870. this.scaling.x = scale.x;
  18871. this.scaling.y = scale.y;
  18872. this.scaling.z = scale.z;
  18873. this.position.x = position.x;
  18874. this.position.y = position.y;
  18875. this.position.z = position.z;
  18876. }
  18877. else {
  18878. var rotation = BABYLON.Tmp.Quaternion[0];
  18879. var position = BABYLON.Tmp.Vector3[0];
  18880. var scale = BABYLON.Tmp.Vector3[1];
  18881. var diffMatrix = BABYLON.Tmp.Matrix[0];
  18882. var invParentMatrix = BABYLON.Tmp.Matrix[1];
  18883. this.computeWorldMatrix(true);
  18884. node.computeWorldMatrix(true);
  18885. node.getWorldMatrix().invertToRef(invParentMatrix);
  18886. this.getWorldMatrix().multiplyToRef(invParentMatrix, diffMatrix);
  18887. diffMatrix.decompose(scale, rotation, position);
  18888. if (this.rotationQuaternion) {
  18889. this.rotationQuaternion.copyFrom(rotation);
  18890. }
  18891. else {
  18892. rotation.toEulerAnglesToRef(this.rotation);
  18893. }
  18894. this.position.x = position.x;
  18895. this.position.y = position.y;
  18896. this.position.z = position.z;
  18897. this.scaling.x = scale.x;
  18898. this.scaling.y = scale.y;
  18899. this.scaling.z = scale.z;
  18900. }
  18901. this.parent = node;
  18902. return this;
  18903. };
  18904. Object.defineProperty(TransformNode.prototype, "nonUniformScaling", {
  18905. get: function () {
  18906. return this._nonUniformScaling;
  18907. },
  18908. enumerable: true,
  18909. configurable: true
  18910. });
  18911. TransformNode.prototype._updateNonUniformScalingState = function (value) {
  18912. if (this._nonUniformScaling === value) {
  18913. return false;
  18914. }
  18915. this._nonUniformScaling = true;
  18916. return true;
  18917. };
  18918. /**
  18919. * Attach the current TransformNode to another TransformNode associated with a bone
  18920. * @param bone Bone affecting the TransformNode
  18921. * @param affectedTransformNode TransformNode associated with the bone
  18922. */
  18923. TransformNode.prototype.attachToBone = function (bone, affectedTransformNode) {
  18924. this._transformToBoneReferal = affectedTransformNode;
  18925. this.parent = bone;
  18926. if (bone.getWorldMatrix().determinant() < 0) {
  18927. this.scalingDeterminant *= -1;
  18928. }
  18929. return this;
  18930. };
  18931. TransformNode.prototype.detachFromBone = function () {
  18932. if (!this.parent) {
  18933. return this;
  18934. }
  18935. if (this.parent.getWorldMatrix().determinant() < 0) {
  18936. this.scalingDeterminant *= -1;
  18937. }
  18938. this._transformToBoneReferal = null;
  18939. this.parent = null;
  18940. return this;
  18941. };
  18942. /**
  18943. * Rotates the mesh around the axis vector for the passed angle (amount) expressed in radians, in the given space.
  18944. * space (default LOCAL) can be either BABYLON.Space.LOCAL, either BABYLON.Space.WORLD.
  18945. * Note that the property `rotationQuaternion` is then automatically updated and the property `rotation` is set to (0,0,0) and no longer used.
  18946. * The passed axis is also normalized.
  18947. * Returns the TransformNode.
  18948. */
  18949. TransformNode.prototype.rotate = function (axis, amount, space) {
  18950. axis.normalize();
  18951. if (!this.rotationQuaternion) {
  18952. this.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z);
  18953. this.rotation = BABYLON.Vector3.Zero();
  18954. }
  18955. var rotationQuaternion;
  18956. if (!space || space === BABYLON.Space.LOCAL) {
  18957. rotationQuaternion = BABYLON.Quaternion.RotationAxisToRef(axis, amount, TransformNode._rotationAxisCache);
  18958. this.rotationQuaternion.multiplyToRef(rotationQuaternion, this.rotationQuaternion);
  18959. }
  18960. else {
  18961. if (this.parent) {
  18962. var invertParentWorldMatrix = this.parent.getWorldMatrix().clone();
  18963. invertParentWorldMatrix.invert();
  18964. axis = BABYLON.Vector3.TransformNormal(axis, invertParentWorldMatrix);
  18965. }
  18966. rotationQuaternion = BABYLON.Quaternion.RotationAxisToRef(axis, amount, TransformNode._rotationAxisCache);
  18967. rotationQuaternion.multiplyToRef(this.rotationQuaternion, this.rotationQuaternion);
  18968. }
  18969. return this;
  18970. };
  18971. /**
  18972. * Rotates the mesh around the axis vector for the passed angle (amount) expressed in radians, in world space.
  18973. * Note that the property `rotationQuaternion` is then automatically updated and the property `rotation` is set to (0,0,0) and no longer used.
  18974. * The passed axis is also normalized.
  18975. * Returns the TransformNode.
  18976. * Method is based on http://www.euclideanspace.com/maths/geometry/affine/aroundPoint/index.htm
  18977. */
  18978. TransformNode.prototype.rotateAround = function (point, axis, amount) {
  18979. axis.normalize();
  18980. if (!this.rotationQuaternion) {
  18981. this.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z);
  18982. this.rotation.copyFromFloats(0, 0, 0);
  18983. }
  18984. point.subtractToRef(this.position, BABYLON.Tmp.Vector3[0]);
  18985. BABYLON.Matrix.TranslationToRef(BABYLON.Tmp.Vector3[0].x, BABYLON.Tmp.Vector3[0].y, BABYLON.Tmp.Vector3[0].z, BABYLON.Tmp.Matrix[0]);
  18986. BABYLON.Tmp.Matrix[0].invertToRef(BABYLON.Tmp.Matrix[2]);
  18987. BABYLON.Matrix.RotationAxisToRef(axis, amount, BABYLON.Tmp.Matrix[1]);
  18988. BABYLON.Tmp.Matrix[2].multiplyToRef(BABYLON.Tmp.Matrix[1], BABYLON.Tmp.Matrix[2]);
  18989. BABYLON.Tmp.Matrix[2].multiplyToRef(BABYLON.Tmp.Matrix[0], BABYLON.Tmp.Matrix[2]);
  18990. BABYLON.Tmp.Matrix[2].decompose(BABYLON.Tmp.Vector3[0], BABYLON.Tmp.Quaternion[0], BABYLON.Tmp.Vector3[1]);
  18991. this.position.addInPlace(BABYLON.Tmp.Vector3[1]);
  18992. BABYLON.Tmp.Quaternion[0].multiplyToRef(this.rotationQuaternion, this.rotationQuaternion);
  18993. return this;
  18994. };
  18995. /**
  18996. * Translates the mesh along the axis vector for the passed distance in the given space.
  18997. * space (default LOCAL) can be either BABYLON.Space.LOCAL, either BABYLON.Space.WORLD.
  18998. * Returns the TransformNode.
  18999. */
  19000. TransformNode.prototype.translate = function (axis, distance, space) {
  19001. var displacementVector = axis.scale(distance);
  19002. if (!space || space === BABYLON.Space.LOCAL) {
  19003. var tempV3 = this.getPositionExpressedInLocalSpace().add(displacementVector);
  19004. this.setPositionWithLocalVector(tempV3);
  19005. }
  19006. else {
  19007. this.setAbsolutePosition(this.getAbsolutePosition().add(displacementVector));
  19008. }
  19009. return this;
  19010. };
  19011. /**
  19012. * Adds a rotation step to the mesh current rotation.
  19013. * x, y, z are Euler angles expressed in radians.
  19014. * This methods updates the current mesh rotation, either mesh.rotation, either mesh.rotationQuaternion if it's set.
  19015. * This means this rotation is made in the mesh local space only.
  19016. * It's useful to set a custom rotation order different from the BJS standard one YXZ.
  19017. * Example : this rotates the mesh first around its local X axis, then around its local Z axis, finally around its local Y axis.
  19018. * ```javascript
  19019. * mesh.addRotation(x1, 0, 0).addRotation(0, 0, z2).addRotation(0, 0, y3);
  19020. * ```
  19021. * Note that `addRotation()` accumulates the passed rotation values to the current ones and computes the .rotation or .rotationQuaternion updated values.
  19022. * 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.
  19023. * Returns the TransformNode.
  19024. */
  19025. TransformNode.prototype.addRotation = function (x, y, z) {
  19026. var rotationQuaternion;
  19027. if (this.rotationQuaternion) {
  19028. rotationQuaternion = this.rotationQuaternion;
  19029. }
  19030. else {
  19031. rotationQuaternion = BABYLON.Tmp.Quaternion[1];
  19032. BABYLON.Quaternion.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, rotationQuaternion);
  19033. }
  19034. var accumulation = BABYLON.Tmp.Quaternion[0];
  19035. BABYLON.Quaternion.RotationYawPitchRollToRef(y, x, z, accumulation);
  19036. rotationQuaternion.multiplyInPlace(accumulation);
  19037. if (!this.rotationQuaternion) {
  19038. rotationQuaternion.toEulerAnglesToRef(this.rotation);
  19039. }
  19040. return this;
  19041. };
  19042. /**
  19043. * Computes the mesh World matrix and returns it.
  19044. * If the mesh world matrix is frozen, this computation does nothing more than returning the last frozen values.
  19045. * If the parameter `force` is let to `false` (default), the current cached World matrix is returned.
  19046. * If the parameter `force`is set to `true`, the actual computation is done.
  19047. * Returns the mesh World Matrix.
  19048. */
  19049. TransformNode.prototype.computeWorldMatrix = function (force) {
  19050. if (this._isWorldMatrixFrozen) {
  19051. return this._worldMatrix;
  19052. }
  19053. if (!force && this.isSynchronized(true)) {
  19054. this._currentRenderId = this.getScene().getRenderId();
  19055. return this._worldMatrix;
  19056. }
  19057. this._cache.position.copyFrom(this.position);
  19058. this._cache.scaling.copyFrom(this.scaling);
  19059. this._cache.pivotMatrixUpdated = false;
  19060. this._cache.billboardMode = this.billboardMode;
  19061. this._currentRenderId = this.getScene().getRenderId();
  19062. this._childRenderId = this.getScene().getRenderId();
  19063. this._isDirty = false;
  19064. // Scaling
  19065. BABYLON.Matrix.ScalingToRef(this.scaling.x * this.scalingDeterminant, this.scaling.y * this.scalingDeterminant, this.scaling.z * this.scalingDeterminant, BABYLON.Tmp.Matrix[1]);
  19066. // Rotation
  19067. //rotate, if quaternion is set and rotation was used
  19068. if (this.rotationQuaternion) {
  19069. var len = this.rotation.length();
  19070. if (len) {
  19071. this.rotationQuaternion.multiplyInPlace(BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z));
  19072. this.rotation.copyFromFloats(0, 0, 0);
  19073. }
  19074. }
  19075. if (this.rotationQuaternion) {
  19076. this.rotationQuaternion.toRotationMatrix(BABYLON.Tmp.Matrix[0]);
  19077. this._cache.rotationQuaternion.copyFrom(this.rotationQuaternion);
  19078. }
  19079. else {
  19080. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, BABYLON.Tmp.Matrix[0]);
  19081. this._cache.rotation.copyFrom(this.rotation);
  19082. }
  19083. // Translation
  19084. var camera = this.getScene().activeCamera;
  19085. if (this.infiniteDistance && !this.parent && camera) {
  19086. var cameraWorldMatrix = camera.getWorldMatrix();
  19087. var cameraGlobalPosition = new BABYLON.Vector3(cameraWorldMatrix.m[12], cameraWorldMatrix.m[13], cameraWorldMatrix.m[14]);
  19088. BABYLON.Matrix.TranslationToRef(this.position.x + cameraGlobalPosition.x, this.position.y + cameraGlobalPosition.y, this.position.z + cameraGlobalPosition.z, BABYLON.Tmp.Matrix[2]);
  19089. }
  19090. else {
  19091. BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, BABYLON.Tmp.Matrix[2]);
  19092. }
  19093. // Composing transformations
  19094. this._pivotMatrix.multiplyToRef(BABYLON.Tmp.Matrix[1], BABYLON.Tmp.Matrix[4]);
  19095. BABYLON.Tmp.Matrix[4].multiplyToRef(BABYLON.Tmp.Matrix[0], BABYLON.Tmp.Matrix[5]);
  19096. // Billboarding (testing PG:http://www.babylonjs-playground.com/#UJEIL#13)
  19097. if (this.billboardMode !== TransformNode.BILLBOARDMODE_NONE && camera) {
  19098. if ((this.billboardMode & TransformNode.BILLBOARDMODE_ALL) !== TransformNode.BILLBOARDMODE_ALL) {
  19099. // Need to decompose each rotation here
  19100. var currentPosition = BABYLON.Tmp.Vector3[3];
  19101. if (this.parent && this.parent.getWorldMatrix) {
  19102. if (this._transformToBoneReferal) {
  19103. this.parent.getWorldMatrix().multiplyToRef(this._transformToBoneReferal.getWorldMatrix(), BABYLON.Tmp.Matrix[6]);
  19104. BABYLON.Vector3.TransformCoordinatesToRef(this.position, BABYLON.Tmp.Matrix[6], currentPosition);
  19105. }
  19106. else {
  19107. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this.parent.getWorldMatrix(), currentPosition);
  19108. }
  19109. }
  19110. else {
  19111. currentPosition.copyFrom(this.position);
  19112. }
  19113. currentPosition.subtractInPlace(camera.globalPosition);
  19114. var finalEuler = BABYLON.Tmp.Vector3[4].copyFromFloats(0, 0, 0);
  19115. if ((this.billboardMode & TransformNode.BILLBOARDMODE_X) === TransformNode.BILLBOARDMODE_X) {
  19116. finalEuler.x = Math.atan2(-currentPosition.y, currentPosition.z);
  19117. }
  19118. if ((this.billboardMode & TransformNode.BILLBOARDMODE_Y) === TransformNode.BILLBOARDMODE_Y) {
  19119. finalEuler.y = Math.atan2(currentPosition.x, currentPosition.z);
  19120. }
  19121. if ((this.billboardMode & TransformNode.BILLBOARDMODE_Z) === TransformNode.BILLBOARDMODE_Z) {
  19122. finalEuler.z = Math.atan2(currentPosition.y, currentPosition.x);
  19123. }
  19124. BABYLON.Matrix.RotationYawPitchRollToRef(finalEuler.y, finalEuler.x, finalEuler.z, BABYLON.Tmp.Matrix[0]);
  19125. }
  19126. else {
  19127. BABYLON.Tmp.Matrix[1].copyFrom(camera.getViewMatrix());
  19128. BABYLON.Tmp.Matrix[1].setTranslationFromFloats(0, 0, 0);
  19129. BABYLON.Tmp.Matrix[1].invertToRef(BABYLON.Tmp.Matrix[0]);
  19130. }
  19131. BABYLON.Tmp.Matrix[1].copyFrom(BABYLON.Tmp.Matrix[5]);
  19132. BABYLON.Tmp.Matrix[1].multiplyToRef(BABYLON.Tmp.Matrix[0], BABYLON.Tmp.Matrix[5]);
  19133. }
  19134. // Local world
  19135. BABYLON.Tmp.Matrix[5].multiplyToRef(BABYLON.Tmp.Matrix[2], this._localWorld);
  19136. // Parent
  19137. if (this.parent && this.parent.getWorldMatrix) {
  19138. if (this.billboardMode !== TransformNode.BILLBOARDMODE_NONE) {
  19139. if (this._transformToBoneReferal) {
  19140. this.parent.getWorldMatrix().multiplyToRef(this._transformToBoneReferal.getWorldMatrix(), BABYLON.Tmp.Matrix[6]);
  19141. BABYLON.Tmp.Matrix[5].copyFrom(BABYLON.Tmp.Matrix[6]);
  19142. }
  19143. else {
  19144. BABYLON.Tmp.Matrix[5].copyFrom(this.parent.getWorldMatrix());
  19145. }
  19146. this._localWorld.getTranslationToRef(BABYLON.Tmp.Vector3[5]);
  19147. BABYLON.Vector3.TransformCoordinatesToRef(BABYLON.Tmp.Vector3[5], BABYLON.Tmp.Matrix[5], BABYLON.Tmp.Vector3[5]);
  19148. this._worldMatrix.copyFrom(this._localWorld);
  19149. this._worldMatrix.setTranslation(BABYLON.Tmp.Vector3[5]);
  19150. }
  19151. else {
  19152. if (this._transformToBoneReferal) {
  19153. this._localWorld.multiplyToRef(this.parent.getWorldMatrix(), BABYLON.Tmp.Matrix[6]);
  19154. BABYLON.Tmp.Matrix[6].multiplyToRef(this._transformToBoneReferal.getWorldMatrix(), this._worldMatrix);
  19155. }
  19156. else {
  19157. this._localWorld.multiplyToRef(this.parent.getWorldMatrix(), this._worldMatrix);
  19158. }
  19159. }
  19160. this._markSyncedWithParent();
  19161. }
  19162. else {
  19163. this._worldMatrix.copyFrom(this._localWorld);
  19164. }
  19165. // Post multiply inverse of pivotMatrix
  19166. if (this._postMultiplyPivotMatrix) {
  19167. this._worldMatrix.multiplyToRef(this._pivotMatrixInverse, this._worldMatrix);
  19168. }
  19169. // Normal matrix
  19170. if (this.scaling.isNonUniform) {
  19171. this._updateNonUniformScalingState(true);
  19172. }
  19173. else if (this.parent && this.parent._nonUniformScaling) {
  19174. this._updateNonUniformScalingState(this.parent._nonUniformScaling);
  19175. }
  19176. else {
  19177. this._updateNonUniformScalingState(false);
  19178. }
  19179. this._afterComputeWorldMatrix();
  19180. // Absolute position
  19181. this._absolutePosition.copyFromFloats(this._worldMatrix.m[12], this._worldMatrix.m[13], this._worldMatrix.m[14]);
  19182. // Callbacks
  19183. this.onAfterWorldMatrixUpdateObservable.notifyObservers(this);
  19184. if (!this._poseMatrix) {
  19185. this._poseMatrix = BABYLON.Matrix.Invert(this._worldMatrix);
  19186. }
  19187. // Cache the determinant
  19188. this._worldMatrixDeterminant = this._worldMatrix.determinant();
  19189. return this._worldMatrix;
  19190. };
  19191. TransformNode.prototype._afterComputeWorldMatrix = function () {
  19192. };
  19193. /**
  19194. * If you'd like to be called back after the mesh position, rotation or scaling has been updated.
  19195. * @param func: callback function to add
  19196. *
  19197. * Returns the TransformNode.
  19198. */
  19199. TransformNode.prototype.registerAfterWorldMatrixUpdate = function (func) {
  19200. this.onAfterWorldMatrixUpdateObservable.add(func);
  19201. return this;
  19202. };
  19203. /**
  19204. * Removes a registered callback function.
  19205. * Returns the TransformNode.
  19206. */
  19207. TransformNode.prototype.unregisterAfterWorldMatrixUpdate = function (func) {
  19208. this.onAfterWorldMatrixUpdateObservable.removeCallback(func);
  19209. return this;
  19210. };
  19211. /**
  19212. * Clone the current transform node
  19213. * Returns the new transform node
  19214. * @param name Name of the new clone
  19215. * @param newParent New parent for the clone
  19216. * @param doNotCloneChildren Do not clone children hierarchy
  19217. */
  19218. TransformNode.prototype.clone = function (name, newParent, doNotCloneChildren) {
  19219. var _this = this;
  19220. var result = BABYLON.SerializationHelper.Clone(function () { return new TransformNode(name, _this.getScene()); }, this);
  19221. result.name = name;
  19222. result.id = name;
  19223. if (newParent) {
  19224. result.parent = newParent;
  19225. }
  19226. if (!doNotCloneChildren) {
  19227. // Children
  19228. var directDescendants = this.getDescendants(true);
  19229. for (var index = 0; index < directDescendants.length; index++) {
  19230. var child = directDescendants[index];
  19231. if (child.clone) {
  19232. child.clone(name + "." + child.name, result);
  19233. }
  19234. }
  19235. }
  19236. return result;
  19237. };
  19238. TransformNode.prototype.serialize = function (currentSerializationObject) {
  19239. var serializationObject = BABYLON.SerializationHelper.Serialize(this, currentSerializationObject);
  19240. serializationObject.type = this.getClassName();
  19241. // Parent
  19242. if (this.parent) {
  19243. serializationObject.parentId = this.parent.id;
  19244. }
  19245. if (BABYLON.Tags && BABYLON.Tags.HasTags(this)) {
  19246. serializationObject.tags = BABYLON.Tags.GetTags(this);
  19247. }
  19248. serializationObject.localMatrix = this.getPivotMatrix().asArray();
  19249. serializationObject.isEnabled = this.isEnabled();
  19250. // Parent
  19251. if (this.parent) {
  19252. serializationObject.parentId = this.parent.id;
  19253. }
  19254. return serializationObject;
  19255. };
  19256. // Statics
  19257. /**
  19258. * Returns a new TransformNode object parsed from the source provided.
  19259. * The parameter `parsedMesh` is the source.
  19260. * The parameter `rootUrl` is a string, it's the root URL to prefix the `delayLoadingFile` property with
  19261. */
  19262. TransformNode.Parse = function (parsedTransformNode, scene, rootUrl) {
  19263. var transformNode = BABYLON.SerializationHelper.Parse(function () { return new TransformNode(parsedTransformNode.name, scene); }, parsedTransformNode, scene, rootUrl);
  19264. if (BABYLON.Tags) {
  19265. BABYLON.Tags.AddTagsTo(transformNode, parsedTransformNode.tags);
  19266. }
  19267. if (parsedTransformNode.localMatrix) {
  19268. transformNode.setPreTransformMatrix(BABYLON.Matrix.FromArray(parsedTransformNode.localMatrix));
  19269. }
  19270. else if (parsedTransformNode.pivotMatrix) {
  19271. transformNode.setPivotMatrix(BABYLON.Matrix.FromArray(parsedTransformNode.pivotMatrix));
  19272. }
  19273. transformNode.setEnabled(parsedTransformNode.isEnabled);
  19274. // Parent
  19275. if (parsedTransformNode.parentId) {
  19276. transformNode._waitingParentId = parsedTransformNode.parentId;
  19277. }
  19278. return transformNode;
  19279. };
  19280. /**
  19281. * Releases resources associated with this transform node.
  19282. * @param doNotRecurse Set to true to not recurse into each children (recurse into each children by default)
  19283. * @param disposeMaterialAndTextures Set to true to also dispose referenced materials and textures (false by default)
  19284. */
  19285. TransformNode.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  19286. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  19287. // Animations
  19288. this.getScene().stopAnimation(this);
  19289. // Remove from scene
  19290. this.getScene().removeTransformNode(this);
  19291. this.onAfterWorldMatrixUpdateObservable.clear();
  19292. _super.prototype.dispose.call(this, doNotRecurse, disposeMaterialAndTextures);
  19293. };
  19294. // Statics
  19295. TransformNode.BILLBOARDMODE_NONE = 0;
  19296. TransformNode.BILLBOARDMODE_X = 1;
  19297. TransformNode.BILLBOARDMODE_Y = 2;
  19298. TransformNode.BILLBOARDMODE_Z = 4;
  19299. TransformNode.BILLBOARDMODE_ALL = 7;
  19300. TransformNode._lookAtVectorCache = new BABYLON.Vector3(0, 0, 0);
  19301. TransformNode._rotationAxisCache = new BABYLON.Quaternion();
  19302. __decorate([
  19303. BABYLON.serializeAsVector3()
  19304. ], TransformNode.prototype, "_rotation", void 0);
  19305. __decorate([
  19306. BABYLON.serializeAsQuaternion()
  19307. ], TransformNode.prototype, "_rotationQuaternion", void 0);
  19308. __decorate([
  19309. BABYLON.serializeAsVector3()
  19310. ], TransformNode.prototype, "_scaling", void 0);
  19311. __decorate([
  19312. BABYLON.serialize()
  19313. ], TransformNode.prototype, "billboardMode", void 0);
  19314. __decorate([
  19315. BABYLON.serialize()
  19316. ], TransformNode.prototype, "scalingDeterminant", void 0);
  19317. __decorate([
  19318. BABYLON.serialize()
  19319. ], TransformNode.prototype, "infiniteDistance", void 0);
  19320. __decorate([
  19321. BABYLON.serializeAsVector3()
  19322. ], TransformNode.prototype, "position", void 0);
  19323. return TransformNode;
  19324. }(BABYLON.Node));
  19325. BABYLON.TransformNode = TransformNode;
  19326. })(BABYLON || (BABYLON = {}));
  19327. //# sourceMappingURL=babylon.transformNode.js.map
  19328. var BABYLON;
  19329. (function (BABYLON) {
  19330. /**
  19331. * Class used to store all common mesh properties
  19332. */
  19333. var AbstractMesh = /** @class */ (function (_super) {
  19334. __extends(AbstractMesh, _super);
  19335. // Constructor
  19336. /**
  19337. * Creates a new AbstractMesh
  19338. * @param name defines the name of the mesh
  19339. * @param scene defines the hosting scene
  19340. */
  19341. function AbstractMesh(name, scene) {
  19342. if (scene === void 0) { scene = null; }
  19343. var _this = _super.call(this, name, scene, false) || this;
  19344. _this._facetNb = 0; // facet number
  19345. _this._partitioningSubdivisions = 10; // number of subdivisions per axis in the partioning space
  19346. _this._partitioningBBoxRatio = 1.01; // the partioning array space is by default 1% bigger than the bounding box
  19347. _this._facetDataEnabled = false; // is the facet data feature enabled on this mesh ?
  19348. _this._facetParameters = {}; // keep a reference to the object parameters to avoid memory re-allocation
  19349. _this._bbSize = BABYLON.Vector3.Zero(); // bbox size approximated for facet data
  19350. _this._subDiv = {
  19351. max: 1,
  19352. X: 1,
  19353. Y: 1,
  19354. Z: 1
  19355. };
  19356. _this._facetDepthSort = false; // is the facet depth sort to be computed
  19357. _this._facetDepthSortEnabled = false; // is the facet depth sort initialized
  19358. // Events
  19359. /**
  19360. * An event triggered when this mesh collides with another one
  19361. */
  19362. _this.onCollideObservable = new BABYLON.Observable();
  19363. /**
  19364. * An event triggered when the collision's position changes
  19365. */
  19366. _this.onCollisionPositionChangeObservable = new BABYLON.Observable();
  19367. /**
  19368. * An event triggered when material is changed
  19369. */
  19370. _this.onMaterialChangedObservable = new BABYLON.Observable();
  19371. // Properties
  19372. /**
  19373. * Gets or sets the orientation for POV movement & rotation
  19374. */
  19375. _this.definedFacingForward = true;
  19376. /**
  19377. * This property determines the type of occlusion query algorithm to run in WebGl, you can use:
  19378. * * AbstractMesh.OCCLUSION_ALGORITHM_TYPE_ACCURATE which is mapped to GL_ANY_SAMPLES_PASSED.
  19379. * * 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.
  19380. * @see http://doc.babylonjs.com/features/occlusionquery
  19381. */
  19382. _this.occlusionQueryAlgorithmType = AbstractMesh.OCCLUSION_ALGORITHM_TYPE_CONSERVATIVE;
  19383. /**
  19384. * 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:
  19385. * * OCCLUSION_TYPE_NONE (Default Value): this option means no occlusion query whith the Mesh.
  19386. * * OCCLUSION_TYPE_OPTIMISTIC: this option is means use occlusion query and if occlusionRetryCount is reached and the query is broken show the mesh.
  19387. * * 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.
  19388. * @see http://doc.babylonjs.com/features/occlusionquery
  19389. */
  19390. _this.occlusionType = AbstractMesh.OCCLUSION_TYPE_NONE;
  19391. /**
  19392. * 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.
  19393. * The default value is -1 which means don't break the query and wait till the result
  19394. * @see http://doc.babylonjs.com/features/occlusionquery
  19395. */
  19396. _this.occlusionRetryCount = -1;
  19397. _this._occlusionInternalRetryCounter = 0;
  19398. _this._isOccluded = false;
  19399. _this._isOcclusionQueryInProgress = false;
  19400. _this._visibility = 1.0;
  19401. /** Gets or sets the alpha index used to sort transparent meshes
  19402. * @see http://doc.babylonjs.com/resources/transparency_and_how_meshes_are_rendered#alpha-index
  19403. */
  19404. _this.alphaIndex = Number.MAX_VALUE;
  19405. /**
  19406. * Gets or sets a boolean indicating if the mesh is visible (renderable). Default is true
  19407. */
  19408. _this.isVisible = true;
  19409. /**
  19410. * Gets or sets a boolean indicating if the mesh can be picked (by scene.pick for instance or through actions). Default is true
  19411. */
  19412. _this.isPickable = true;
  19413. /**
  19414. * Gets or sets a boolean indicating if the bounding box must be rendered as well (false by default)
  19415. */
  19416. _this.showBoundingBox = false;
  19417. /** Gets or sets a boolean indicating that bounding boxes of subMeshes must be rendered as well (false by default) */
  19418. _this.showSubMeshesBoundingBox = false;
  19419. /** Gets or sets a boolean indicating if the mesh must be considered as a ray blocker for lens flares (false by default)
  19420. * @see http://doc.babylonjs.com/how_to/how_to_use_lens_flares
  19421. */
  19422. _this.isBlocker = false;
  19423. /**
  19424. * Gets or sets a boolean indicating that pointer move events must be supported on this mesh (false by default)
  19425. */
  19426. _this.enablePointerMoveEvents = false;
  19427. /**
  19428. * Specifies the rendering group id for this mesh (0 by default)
  19429. * @see http://doc.babylonjs.com/resources/transparency_and_how_meshes_are_rendered#rendering-groups
  19430. */
  19431. _this.renderingGroupId = 0;
  19432. _this._receiveShadows = false;
  19433. /**
  19434. * Gets or sets a boolean indicating if the outline must be rendered as well
  19435. * @see https://www.babylonjs-playground.com/#10WJ5S#3
  19436. */
  19437. _this.renderOutline = false;
  19438. /** Defines color to use when rendering outline */
  19439. _this.outlineColor = BABYLON.Color3.Red();
  19440. /** Define width to use when rendering outline */
  19441. _this.outlineWidth = 0.02;
  19442. /**
  19443. * Gets or sets a boolean indicating if the overlay must be rendered as well
  19444. * @see https://www.babylonjs-playground.com/#10WJ5S#2
  19445. */
  19446. _this.renderOverlay = false;
  19447. /** Defines color to use when rendering overlay */
  19448. _this.overlayColor = BABYLON.Color3.Red();
  19449. /** Defines alpha to use when rendering overlay */
  19450. _this.overlayAlpha = 0.5;
  19451. _this._hasVertexAlpha = false;
  19452. _this._useVertexColors = true;
  19453. _this._computeBonesUsingShaders = true;
  19454. _this._numBoneInfluencers = 4;
  19455. _this._applyFog = true;
  19456. /** Gets or sets a boolean indicating that internal octree (if available) can be used to boost submeshes selection (true by default) */
  19457. _this.useOctreeForRenderingSelection = true;
  19458. /** Gets or sets a boolean indicating that internal octree (if available) can be used to boost submeshes picking (true by default) */
  19459. _this.useOctreeForPicking = true;
  19460. /** Gets or sets a boolean indicating that internal octree (if available) can be used to boost submeshes collision (true by default) */
  19461. _this.useOctreeForCollisions = true;
  19462. _this._layerMask = 0x0FFFFFFF;
  19463. /**
  19464. * True if the mesh must be rendered in any case (this will shortcut the frustum clipping phase)
  19465. */
  19466. _this.alwaysSelectAsActiveMesh = false;
  19467. /**
  19468. * Gets or sets the current action manager
  19469. * @see http://doc.babylonjs.com/how_to/how_to_use_actions
  19470. */
  19471. _this.actionManager = null;
  19472. /**
  19473. * Gets or sets impostor used for physic simulation
  19474. * @see http://doc.babylonjs.com/features/physics_engine
  19475. */
  19476. _this.physicsImpostor = null;
  19477. // Collisions
  19478. _this._checkCollisions = false;
  19479. _this._collisionMask = -1;
  19480. _this._collisionGroup = -1;
  19481. /**
  19482. * Gets or sets the ellipsoid used to impersonate this mesh when using collision engine (default is (0.5, 1, 0.5))
  19483. * @see http://doc.babylonjs.com/babylon101/cameras,_mesh_collisions_and_gravity
  19484. */
  19485. _this.ellipsoid = new BABYLON.Vector3(0.5, 1, 0.5);
  19486. /**
  19487. * Gets or sets the ellipsoid offset used to impersonate this mesh when using collision engine (default is (0, 0, 0))
  19488. * @see http://doc.babylonjs.com/babylon101/cameras,_mesh_collisions_and_gravity
  19489. */
  19490. _this.ellipsoidOffset = new BABYLON.Vector3(0, 0, 0);
  19491. _this._oldPositionForCollisions = new BABYLON.Vector3(0, 0, 0);
  19492. _this._diffPositionForCollisions = new BABYLON.Vector3(0, 0, 0);
  19493. // Edges
  19494. /**
  19495. * Defines edge width used when edgesRenderer is enabled
  19496. * @see https://www.babylonjs-playground.com/#10OJSG#13
  19497. */
  19498. _this.edgesWidth = 1;
  19499. /**
  19500. * Defines edge color used when edgesRenderer is enabled
  19501. * @see https://www.babylonjs-playground.com/#10OJSG#13
  19502. */
  19503. _this.edgesColor = new BABYLON.Color4(1, 0, 0, 1);
  19504. // Cache
  19505. _this._collisionsTransformMatrix = BABYLON.Matrix.Zero();
  19506. _this._collisionsScalingMatrix = BABYLON.Matrix.Zero();
  19507. /** @hidden */
  19508. _this._renderId = 0;
  19509. /** @hidden */
  19510. _this._intersectionsInProgress = new Array();
  19511. /** @hidden */
  19512. _this._unIndexed = false;
  19513. /** @hidden */
  19514. _this._lightSources = new Array();
  19515. _this._onCollisionPositionChange = function (collisionId, newPosition, collidedMesh) {
  19516. if (collidedMesh === void 0) { collidedMesh = null; }
  19517. //TODO move this to the collision coordinator!
  19518. if (_this.getScene().workerCollisions)
  19519. newPosition.multiplyInPlace(_this._collider._radius);
  19520. newPosition.subtractToRef(_this._oldPositionForCollisions, _this._diffPositionForCollisions);
  19521. if (_this._diffPositionForCollisions.length() > BABYLON.Engine.CollisionsEpsilon) {
  19522. _this.position.addInPlace(_this._diffPositionForCollisions);
  19523. }
  19524. if (collidedMesh) {
  19525. _this.onCollideObservable.notifyObservers(collidedMesh);
  19526. }
  19527. _this.onCollisionPositionChangeObservable.notifyObservers(_this.position);
  19528. };
  19529. _this.getScene().addMesh(_this);
  19530. _this._resyncLightSources();
  19531. return _this;
  19532. }
  19533. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_NONE", {
  19534. /**
  19535. * No billboard
  19536. */
  19537. get: function () {
  19538. return BABYLON.TransformNode.BILLBOARDMODE_NONE;
  19539. },
  19540. enumerable: true,
  19541. configurable: true
  19542. });
  19543. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_X", {
  19544. /** Billboard on X axis */
  19545. get: function () {
  19546. return BABYLON.TransformNode.BILLBOARDMODE_X;
  19547. },
  19548. enumerable: true,
  19549. configurable: true
  19550. });
  19551. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_Y", {
  19552. /** Billboard on Y axis */
  19553. get: function () {
  19554. return BABYLON.TransformNode.BILLBOARDMODE_Y;
  19555. },
  19556. enumerable: true,
  19557. configurable: true
  19558. });
  19559. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_Z", {
  19560. /** Billboard on Z axis */
  19561. get: function () {
  19562. return BABYLON.TransformNode.BILLBOARDMODE_Z;
  19563. },
  19564. enumerable: true,
  19565. configurable: true
  19566. });
  19567. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_ALL", {
  19568. /** Billboard on all axes */
  19569. get: function () {
  19570. return BABYLON.TransformNode.BILLBOARDMODE_ALL;
  19571. },
  19572. enumerable: true,
  19573. configurable: true
  19574. });
  19575. Object.defineProperty(AbstractMesh.prototype, "facetNb", {
  19576. /**
  19577. * Gets the number of facets in the mesh
  19578. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata#what-is-a-mesh-facet
  19579. */
  19580. get: function () {
  19581. return this._facetNb;
  19582. },
  19583. enumerable: true,
  19584. configurable: true
  19585. });
  19586. Object.defineProperty(AbstractMesh.prototype, "partitioningSubdivisions", {
  19587. /**
  19588. * Gets or set the number (integer) of subdivisions per axis in the partioning space
  19589. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata#tweaking-the-partitioning
  19590. */
  19591. get: function () {
  19592. return this._partitioningSubdivisions;
  19593. },
  19594. set: function (nb) {
  19595. this._partitioningSubdivisions = nb;
  19596. },
  19597. enumerable: true,
  19598. configurable: true
  19599. });
  19600. Object.defineProperty(AbstractMesh.prototype, "partitioningBBoxRatio", {
  19601. /**
  19602. * The ratio (float) to apply to the bouding box size to set to the partioning space.
  19603. * Ex : 1.01 (default) the partioning space is 1% bigger than the bounding box
  19604. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata#tweaking-the-partitioning
  19605. */
  19606. get: function () {
  19607. return this._partitioningBBoxRatio;
  19608. },
  19609. set: function (ratio) {
  19610. this._partitioningBBoxRatio = ratio;
  19611. },
  19612. enumerable: true,
  19613. configurable: true
  19614. });
  19615. Object.defineProperty(AbstractMesh.prototype, "mustDepthSortFacets", {
  19616. /**
  19617. * Gets or sets a boolean indicating that the facets must be depth sorted on next call to `updateFacetData()`.
  19618. * Works only for updatable meshes.
  19619. * Doesn't work with multi-materials
  19620. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata#facet-depth-sort
  19621. */
  19622. get: function () {
  19623. return this._facetDepthSort;
  19624. },
  19625. set: function (sort) {
  19626. this._facetDepthSort = sort;
  19627. },
  19628. enumerable: true,
  19629. configurable: true
  19630. });
  19631. Object.defineProperty(AbstractMesh.prototype, "facetDepthSortFrom", {
  19632. /**
  19633. * The location (Vector3) where the facet depth sort must be computed from.
  19634. * By default, the active camera position.
  19635. * Used only when facet depth sort is enabled
  19636. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata#facet-depth-sort
  19637. */
  19638. get: function () {
  19639. return this._facetDepthSortFrom;
  19640. },
  19641. set: function (location) {
  19642. this._facetDepthSortFrom = location;
  19643. },
  19644. enumerable: true,
  19645. configurable: true
  19646. });
  19647. Object.defineProperty(AbstractMesh.prototype, "isFacetDataEnabled", {
  19648. /**
  19649. * gets a boolean indicating if facetData is enabled
  19650. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata#what-is-a-mesh-facet
  19651. */
  19652. get: function () {
  19653. return this._facetDataEnabled;
  19654. },
  19655. enumerable: true,
  19656. configurable: true
  19657. });
  19658. /** @hidden */
  19659. AbstractMesh.prototype._updateNonUniformScalingState = function (value) {
  19660. if (!_super.prototype._updateNonUniformScalingState.call(this, value)) {
  19661. return false;
  19662. }
  19663. this._markSubMeshesAsMiscDirty();
  19664. return true;
  19665. };
  19666. Object.defineProperty(AbstractMesh.prototype, "onCollide", {
  19667. /** Set a function to call when this mesh collides with another one */
  19668. set: function (callback) {
  19669. if (this._onCollideObserver) {
  19670. this.onCollideObservable.remove(this._onCollideObserver);
  19671. }
  19672. this._onCollideObserver = this.onCollideObservable.add(callback);
  19673. },
  19674. enumerable: true,
  19675. configurable: true
  19676. });
  19677. Object.defineProperty(AbstractMesh.prototype, "onCollisionPositionChange", {
  19678. /** Set a function to call when the collision's position changes */
  19679. set: function (callback) {
  19680. if (this._onCollisionPositionChangeObserver) {
  19681. this.onCollisionPositionChangeObservable.remove(this._onCollisionPositionChangeObserver);
  19682. }
  19683. this._onCollisionPositionChangeObserver = this.onCollisionPositionChangeObservable.add(callback);
  19684. },
  19685. enumerable: true,
  19686. configurable: true
  19687. });
  19688. Object.defineProperty(AbstractMesh.prototype, "isOccluded", {
  19689. /**
  19690. * 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
  19691. * @see http://doc.babylonjs.com/features/occlusionquery
  19692. */
  19693. get: function () {
  19694. return this._isOccluded;
  19695. },
  19696. set: function (value) {
  19697. this._isOccluded = value;
  19698. },
  19699. enumerable: true,
  19700. configurable: true
  19701. });
  19702. Object.defineProperty(AbstractMesh.prototype, "isOcclusionQueryInProgress", {
  19703. /**
  19704. * Flag to check the progress status of the query
  19705. * @see http://doc.babylonjs.com/features/occlusionquery
  19706. */
  19707. get: function () {
  19708. return this._isOcclusionQueryInProgress;
  19709. },
  19710. enumerable: true,
  19711. configurable: true
  19712. });
  19713. Object.defineProperty(AbstractMesh.prototype, "visibility", {
  19714. /**
  19715. * Gets or sets mesh visibility between 0 and 1 (default is 1)
  19716. */
  19717. get: function () {
  19718. return this._visibility;
  19719. },
  19720. /**
  19721. * Gets or sets mesh visibility between 0 and 1 (default is 1)
  19722. */
  19723. set: function (value) {
  19724. if (this._visibility === value) {
  19725. return;
  19726. }
  19727. this._visibility = value;
  19728. this._markSubMeshesAsMiscDirty();
  19729. },
  19730. enumerable: true,
  19731. configurable: true
  19732. });
  19733. Object.defineProperty(AbstractMesh.prototype, "material", {
  19734. /** Gets or sets current material */
  19735. get: function () {
  19736. return this._material;
  19737. },
  19738. set: function (value) {
  19739. if (this._material === value) {
  19740. return;
  19741. }
  19742. this._material = value;
  19743. if (this.onMaterialChangedObservable.hasObservers) {
  19744. this.onMaterialChangedObservable.notifyObservers(this);
  19745. }
  19746. if (!this.subMeshes) {
  19747. return;
  19748. }
  19749. this._unBindEffect();
  19750. },
  19751. enumerable: true,
  19752. configurable: true
  19753. });
  19754. Object.defineProperty(AbstractMesh.prototype, "receiveShadows", {
  19755. /**
  19756. * Gets or sets a boolean indicating that this mesh can receive realtime shadows
  19757. * @see http://doc.babylonjs.com/babylon101/shadows
  19758. */
  19759. get: function () {
  19760. return this._receiveShadows;
  19761. },
  19762. set: function (value) {
  19763. if (this._receiveShadows === value) {
  19764. return;
  19765. }
  19766. this._receiveShadows = value;
  19767. this._markSubMeshesAsLightDirty();
  19768. },
  19769. enumerable: true,
  19770. configurable: true
  19771. });
  19772. Object.defineProperty(AbstractMesh.prototype, "hasVertexAlpha", {
  19773. /** Gets or sets a boolean indicating that this mesh contains vertex color data with alpha values */
  19774. get: function () {
  19775. return this._hasVertexAlpha;
  19776. },
  19777. set: function (value) {
  19778. if (this._hasVertexAlpha === value) {
  19779. return;
  19780. }
  19781. this._hasVertexAlpha = value;
  19782. this._markSubMeshesAsAttributesDirty();
  19783. this._markSubMeshesAsMiscDirty();
  19784. },
  19785. enumerable: true,
  19786. configurable: true
  19787. });
  19788. Object.defineProperty(AbstractMesh.prototype, "useVertexColors", {
  19789. /** Gets or sets a boolean indicating that this mesh needs to use vertex color data to render (if this kind of vertex data is available in the geometry) */
  19790. get: function () {
  19791. return this._useVertexColors;
  19792. },
  19793. set: function (value) {
  19794. if (this._useVertexColors === value) {
  19795. return;
  19796. }
  19797. this._useVertexColors = value;
  19798. this._markSubMeshesAsAttributesDirty();
  19799. },
  19800. enumerable: true,
  19801. configurable: true
  19802. });
  19803. Object.defineProperty(AbstractMesh.prototype, "computeBonesUsingShaders", {
  19804. /**
  19805. * Gets or sets a boolean indicating that bone animations must be computed by the CPU (false by default)
  19806. */
  19807. get: function () {
  19808. return this._computeBonesUsingShaders;
  19809. },
  19810. set: function (value) {
  19811. if (this._computeBonesUsingShaders === value) {
  19812. return;
  19813. }
  19814. this._computeBonesUsingShaders = value;
  19815. this._markSubMeshesAsAttributesDirty();
  19816. },
  19817. enumerable: true,
  19818. configurable: true
  19819. });
  19820. Object.defineProperty(AbstractMesh.prototype, "numBoneInfluencers", {
  19821. /** Gets or sets the number of allowed bone influences per vertex (4 by default) */
  19822. get: function () {
  19823. return this._numBoneInfluencers;
  19824. },
  19825. set: function (value) {
  19826. if (this._numBoneInfluencers === value) {
  19827. return;
  19828. }
  19829. this._numBoneInfluencers = value;
  19830. this._markSubMeshesAsAttributesDirty();
  19831. },
  19832. enumerable: true,
  19833. configurable: true
  19834. });
  19835. Object.defineProperty(AbstractMesh.prototype, "applyFog", {
  19836. /** Gets or sets a boolean indicating that this mesh will allow fog to be rendered on it (true by default) */
  19837. get: function () {
  19838. return this._applyFog;
  19839. },
  19840. set: function (value) {
  19841. if (this._applyFog === value) {
  19842. return;
  19843. }
  19844. this._applyFog = value;
  19845. this._markSubMeshesAsMiscDirty();
  19846. },
  19847. enumerable: true,
  19848. configurable: true
  19849. });
  19850. Object.defineProperty(AbstractMesh.prototype, "layerMask", {
  19851. /**
  19852. * Gets or sets the current layer mask (default is 0x0FFFFFFF)
  19853. * @see http://doc.babylonjs.com/how_to/layermasks_and_multi-cam_textures
  19854. */
  19855. get: function () {
  19856. return this._layerMask;
  19857. },
  19858. set: function (value) {
  19859. if (value === this._layerMask) {
  19860. return;
  19861. }
  19862. this._layerMask = value;
  19863. this._resyncLightSources();
  19864. },
  19865. enumerable: true,
  19866. configurable: true
  19867. });
  19868. Object.defineProperty(AbstractMesh.prototype, "collisionMask", {
  19869. /**
  19870. * Gets or sets a collision mask used to mask collisions (default is -1).
  19871. * A collision between A and B will happen if A.collisionGroup & b.collisionMask !== 0
  19872. */
  19873. get: function () {
  19874. return this._collisionMask;
  19875. },
  19876. set: function (mask) {
  19877. this._collisionMask = !isNaN(mask) ? mask : -1;
  19878. },
  19879. enumerable: true,
  19880. configurable: true
  19881. });
  19882. Object.defineProperty(AbstractMesh.prototype, "collisionGroup", {
  19883. /**
  19884. * Gets or sets the current collision group mask (-1 by default).
  19885. * A collision between A and B will happen if A.collisionGroup & b.collisionMask !== 0
  19886. */
  19887. get: function () {
  19888. return this._collisionGroup;
  19889. },
  19890. set: function (mask) {
  19891. this._collisionGroup = !isNaN(mask) ? mask : -1;
  19892. },
  19893. enumerable: true,
  19894. configurable: true
  19895. });
  19896. Object.defineProperty(AbstractMesh.prototype, "_positions", {
  19897. /** @hidden */
  19898. get: function () {
  19899. return null;
  19900. },
  19901. enumerable: true,
  19902. configurable: true
  19903. });
  19904. Object.defineProperty(AbstractMesh.prototype, "skeleton", {
  19905. get: function () {
  19906. return this._skeleton;
  19907. },
  19908. /**
  19909. * Gets or sets a skeleton to apply skining transformations
  19910. * @see http://doc.babylonjs.com/how_to/how_to_use_bones_and_skeletons
  19911. */
  19912. set: function (value) {
  19913. if (this._skeleton && this._skeleton.needInitialSkinMatrix) {
  19914. this._skeleton._unregisterMeshWithPoseMatrix(this);
  19915. }
  19916. if (value && value.needInitialSkinMatrix) {
  19917. value._registerMeshWithPoseMatrix(this);
  19918. }
  19919. this._skeleton = value;
  19920. if (!this._skeleton) {
  19921. this._bonesTransformMatrices = null;
  19922. }
  19923. this._markSubMeshesAsAttributesDirty();
  19924. },
  19925. enumerable: true,
  19926. configurable: true
  19927. });
  19928. /**
  19929. * Returns the string "AbstractMesh"
  19930. * @returns "AbstractMesh"
  19931. */
  19932. AbstractMesh.prototype.getClassName = function () {
  19933. return "AbstractMesh";
  19934. };
  19935. /**
  19936. * Gets a string representation of the current mesh
  19937. * @param fullDetails defines a boolean indicating if full details must be included
  19938. * @returns a string representation of the current mesh
  19939. */
  19940. AbstractMesh.prototype.toString = function (fullDetails) {
  19941. var ret = "Name: " + this.name + ", isInstance: " + (this instanceof BABYLON.InstancedMesh ? "YES" : "NO");
  19942. ret += ", # of submeshes: " + (this.subMeshes ? this.subMeshes.length : 0);
  19943. if (this._skeleton) {
  19944. ret += ", skeleton: " + this._skeleton.name;
  19945. }
  19946. if (fullDetails) {
  19947. ret += ", billboard mode: " + (["NONE", "X", "Y", null, "Z", null, null, "ALL"])[this.billboardMode];
  19948. ret += ", freeze wrld mat: " + (this._isWorldMatrixFrozen || this._waitingFreezeWorldMatrix ? "YES" : "NO");
  19949. }
  19950. return ret;
  19951. };
  19952. /** @hidden */
  19953. AbstractMesh.prototype._rebuild = function () {
  19954. if (this._occlusionQuery) {
  19955. this._occlusionQuery = null;
  19956. }
  19957. if (this._edgesRenderer) {
  19958. this._edgesRenderer._rebuild();
  19959. }
  19960. if (!this.subMeshes) {
  19961. return;
  19962. }
  19963. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  19964. var subMesh = _a[_i];
  19965. subMesh._rebuild();
  19966. }
  19967. };
  19968. /** @hidden */
  19969. AbstractMesh.prototype._resyncLightSources = function () {
  19970. this._lightSources.length = 0;
  19971. for (var _i = 0, _a = this.getScene().lights; _i < _a.length; _i++) {
  19972. var light = _a[_i];
  19973. if (!light.isEnabled()) {
  19974. continue;
  19975. }
  19976. if (light.canAffectMesh(this)) {
  19977. this._lightSources.push(light);
  19978. }
  19979. }
  19980. this._markSubMeshesAsLightDirty();
  19981. };
  19982. /** @hidden */
  19983. AbstractMesh.prototype._resyncLighSource = function (light) {
  19984. var isIn = light.isEnabled() && light.canAffectMesh(this);
  19985. var index = this._lightSources.indexOf(light);
  19986. if (index === -1) {
  19987. if (!isIn) {
  19988. return;
  19989. }
  19990. this._lightSources.push(light);
  19991. }
  19992. else {
  19993. if (isIn) {
  19994. return;
  19995. }
  19996. this._lightSources.splice(index, 1);
  19997. }
  19998. this._markSubMeshesAsLightDirty();
  19999. };
  20000. /** @hidden */
  20001. AbstractMesh.prototype._unBindEffect = function () {
  20002. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  20003. var subMesh = _a[_i];
  20004. subMesh.setEffect(null);
  20005. }
  20006. };
  20007. /** @hidden */
  20008. AbstractMesh.prototype._removeLightSource = function (light) {
  20009. var index = this._lightSources.indexOf(light);
  20010. if (index === -1) {
  20011. return;
  20012. }
  20013. this._lightSources.splice(index, 1);
  20014. this._markSubMeshesAsLightDirty();
  20015. };
  20016. AbstractMesh.prototype._markSubMeshesAsDirty = function (func) {
  20017. if (!this.subMeshes) {
  20018. return;
  20019. }
  20020. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  20021. var subMesh = _a[_i];
  20022. if (subMesh._materialDefines) {
  20023. func(subMesh._materialDefines);
  20024. }
  20025. }
  20026. };
  20027. /** @hidden */
  20028. AbstractMesh.prototype._markSubMeshesAsLightDirty = function () {
  20029. this._markSubMeshesAsDirty(function (defines) { return defines.markAsLightDirty(); });
  20030. };
  20031. /** @hidden */
  20032. AbstractMesh.prototype._markSubMeshesAsAttributesDirty = function () {
  20033. this._markSubMeshesAsDirty(function (defines) { return defines.markAsAttributesDirty(); });
  20034. };
  20035. /** @hidden */
  20036. AbstractMesh.prototype._markSubMeshesAsMiscDirty = function () {
  20037. if (!this.subMeshes) {
  20038. return;
  20039. }
  20040. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  20041. var subMesh = _a[_i];
  20042. var material = subMesh.getMaterial();
  20043. if (material) {
  20044. material.markAsDirty(BABYLON.Material.MiscDirtyFlag);
  20045. }
  20046. }
  20047. };
  20048. Object.defineProperty(AbstractMesh.prototype, "scaling", {
  20049. /**
  20050. * Gets or sets a Vector3 depicting the mesh scaling along each local axis X, Y, Z. Default is (1.0, 1.0, 1.0)
  20051. */
  20052. get: function () {
  20053. return this._scaling;
  20054. },
  20055. set: function (newScaling) {
  20056. this._scaling = newScaling;
  20057. if (this.physicsImpostor) {
  20058. this.physicsImpostor.forceUpdate();
  20059. }
  20060. },
  20061. enumerable: true,
  20062. configurable: true
  20063. });
  20064. // Methods
  20065. /**
  20066. * Disables the mesh edge rendering mode
  20067. * @returns the currentAbstractMesh
  20068. */
  20069. AbstractMesh.prototype.disableEdgesRendering = function () {
  20070. if (this._edgesRenderer) {
  20071. this._edgesRenderer.dispose();
  20072. this._edgesRenderer = null;
  20073. }
  20074. return this;
  20075. };
  20076. /**
  20077. * Enables the edge rendering mode on the mesh.
  20078. * This mode makes the mesh edges visible
  20079. * @param epsilon defines the maximal distance between two angles to detect a face
  20080. * @param checkVerticesInsteadOfIndices indicates that we should check vertex list directly instead of faces
  20081. * @returns the currentAbstractMesh
  20082. * @see https://www.babylonjs-playground.com/#19O9TU#0
  20083. */
  20084. AbstractMesh.prototype.enableEdgesRendering = function (epsilon, checkVerticesInsteadOfIndices) {
  20085. if (epsilon === void 0) { epsilon = 0.95; }
  20086. if (checkVerticesInsteadOfIndices === void 0) { checkVerticesInsteadOfIndices = false; }
  20087. this.disableEdgesRendering();
  20088. this._edgesRenderer = new BABYLON.EdgesRenderer(this, epsilon, checkVerticesInsteadOfIndices);
  20089. return this;
  20090. };
  20091. Object.defineProperty(AbstractMesh.prototype, "isBlocked", {
  20092. /**
  20093. * Returns true if the mesh is blocked. Implemented by child classes
  20094. */
  20095. get: function () {
  20096. return false;
  20097. },
  20098. enumerable: true,
  20099. configurable: true
  20100. });
  20101. /**
  20102. * Returns the mesh itself by default. Implemented by child classes
  20103. * @param camera defines the camera to use to pick the right LOD level
  20104. * @returns the currentAbstractMesh
  20105. */
  20106. AbstractMesh.prototype.getLOD = function (camera) {
  20107. return this;
  20108. };
  20109. /**
  20110. * Returns 0 by default. Implemented by child classes
  20111. * @returns an integer
  20112. */
  20113. AbstractMesh.prototype.getTotalVertices = function () {
  20114. return 0;
  20115. };
  20116. /**
  20117. * Returns null by default. Implemented by child classes
  20118. * @returns null
  20119. */
  20120. AbstractMesh.prototype.getIndices = function () {
  20121. return null;
  20122. };
  20123. /**
  20124. * Returns the array of the requested vertex data kind. Implemented by child classes
  20125. * @param kind defines the vertex data kind to use
  20126. * @returns null
  20127. */
  20128. AbstractMesh.prototype.getVerticesData = function (kind) {
  20129. return null;
  20130. };
  20131. /**
  20132. * Sets the vertex data of the mesh geometry for the requested `kind`.
  20133. * If the mesh has no geometry, a new Geometry object is set to the mesh and then passed this vertex data.
  20134. * Note that a new underlying VertexBuffer object is created each call.
  20135. * If the `kind` is the `PositionKind`, the mesh BoundingInfo is renewed, so the bounding box and sphere, and the mesh World Matrix is recomputed.
  20136. * @param kind defines vertex data kind:
  20137. * * BABYLON.VertexBuffer.PositionKind
  20138. * * BABYLON.VertexBuffer.UVKind
  20139. * * BABYLON.VertexBuffer.UV2Kind
  20140. * * BABYLON.VertexBuffer.UV3Kind
  20141. * * BABYLON.VertexBuffer.UV4Kind
  20142. * * BABYLON.VertexBuffer.UV5Kind
  20143. * * BABYLON.VertexBuffer.UV6Kind
  20144. * * BABYLON.VertexBuffer.ColorKind
  20145. * * BABYLON.VertexBuffer.MatricesIndicesKind
  20146. * * BABYLON.VertexBuffer.MatricesIndicesExtraKind
  20147. * * BABYLON.VertexBuffer.MatricesWeightsKind
  20148. * * BABYLON.VertexBuffer.MatricesWeightsExtraKind
  20149. * @param data defines the data source
  20150. * @param updatable defines if the data must be flagged as updatable (or static)
  20151. * @param stride defines the vertex stride (size of an entire vertex). Can be null and in this case will be deduced from vertex data kind
  20152. * @returns the current mesh
  20153. */
  20154. AbstractMesh.prototype.setVerticesData = function (kind, data, updatable, stride) {
  20155. return this;
  20156. };
  20157. /**
  20158. * Updates the existing vertex data of the mesh geometry for the requested `kind`.
  20159. * If the mesh has no geometry, it is simply returned as it is.
  20160. * @param kind defines vertex data kind:
  20161. * * BABYLON.VertexBuffer.PositionKind
  20162. * * BABYLON.VertexBuffer.UVKind
  20163. * * BABYLON.VertexBuffer.UV2Kind
  20164. * * BABYLON.VertexBuffer.UV3Kind
  20165. * * BABYLON.VertexBuffer.UV4Kind
  20166. * * BABYLON.VertexBuffer.UV5Kind
  20167. * * BABYLON.VertexBuffer.UV6Kind
  20168. * * BABYLON.VertexBuffer.ColorKind
  20169. * * BABYLON.VertexBuffer.MatricesIndicesKind
  20170. * * BABYLON.VertexBuffer.MatricesIndicesExtraKind
  20171. * * BABYLON.VertexBuffer.MatricesWeightsKind
  20172. * * BABYLON.VertexBuffer.MatricesWeightsExtraKind
  20173. * @param data defines the data source
  20174. * @param updateExtends If `kind` is `PositionKind` and if `updateExtends` is true, the mesh BoundingInfo is renewed, so the bounding box and sphere, and the mesh World Matrix is recomputed
  20175. * @param makeItUnique If true, a new global geometry is created from this data and is set to the mesh
  20176. * @returns the current mesh
  20177. */
  20178. AbstractMesh.prototype.updateVerticesData = function (kind, data, updateExtends, makeItUnique) {
  20179. return this;
  20180. };
  20181. /**
  20182. * Sets the mesh indices,
  20183. * If the mesh has no geometry, a new Geometry object is created and set to the mesh.
  20184. * @param indices Expects an array populated with integers or a typed array (Int32Array, Uint32Array, Uint16Array)
  20185. * @param totalVertices Defines the total number of vertices
  20186. * @returns the current mesh
  20187. */
  20188. AbstractMesh.prototype.setIndices = function (indices, totalVertices) {
  20189. return this;
  20190. };
  20191. /**
  20192. * Gets a boolean indicating if specific vertex data is present
  20193. * @param kind defines the vertex data kind to use
  20194. * @returns true is data kind is present
  20195. */
  20196. AbstractMesh.prototype.isVerticesDataPresent = function (kind) {
  20197. return false;
  20198. };
  20199. /**
  20200. * Returns the mesh BoundingInfo object or creates a new one and returns if it was undefined
  20201. * @returns a BoundingInfo
  20202. */
  20203. AbstractMesh.prototype.getBoundingInfo = function () {
  20204. if (this._masterMesh) {
  20205. return this._masterMesh.getBoundingInfo();
  20206. }
  20207. if (!this._boundingInfo) {
  20208. // this._boundingInfo is being created here
  20209. this._updateBoundingInfo();
  20210. }
  20211. // cannot be null.
  20212. return this._boundingInfo;
  20213. };
  20214. /**
  20215. * Uniformly scales the mesh to fit inside of a unit cube (1 X 1 X 1 units)
  20216. * @param includeDescendants Use the hierarchy's bounding box instead of the mesh's bounding box
  20217. * @returns the current mesh
  20218. */
  20219. AbstractMesh.prototype.normalizeToUnitCube = function (includeDescendants) {
  20220. if (includeDescendants === void 0) { includeDescendants = true; }
  20221. var boundingVectors = this.getHierarchyBoundingVectors(includeDescendants);
  20222. var sizeVec = boundingVectors.max.subtract(boundingVectors.min);
  20223. var maxDimension = Math.max(sizeVec.x, sizeVec.y, sizeVec.z);
  20224. if (maxDimension === 0) {
  20225. return this;
  20226. }
  20227. var scale = 1 / maxDimension;
  20228. this.scaling.scaleInPlace(scale);
  20229. return this;
  20230. };
  20231. /**
  20232. * Overwrite the current bounding info
  20233. * @param boundingInfo defines the new bounding info
  20234. * @returns the current mesh
  20235. */
  20236. AbstractMesh.prototype.setBoundingInfo = function (boundingInfo) {
  20237. this._boundingInfo = boundingInfo;
  20238. return this;
  20239. };
  20240. Object.defineProperty(AbstractMesh.prototype, "useBones", {
  20241. /** Gets a boolean indicating if this mesh has skinning data and an attached skeleton */
  20242. get: function () {
  20243. return (this.skeleton && this.getScene().skeletonsEnabled && this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind) && this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind));
  20244. },
  20245. enumerable: true,
  20246. configurable: true
  20247. });
  20248. /** @hidden */
  20249. AbstractMesh.prototype._preActivate = function () {
  20250. };
  20251. /** @hidden */
  20252. AbstractMesh.prototype._preActivateForIntermediateRendering = function (renderId) {
  20253. };
  20254. /** @hidden */
  20255. AbstractMesh.prototype._activate = function (renderId) {
  20256. this._renderId = renderId;
  20257. };
  20258. /**
  20259. * Gets the current world matrix
  20260. * @returns a Matrix
  20261. */
  20262. AbstractMesh.prototype.getWorldMatrix = function () {
  20263. if (this._masterMesh) {
  20264. return this._masterMesh.getWorldMatrix();
  20265. }
  20266. return _super.prototype.getWorldMatrix.call(this);
  20267. };
  20268. /** @hidden */
  20269. AbstractMesh.prototype._getWorldMatrixDeterminant = function () {
  20270. if (this._masterMesh) {
  20271. return this._masterMesh._getWorldMatrixDeterminant();
  20272. }
  20273. return _super.prototype._getWorldMatrixDeterminant.call(this);
  20274. };
  20275. // ================================== Point of View Movement =================================
  20276. /**
  20277. * Perform relative position change from the point of view of behind the front of the mesh.
  20278. * This is performed taking into account the meshes current rotation, so you do not have to care.
  20279. * Supports definition of mesh facing forward or backward
  20280. * @param amountRight defines the distance on the right axis
  20281. * @param amountUp defines the distance on the up axis
  20282. * @param amountForward defines the distance on the forward axis
  20283. * @returns the current mesh
  20284. */
  20285. AbstractMesh.prototype.movePOV = function (amountRight, amountUp, amountForward) {
  20286. this.position.addInPlace(this.calcMovePOV(amountRight, amountUp, amountForward));
  20287. return this;
  20288. };
  20289. /**
  20290. * Calculate relative position change from the point of view of behind the front of the mesh.
  20291. * This is performed taking into account the meshes current rotation, so you do not have to care.
  20292. * Supports definition of mesh facing forward or backward
  20293. * @param amountRight defines the distance on the right axis
  20294. * @param amountUp defines the distance on the up axis
  20295. * @param amountForward defines the distance on the forward axis
  20296. * @returns the new displacement vector
  20297. */
  20298. AbstractMesh.prototype.calcMovePOV = function (amountRight, amountUp, amountForward) {
  20299. var rotMatrix = new BABYLON.Matrix();
  20300. var rotQuaternion = (this.rotationQuaternion) ? this.rotationQuaternion : BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z);
  20301. rotQuaternion.toRotationMatrix(rotMatrix);
  20302. var translationDelta = BABYLON.Vector3.Zero();
  20303. var defForwardMult = this.definedFacingForward ? -1 : 1;
  20304. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(amountRight * defForwardMult, amountUp, amountForward * defForwardMult, rotMatrix, translationDelta);
  20305. return translationDelta;
  20306. };
  20307. // ================================== Point of View Rotation =================================
  20308. /**
  20309. * Perform relative rotation change from the point of view of behind the front of the mesh.
  20310. * Supports definition of mesh facing forward or backward
  20311. * @param flipBack defines the flip
  20312. * @param twirlClockwise defines the twirl
  20313. * @param tiltRight defines the tilt
  20314. * @returns the current mesh
  20315. */
  20316. AbstractMesh.prototype.rotatePOV = function (flipBack, twirlClockwise, tiltRight) {
  20317. this.rotation.addInPlace(this.calcRotatePOV(flipBack, twirlClockwise, tiltRight));
  20318. return this;
  20319. };
  20320. /**
  20321. * Calculate relative rotation change from the point of view of behind the front of the mesh.
  20322. * Supports definition of mesh facing forward or backward.
  20323. * @param flipBack defines the flip
  20324. * @param twirlClockwise defines the twirl
  20325. * @param tiltRight defines the tilt
  20326. * @returns the new rotation vector
  20327. */
  20328. AbstractMesh.prototype.calcRotatePOV = function (flipBack, twirlClockwise, tiltRight) {
  20329. var defForwardMult = this.definedFacingForward ? 1 : -1;
  20330. return new BABYLON.Vector3(flipBack * defForwardMult, twirlClockwise, tiltRight * defForwardMult);
  20331. };
  20332. /**
  20333. * Return the minimum and maximum world vectors of the entire hierarchy under current mesh
  20334. * @param includeDescendants Include bounding info from descendants as well (true by default)
  20335. * @returns the new bounding vectors
  20336. */
  20337. AbstractMesh.prototype.getHierarchyBoundingVectors = function (includeDescendants) {
  20338. if (includeDescendants === void 0) { includeDescendants = true; }
  20339. this.computeWorldMatrix(true);
  20340. var min;
  20341. var max;
  20342. var boundingInfo = this.getBoundingInfo();
  20343. if (!this.subMeshes) {
  20344. min = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  20345. max = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  20346. }
  20347. else {
  20348. min = boundingInfo.boundingBox.minimumWorld;
  20349. max = boundingInfo.boundingBox.maximumWorld;
  20350. }
  20351. if (includeDescendants) {
  20352. var descendants = this.getDescendants(false);
  20353. for (var _i = 0, descendants_1 = descendants; _i < descendants_1.length; _i++) {
  20354. var descendant = descendants_1[_i];
  20355. var childMesh = descendant;
  20356. childMesh.computeWorldMatrix(true);
  20357. //make sure we have the needed params to get mix and max
  20358. if (!childMesh.getBoundingInfo || childMesh.getTotalVertices() === 0) {
  20359. continue;
  20360. }
  20361. var childBoundingInfo = childMesh.getBoundingInfo();
  20362. var boundingBox = childBoundingInfo.boundingBox;
  20363. var minBox = boundingBox.minimumWorld;
  20364. var maxBox = boundingBox.maximumWorld;
  20365. BABYLON.Tools.CheckExtends(minBox, min, max);
  20366. BABYLON.Tools.CheckExtends(maxBox, min, max);
  20367. }
  20368. }
  20369. return {
  20370. min: min,
  20371. max: max
  20372. };
  20373. };
  20374. /** @hidden */
  20375. AbstractMesh.prototype._updateBoundingInfo = function () {
  20376. this._boundingInfo = this._boundingInfo || new BABYLON.BoundingInfo(this.absolutePosition, this.absolutePosition);
  20377. this._boundingInfo.update(this.worldMatrixFromCache);
  20378. this._updateSubMeshesBoundingInfo(this.worldMatrixFromCache);
  20379. return this;
  20380. };
  20381. /** @hidden */
  20382. AbstractMesh.prototype._updateSubMeshesBoundingInfo = function (matrix) {
  20383. if (!this.subMeshes) {
  20384. return this;
  20385. }
  20386. for (var subIndex = 0; subIndex < this.subMeshes.length; subIndex++) {
  20387. var subMesh = this.subMeshes[subIndex];
  20388. if (!subMesh.IsGlobal) {
  20389. subMesh.updateBoundingInfo(matrix);
  20390. }
  20391. }
  20392. return this;
  20393. };
  20394. /** @hidden */
  20395. AbstractMesh.prototype._afterComputeWorldMatrix = function () {
  20396. // Bounding info
  20397. this._updateBoundingInfo();
  20398. };
  20399. /**
  20400. * Returns `true` if the mesh is within the frustum defined by the passed array of planes.
  20401. * A mesh is in the frustum if its bounding box intersects the frustum
  20402. * @param frustumPlanes defines the frustum to test
  20403. * @returns true if the mesh is in the frustum planes
  20404. */
  20405. AbstractMesh.prototype.isInFrustum = function (frustumPlanes) {
  20406. return this._boundingInfo !== null && this._boundingInfo.isInFrustum(frustumPlanes);
  20407. };
  20408. /**
  20409. * Returns `true` if the mesh is completely in the frustum defined be the passed array of planes.
  20410. * A mesh is completely in the frustum if its bounding box it completely inside the frustum.
  20411. * @param frustumPlanes defines the frustum to test
  20412. * @returns true if the mesh is completely in the frustum planes
  20413. */
  20414. AbstractMesh.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  20415. return this._boundingInfo !== null && this._boundingInfo.isCompletelyInFrustum(frustumPlanes);
  20416. ;
  20417. };
  20418. /**
  20419. * True if the mesh intersects another mesh or a SolidParticle object
  20420. * @param mesh defines a target mesh or SolidParticle to test
  20421. * @param precise Unless the parameter `precise` is set to `true` the intersection is computed according to Axis Aligned Bounding Boxes (AABB), else according to OBB (Oriented BBoxes)
  20422. * @param includeDescendants Can be set to true to test if the mesh defined in parameters intersects with the current mesh or any child meshes
  20423. * @returns true if there is an intersection
  20424. */
  20425. AbstractMesh.prototype.intersectsMesh = function (mesh, precise, includeDescendants) {
  20426. if (precise === void 0) { precise = false; }
  20427. if (!this._boundingInfo || !mesh._boundingInfo) {
  20428. return false;
  20429. }
  20430. if (this._boundingInfo.intersects(mesh._boundingInfo, precise)) {
  20431. return true;
  20432. }
  20433. if (includeDescendants) {
  20434. for (var _i = 0, _a = this.getChildMeshes(); _i < _a.length; _i++) {
  20435. var child = _a[_i];
  20436. if (child.intersectsMesh(mesh, precise, true)) {
  20437. return true;
  20438. }
  20439. }
  20440. }
  20441. return false;
  20442. };
  20443. /**
  20444. * Returns true if the passed point (Vector3) is inside the mesh bounding box
  20445. * @param point defines the point to test
  20446. * @returns true if there is an intersection
  20447. */
  20448. AbstractMesh.prototype.intersectsPoint = function (point) {
  20449. if (!this._boundingInfo) {
  20450. return false;
  20451. }
  20452. return this._boundingInfo.intersectsPoint(point);
  20453. };
  20454. /**
  20455. * Gets the current physics impostor
  20456. * @see http://doc.babylonjs.com/features/physics_engine
  20457. * @returns a physics impostor or null
  20458. */
  20459. AbstractMesh.prototype.getPhysicsImpostor = function () {
  20460. return this.physicsImpostor;
  20461. };
  20462. /**
  20463. * Gets the position of the current mesh in camera space
  20464. * @param camera defines the camera to use
  20465. * @returns a position
  20466. */
  20467. AbstractMesh.prototype.getPositionInCameraSpace = function (camera) {
  20468. if (camera === void 0) { camera = null; }
  20469. if (!camera) {
  20470. camera = this.getScene().activeCamera;
  20471. }
  20472. return BABYLON.Vector3.TransformCoordinates(this.absolutePosition, camera.getViewMatrix());
  20473. };
  20474. /**
  20475. * Returns the distance from the mesh to the active camera
  20476. * @param camera defines the camera to use
  20477. * @returns the distance
  20478. */
  20479. AbstractMesh.prototype.getDistanceToCamera = function (camera) {
  20480. if (camera === void 0) { camera = null; }
  20481. if (!camera) {
  20482. camera = this.getScene().activeCamera;
  20483. }
  20484. return this.absolutePosition.subtract(camera.position).length();
  20485. };
  20486. /**
  20487. * Apply a physic impulse to the mesh
  20488. * @param force defines the force to apply
  20489. * @param contactPoint defines where to apply the force
  20490. * @returns the current mesh
  20491. * @see http://doc.babylonjs.com/how_to/using_the_physics_engine
  20492. */
  20493. AbstractMesh.prototype.applyImpulse = function (force, contactPoint) {
  20494. if (!this.physicsImpostor) {
  20495. return this;
  20496. }
  20497. this.physicsImpostor.applyImpulse(force, contactPoint);
  20498. return this;
  20499. };
  20500. /**
  20501. * Creates a physic joint between two meshes
  20502. * @param otherMesh defines the other mesh to use
  20503. * @param pivot1 defines the pivot to use on this mesh
  20504. * @param pivot2 defines the pivot to use on the other mesh
  20505. * @param options defines additional options (can be plugin dependent)
  20506. * @returns the current mesh
  20507. * @see https://www.babylonjs-playground.com/#0BS5U0#0
  20508. */
  20509. AbstractMesh.prototype.setPhysicsLinkWith = function (otherMesh, pivot1, pivot2, options) {
  20510. if (!this.physicsImpostor || !otherMesh.physicsImpostor) {
  20511. return this;
  20512. }
  20513. this.physicsImpostor.createJoint(otherMesh.physicsImpostor, BABYLON.PhysicsJoint.HingeJoint, {
  20514. mainPivot: pivot1,
  20515. connectedPivot: pivot2,
  20516. nativeParams: options
  20517. });
  20518. return this;
  20519. };
  20520. Object.defineProperty(AbstractMesh.prototype, "checkCollisions", {
  20521. // Collisions
  20522. /**
  20523. * Gets or sets a boolean indicating that this mesh can be used in the collision engine
  20524. * @see http://doc.babylonjs.com/babylon101/cameras,_mesh_collisions_and_gravity
  20525. */
  20526. get: function () {
  20527. return this._checkCollisions;
  20528. },
  20529. set: function (collisionEnabled) {
  20530. this._checkCollisions = collisionEnabled;
  20531. if (this.getScene().workerCollisions) {
  20532. this.getScene().collisionCoordinator.onMeshUpdated(this);
  20533. }
  20534. },
  20535. enumerable: true,
  20536. configurable: true
  20537. });
  20538. Object.defineProperty(AbstractMesh.prototype, "collider", {
  20539. /**
  20540. * Gets Collider object used to compute collisions (not physics)
  20541. * @see http://doc.babylonjs.com/babylon101/cameras,_mesh_collisions_and_gravity
  20542. */
  20543. get: function () {
  20544. return this._collider;
  20545. },
  20546. enumerable: true,
  20547. configurable: true
  20548. });
  20549. /**
  20550. * Move the mesh using collision engine
  20551. * @see http://doc.babylonjs.com/babylon101/cameras,_mesh_collisions_and_gravity
  20552. * @param displacement defines the requested displacement vector
  20553. * @returns the current mesh
  20554. */
  20555. AbstractMesh.prototype.moveWithCollisions = function (displacement) {
  20556. var globalPosition = this.getAbsolutePosition();
  20557. globalPosition.addToRef(this.ellipsoidOffset, this._oldPositionForCollisions);
  20558. if (!this._collider) {
  20559. this._collider = new BABYLON.Collider();
  20560. }
  20561. this._collider._radius = this.ellipsoid;
  20562. this.getScene().collisionCoordinator.getNewPosition(this._oldPositionForCollisions, displacement, this._collider, 3, this, this._onCollisionPositionChange, this.uniqueId);
  20563. return this;
  20564. };
  20565. // Submeshes octree
  20566. /**
  20567. * This function will create an octree to help to select the right submeshes for rendering, picking and collision computations.
  20568. * Please note that you must have a decent number of submeshes to get performance improvements when using an octree
  20569. * @param maxCapacity defines the maximum size of each block (64 by default)
  20570. * @param maxDepth defines the maximum depth to use (no more than 2 levels by default)
  20571. * @returns the new octree
  20572. * @see https://www.babylonjs-playground.com/#NA4OQ#12
  20573. * @see http://doc.babylonjs.com/how_to/optimizing_your_scene_with_octrees
  20574. */
  20575. AbstractMesh.prototype.createOrUpdateSubmeshesOctree = function (maxCapacity, maxDepth) {
  20576. if (maxCapacity === void 0) { maxCapacity = 64; }
  20577. if (maxDepth === void 0) { maxDepth = 2; }
  20578. if (!this._submeshesOctree) {
  20579. this._submeshesOctree = new BABYLON.Octree(BABYLON.Octree.CreationFuncForSubMeshes, maxCapacity, maxDepth);
  20580. }
  20581. this.computeWorldMatrix(true);
  20582. var boundingInfo = this.getBoundingInfo();
  20583. // Update octree
  20584. var bbox = boundingInfo.boundingBox;
  20585. this._submeshesOctree.update(bbox.minimumWorld, bbox.maximumWorld, this.subMeshes);
  20586. return this._submeshesOctree;
  20587. };
  20588. // Collisions
  20589. /** @hidden */
  20590. AbstractMesh.prototype._collideForSubMesh = function (subMesh, transformMatrix, collider) {
  20591. this._generatePointsArray();
  20592. if (!this._positions) {
  20593. return this;
  20594. }
  20595. // Transformation
  20596. if (!subMesh._lastColliderWorldVertices || !subMesh._lastColliderTransformMatrix.equals(transformMatrix)) {
  20597. subMesh._lastColliderTransformMatrix = transformMatrix.clone();
  20598. subMesh._lastColliderWorldVertices = [];
  20599. subMesh._trianglePlanes = [];
  20600. var start = subMesh.verticesStart;
  20601. var end = (subMesh.verticesStart + subMesh.verticesCount);
  20602. for (var i = start; i < end; i++) {
  20603. subMesh._lastColliderWorldVertices.push(BABYLON.Vector3.TransformCoordinates(this._positions[i], transformMatrix));
  20604. }
  20605. }
  20606. // Collide
  20607. collider._collide(subMesh._trianglePlanes, subMesh._lastColliderWorldVertices, this.getIndices(), subMesh.indexStart, subMesh.indexStart + subMesh.indexCount, subMesh.verticesStart, !!subMesh.getMaterial());
  20608. if (collider.collisionFound) {
  20609. collider.collidedMesh = this;
  20610. }
  20611. return this;
  20612. };
  20613. /** @hidden */
  20614. AbstractMesh.prototype._processCollisionsForSubMeshes = function (collider, transformMatrix) {
  20615. var subMeshes;
  20616. var len;
  20617. // Octrees
  20618. if (this._submeshesOctree && this.useOctreeForCollisions) {
  20619. var radius = collider._velocityWorldLength + Math.max(collider._radius.x, collider._radius.y, collider._radius.z);
  20620. var intersections = this._submeshesOctree.intersects(collider._basePointWorld, radius);
  20621. len = intersections.length;
  20622. subMeshes = intersections.data;
  20623. }
  20624. else {
  20625. subMeshes = this.subMeshes;
  20626. len = subMeshes.length;
  20627. }
  20628. for (var index = 0; index < len; index++) {
  20629. var subMesh = subMeshes[index];
  20630. // Bounding test
  20631. if (len > 1 && !subMesh._checkCollision(collider))
  20632. continue;
  20633. this._collideForSubMesh(subMesh, transformMatrix, collider);
  20634. }
  20635. return this;
  20636. };
  20637. /** @hidden */
  20638. AbstractMesh.prototype._checkCollision = function (collider) {
  20639. // Bounding box test
  20640. if (!this._boundingInfo || !this._boundingInfo._checkCollision(collider))
  20641. return this;
  20642. // Transformation matrix
  20643. BABYLON.Matrix.ScalingToRef(1.0 / collider._radius.x, 1.0 / collider._radius.y, 1.0 / collider._radius.z, this._collisionsScalingMatrix);
  20644. this.worldMatrixFromCache.multiplyToRef(this._collisionsScalingMatrix, this._collisionsTransformMatrix);
  20645. this._processCollisionsForSubMeshes(collider, this._collisionsTransformMatrix);
  20646. return this;
  20647. };
  20648. // Picking
  20649. /** @hidden */
  20650. AbstractMesh.prototype._generatePointsArray = function () {
  20651. return false;
  20652. };
  20653. /**
  20654. * Checks if the passed Ray intersects with the mesh
  20655. * @param ray defines the ray to use
  20656. * @param fastCheck defines if fast mode (but less precise) must be used (false by default)
  20657. * @returns the picking info
  20658. * @see http://doc.babylonjs.com/babylon101/intersect_collisions_-_mesh
  20659. */
  20660. AbstractMesh.prototype.intersects = function (ray, fastCheck) {
  20661. var pickingInfo = new BABYLON.PickingInfo();
  20662. if (!this.subMeshes || !this._boundingInfo || !ray.intersectsSphere(this._boundingInfo.boundingSphere) || !ray.intersectsBox(this._boundingInfo.boundingBox)) {
  20663. return pickingInfo;
  20664. }
  20665. if (!this._generatePointsArray()) {
  20666. return pickingInfo;
  20667. }
  20668. var intersectInfo = null;
  20669. // Octrees
  20670. var subMeshes;
  20671. var len;
  20672. if (this._submeshesOctree && this.useOctreeForPicking) {
  20673. var worldRay = BABYLON.Ray.Transform(ray, this.getWorldMatrix());
  20674. var intersections = this._submeshesOctree.intersectsRay(worldRay);
  20675. len = intersections.length;
  20676. subMeshes = intersections.data;
  20677. }
  20678. else {
  20679. subMeshes = this.subMeshes;
  20680. len = subMeshes.length;
  20681. }
  20682. for (var index = 0; index < len; index++) {
  20683. var subMesh = subMeshes[index];
  20684. // Bounding test
  20685. if (len > 1 && !subMesh.canIntersects(ray))
  20686. continue;
  20687. var currentIntersectInfo = subMesh.intersects(ray, this._positions, this.getIndices(), fastCheck);
  20688. if (currentIntersectInfo) {
  20689. if (fastCheck || !intersectInfo || currentIntersectInfo.distance < intersectInfo.distance) {
  20690. intersectInfo = currentIntersectInfo;
  20691. intersectInfo.subMeshId = index;
  20692. if (fastCheck) {
  20693. break;
  20694. }
  20695. }
  20696. }
  20697. }
  20698. if (intersectInfo) {
  20699. // Get picked point
  20700. var world = this.getWorldMatrix();
  20701. var worldOrigin = BABYLON.Vector3.TransformCoordinates(ray.origin, world);
  20702. var direction = ray.direction.clone();
  20703. direction = direction.scale(intersectInfo.distance);
  20704. var worldDirection = BABYLON.Vector3.TransformNormal(direction, world);
  20705. var pickedPoint = worldOrigin.add(worldDirection);
  20706. // Return result
  20707. pickingInfo.hit = true;
  20708. pickingInfo.distance = BABYLON.Vector3.Distance(worldOrigin, pickedPoint);
  20709. pickingInfo.pickedPoint = pickedPoint;
  20710. pickingInfo.pickedMesh = this;
  20711. pickingInfo.bu = intersectInfo.bu || 0;
  20712. pickingInfo.bv = intersectInfo.bv || 0;
  20713. pickingInfo.faceId = intersectInfo.faceId;
  20714. pickingInfo.subMeshId = intersectInfo.subMeshId;
  20715. return pickingInfo;
  20716. }
  20717. return pickingInfo;
  20718. };
  20719. /**
  20720. * Clones the current mesh
  20721. * @param name defines the mesh name
  20722. * @param newParent defines the new mesh parent
  20723. * @param doNotCloneChildren defines a boolean indicating that children must not be cloned (false by default)
  20724. * @returns the new mesh
  20725. */
  20726. AbstractMesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  20727. return null;
  20728. };
  20729. /**
  20730. * Disposes all the submeshes of the current meshnp
  20731. * @returns the current mesh
  20732. */
  20733. AbstractMesh.prototype.releaseSubMeshes = function () {
  20734. if (this.subMeshes) {
  20735. while (this.subMeshes.length) {
  20736. this.subMeshes[0].dispose();
  20737. }
  20738. }
  20739. else {
  20740. this.subMeshes = new Array();
  20741. }
  20742. return this;
  20743. };
  20744. /**
  20745. * Releases resources associated with this abstract mesh.
  20746. * @param doNotRecurse Set to true to not recurse into each children (recurse into each children by default)
  20747. * @param disposeMaterialAndTextures Set to true to also dispose referenced materials and textures (false by default)
  20748. */
  20749. AbstractMesh.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  20750. var _this = this;
  20751. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  20752. var index;
  20753. // Smart Array Retainers.
  20754. this.getScene().freeActiveMeshes();
  20755. this.getScene().freeRenderingGroups();
  20756. // Action manager
  20757. if (this.actionManager !== undefined && this.actionManager !== null) {
  20758. this.actionManager.dispose();
  20759. this.actionManager = null;
  20760. }
  20761. // Skeleton
  20762. this._skeleton = null;
  20763. // Physics
  20764. if (this.physicsImpostor) {
  20765. this.physicsImpostor.dispose( /*!doNotRecurse*/);
  20766. }
  20767. // Intersections in progress
  20768. for (index = 0; index < this._intersectionsInProgress.length; index++) {
  20769. var other = this._intersectionsInProgress[index];
  20770. var pos = other._intersectionsInProgress.indexOf(this);
  20771. other._intersectionsInProgress.splice(pos, 1);
  20772. }
  20773. this._intersectionsInProgress = [];
  20774. // Lights
  20775. var lights = this.getScene().lights;
  20776. lights.forEach(function (light) {
  20777. var meshIndex = light.includedOnlyMeshes.indexOf(_this);
  20778. if (meshIndex !== -1) {
  20779. light.includedOnlyMeshes.splice(meshIndex, 1);
  20780. }
  20781. meshIndex = light.excludedMeshes.indexOf(_this);
  20782. if (meshIndex !== -1) {
  20783. light.excludedMeshes.splice(meshIndex, 1);
  20784. }
  20785. // Shadow generators
  20786. var generator = light.getShadowGenerator();
  20787. if (generator) {
  20788. var shadowMap = generator.getShadowMap();
  20789. if (shadowMap && shadowMap.renderList) {
  20790. meshIndex = shadowMap.renderList.indexOf(_this);
  20791. if (meshIndex !== -1) {
  20792. shadowMap.renderList.splice(meshIndex, 1);
  20793. }
  20794. }
  20795. }
  20796. });
  20797. // Edges
  20798. if (this._edgesRenderer) {
  20799. this._edgesRenderer.dispose();
  20800. this._edgesRenderer = null;
  20801. }
  20802. // SubMeshes
  20803. if (this.getClassName() !== "InstancedMesh") {
  20804. this.releaseSubMeshes();
  20805. }
  20806. // Octree
  20807. var sceneOctree = this.getScene().selectionOctree;
  20808. if (sceneOctree !== undefined && sceneOctree !== null) {
  20809. var index = sceneOctree.dynamicContent.indexOf(this);
  20810. if (index !== -1) {
  20811. sceneOctree.dynamicContent.splice(index, 1);
  20812. }
  20813. }
  20814. // Query
  20815. var engine = this.getScene().getEngine();
  20816. if (this._occlusionQuery) {
  20817. this._isOcclusionQueryInProgress = false;
  20818. engine.deleteQuery(this._occlusionQuery);
  20819. this._occlusionQuery = null;
  20820. }
  20821. // Engine
  20822. engine.wipeCaches();
  20823. // Remove from scene
  20824. this.getScene().removeMesh(this);
  20825. if (disposeMaterialAndTextures) {
  20826. if (this.material) {
  20827. this.material.dispose(false, true);
  20828. }
  20829. }
  20830. if (!doNotRecurse) {
  20831. // Particles
  20832. for (index = 0; index < this.getScene().particleSystems.length; index++) {
  20833. if (this.getScene().particleSystems[index].emitter === this) {
  20834. this.getScene().particleSystems[index].dispose();
  20835. index--;
  20836. }
  20837. }
  20838. }
  20839. // facet data
  20840. if (this._facetDataEnabled) {
  20841. this.disableFacetData();
  20842. }
  20843. this.onAfterWorldMatrixUpdateObservable.clear();
  20844. this.onCollideObservable.clear();
  20845. this.onCollisionPositionChangeObservable.clear();
  20846. _super.prototype.dispose.call(this, doNotRecurse, disposeMaterialAndTextures);
  20847. };
  20848. /**
  20849. * Adds the passed mesh as a child to the current mesh
  20850. * @param mesh defines the child mesh
  20851. * @returns the current mesh
  20852. */
  20853. AbstractMesh.prototype.addChild = function (mesh) {
  20854. mesh.setParent(this);
  20855. return this;
  20856. };
  20857. /**
  20858. * Removes the passed mesh from the current mesh children list
  20859. * @param mesh defines the child mesh
  20860. * @returns the current mesh
  20861. */
  20862. AbstractMesh.prototype.removeChild = function (mesh) {
  20863. mesh.setParent(null);
  20864. return this;
  20865. };
  20866. // Facet data
  20867. /** @hidden */
  20868. AbstractMesh.prototype._initFacetData = function () {
  20869. if (!this._facetNormals) {
  20870. this._facetNormals = new Array();
  20871. }
  20872. if (!this._facetPositions) {
  20873. this._facetPositions = new Array();
  20874. }
  20875. if (!this._facetPartitioning) {
  20876. this._facetPartitioning = new Array();
  20877. }
  20878. this._facetNb = (this.getIndices().length / 3) | 0;
  20879. this._partitioningSubdivisions = (this._partitioningSubdivisions) ? this._partitioningSubdivisions : 10; // default nb of partitioning subdivisions = 10
  20880. this._partitioningBBoxRatio = (this._partitioningBBoxRatio) ? this._partitioningBBoxRatio : 1.01; // default ratio 1.01 = the partitioning is 1% bigger than the bounding box
  20881. for (var f = 0; f < this._facetNb; f++) {
  20882. this._facetNormals[f] = BABYLON.Vector3.Zero();
  20883. this._facetPositions[f] = BABYLON.Vector3.Zero();
  20884. }
  20885. this._facetDataEnabled = true;
  20886. return this;
  20887. };
  20888. /**
  20889. * Updates the mesh facetData arrays and the internal partitioning when the mesh is morphed or updated.
  20890. * This method can be called within the render loop.
  20891. * 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
  20892. * @returns the current mesh
  20893. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  20894. */
  20895. AbstractMesh.prototype.updateFacetData = function () {
  20896. if (!this._facetDataEnabled) {
  20897. this._initFacetData();
  20898. }
  20899. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  20900. var indices = this.getIndices();
  20901. var normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  20902. var bInfo = this.getBoundingInfo();
  20903. if (this._facetDepthSort && !this._facetDepthSortEnabled) {
  20904. // init arrays, matrix and sort function on first call
  20905. this._facetDepthSortEnabled = true;
  20906. if (indices instanceof Uint16Array) {
  20907. this._depthSortedIndices = new Uint16Array(indices);
  20908. }
  20909. else if (indices instanceof Uint32Array) {
  20910. this._depthSortedIndices = new Uint32Array(indices);
  20911. }
  20912. else {
  20913. var needs32bits = false;
  20914. for (var i = 0; i < indices.length; i++) {
  20915. if (indices[i] > 65535) {
  20916. needs32bits = true;
  20917. break;
  20918. }
  20919. }
  20920. if (needs32bits) {
  20921. this._depthSortedIndices = new Uint32Array(indices);
  20922. }
  20923. else {
  20924. this._depthSortedIndices = new Uint16Array(indices);
  20925. }
  20926. }
  20927. this._facetDepthSortFunction = function (f1, f2) {
  20928. return (f2.sqDistance - f1.sqDistance);
  20929. };
  20930. if (!this._facetDepthSortFrom) {
  20931. var camera = this.getScene().activeCamera;
  20932. this._facetDepthSortFrom = (camera) ? camera.position : BABYLON.Vector3.Zero();
  20933. }
  20934. this._depthSortedFacets = [];
  20935. for (var f = 0; f < this._facetNb; f++) {
  20936. var depthSortedFacet = { ind: f * 3, sqDistance: 0.0 };
  20937. this._depthSortedFacets.push(depthSortedFacet);
  20938. }
  20939. this._invertedMatrix = BABYLON.Matrix.Identity();
  20940. this._facetDepthSortOrigin = BABYLON.Vector3.Zero();
  20941. }
  20942. this._bbSize.x = (bInfo.maximum.x - bInfo.minimum.x > BABYLON.Epsilon) ? bInfo.maximum.x - bInfo.minimum.x : BABYLON.Epsilon;
  20943. this._bbSize.y = (bInfo.maximum.y - bInfo.minimum.y > BABYLON.Epsilon) ? bInfo.maximum.y - bInfo.minimum.y : BABYLON.Epsilon;
  20944. this._bbSize.z = (bInfo.maximum.z - bInfo.minimum.z > BABYLON.Epsilon) ? bInfo.maximum.z - bInfo.minimum.z : BABYLON.Epsilon;
  20945. var bbSizeMax = (this._bbSize.x > this._bbSize.y) ? this._bbSize.x : this._bbSize.y;
  20946. bbSizeMax = (bbSizeMax > this._bbSize.z) ? bbSizeMax : this._bbSize.z;
  20947. this._subDiv.max = this._partitioningSubdivisions;
  20948. this._subDiv.X = Math.floor(this._subDiv.max * this._bbSize.x / bbSizeMax); // adjust the number of subdivisions per axis
  20949. this._subDiv.Y = Math.floor(this._subDiv.max * this._bbSize.y / bbSizeMax); // according to each bbox size per axis
  20950. this._subDiv.Z = Math.floor(this._subDiv.max * this._bbSize.z / bbSizeMax);
  20951. this._subDiv.X = this._subDiv.X < 1 ? 1 : this._subDiv.X; // at least one subdivision
  20952. this._subDiv.Y = this._subDiv.Y < 1 ? 1 : this._subDiv.Y;
  20953. this._subDiv.Z = this._subDiv.Z < 1 ? 1 : this._subDiv.Z;
  20954. // set the parameters for ComputeNormals()
  20955. this._facetParameters.facetNormals = this.getFacetLocalNormals();
  20956. this._facetParameters.facetPositions = this.getFacetLocalPositions();
  20957. this._facetParameters.facetPartitioning = this.getFacetLocalPartitioning();
  20958. this._facetParameters.bInfo = bInfo;
  20959. this._facetParameters.bbSize = this._bbSize;
  20960. this._facetParameters.subDiv = this._subDiv;
  20961. this._facetParameters.ratio = this.partitioningBBoxRatio;
  20962. this._facetParameters.depthSort = this._facetDepthSort;
  20963. if (this._facetDepthSort && this._facetDepthSortEnabled) {
  20964. this.computeWorldMatrix(true);
  20965. this._worldMatrix.invertToRef(this._invertedMatrix);
  20966. BABYLON.Vector3.TransformCoordinatesToRef(this._facetDepthSortFrom, this._invertedMatrix, this._facetDepthSortOrigin);
  20967. this._facetParameters.distanceTo = this._facetDepthSortOrigin;
  20968. }
  20969. this._facetParameters.depthSortedFacets = this._depthSortedFacets;
  20970. BABYLON.VertexData.ComputeNormals(positions, indices, normals, this._facetParameters);
  20971. if (this._facetDepthSort && this._facetDepthSortEnabled) {
  20972. this._depthSortedFacets.sort(this._facetDepthSortFunction);
  20973. var l = (this._depthSortedIndices.length / 3) | 0;
  20974. for (var f = 0; f < l; f++) {
  20975. var sind = this._depthSortedFacets[f].ind;
  20976. this._depthSortedIndices[f * 3] = indices[sind];
  20977. this._depthSortedIndices[f * 3 + 1] = indices[sind + 1];
  20978. this._depthSortedIndices[f * 3 + 2] = indices[sind + 2];
  20979. }
  20980. this.updateIndices(this._depthSortedIndices);
  20981. }
  20982. return this;
  20983. };
  20984. /**
  20985. * Returns the facetLocalNormals array.
  20986. * The normals are expressed in the mesh local spac
  20987. * @returns an array of Vector3
  20988. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  20989. */
  20990. AbstractMesh.prototype.getFacetLocalNormals = function () {
  20991. if (!this._facetNormals) {
  20992. this.updateFacetData();
  20993. }
  20994. return this._facetNormals;
  20995. };
  20996. /**
  20997. * Returns the facetLocalPositions array.
  20998. * The facet positions are expressed in the mesh local space
  20999. * @returns an array of Vector3
  21000. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  21001. */
  21002. AbstractMesh.prototype.getFacetLocalPositions = function () {
  21003. if (!this._facetPositions) {
  21004. this.updateFacetData();
  21005. }
  21006. return this._facetPositions;
  21007. };
  21008. /**
  21009. * Returns the facetLocalPartioning array
  21010. * @returns an array of array of numbers
  21011. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  21012. */
  21013. AbstractMesh.prototype.getFacetLocalPartitioning = function () {
  21014. if (!this._facetPartitioning) {
  21015. this.updateFacetData();
  21016. }
  21017. return this._facetPartitioning;
  21018. };
  21019. /**
  21020. * Returns the i-th facet position in the world system.
  21021. * This method allocates a new Vector3 per call
  21022. * @param i defines the facet index
  21023. * @returns a new Vector3
  21024. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  21025. */
  21026. AbstractMesh.prototype.getFacetPosition = function (i) {
  21027. var pos = BABYLON.Vector3.Zero();
  21028. this.getFacetPositionToRef(i, pos);
  21029. return pos;
  21030. };
  21031. /**
  21032. * Sets the reference Vector3 with the i-th facet position in the world system
  21033. * @param i defines the facet index
  21034. * @param ref defines the target vector
  21035. * @returns the current mesh
  21036. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  21037. */
  21038. AbstractMesh.prototype.getFacetPositionToRef = function (i, ref) {
  21039. var localPos = (this.getFacetLocalPositions())[i];
  21040. var world = this.getWorldMatrix();
  21041. BABYLON.Vector3.TransformCoordinatesToRef(localPos, world, ref);
  21042. return this;
  21043. };
  21044. /**
  21045. * Returns the i-th facet normal in the world system.
  21046. * This method allocates a new Vector3 per call
  21047. * @param i defines the facet index
  21048. * @returns a new Vector3
  21049. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  21050. */
  21051. AbstractMesh.prototype.getFacetNormal = function (i) {
  21052. var norm = BABYLON.Vector3.Zero();
  21053. this.getFacetNormalToRef(i, norm);
  21054. return norm;
  21055. };
  21056. /**
  21057. * Sets the reference Vector3 with the i-th facet normal in the world system
  21058. * @param i defines the facet index
  21059. * @param ref defines the target vector
  21060. * @returns the current mesh
  21061. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  21062. */
  21063. AbstractMesh.prototype.getFacetNormalToRef = function (i, ref) {
  21064. var localNorm = (this.getFacetLocalNormals())[i];
  21065. BABYLON.Vector3.TransformNormalToRef(localNorm, this.getWorldMatrix(), ref);
  21066. return this;
  21067. };
  21068. /**
  21069. * 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)
  21070. * @param x defines x coordinate
  21071. * @param y defines y coordinate
  21072. * @param z defines z coordinate
  21073. * @returns the array of facet indexes
  21074. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  21075. */
  21076. AbstractMesh.prototype.getFacetsAtLocalCoordinates = function (x, y, z) {
  21077. var bInfo = this.getBoundingInfo();
  21078. var ox = Math.floor((x - bInfo.minimum.x * this._partitioningBBoxRatio) * this._subDiv.X * this._partitioningBBoxRatio / this._bbSize.x);
  21079. var oy = Math.floor((y - bInfo.minimum.y * this._partitioningBBoxRatio) * this._subDiv.Y * this._partitioningBBoxRatio / this._bbSize.y);
  21080. var oz = Math.floor((z - bInfo.minimum.z * this._partitioningBBoxRatio) * this._subDiv.Z * this._partitioningBBoxRatio / this._bbSize.z);
  21081. if (ox < 0 || ox > this._subDiv.max || oy < 0 || oy > this._subDiv.max || oz < 0 || oz > this._subDiv.max) {
  21082. return null;
  21083. }
  21084. return this._facetPartitioning[ox + this._subDiv.max * oy + this._subDiv.max * this._subDiv.max * oz];
  21085. };
  21086. /**
  21087. * Returns the closest mesh facet index at (x,y,z) World coordinates, null if not found
  21088. * @param projected sets as the (x,y,z) world projection on the facet
  21089. * @param checkFace if true (default false), only the facet "facing" to (x,y,z) or only the ones "turning their backs", according to the parameter "facing" are returned
  21090. * @param facing if facing and checkFace are true, only the facet "facing" to (x, y, z) are returned : positive dot (x, y, z) * facet position. If facing si false and checkFace is true, only the facet "turning their backs" to (x, y, z) are returned : negative dot (x, y, z) * facet position
  21091. * @param x defines x coordinate
  21092. * @param y defines y coordinate
  21093. * @param z defines z coordinate
  21094. * @returns the face index if found (or null instead)
  21095. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  21096. */
  21097. AbstractMesh.prototype.getClosestFacetAtCoordinates = function (x, y, z, projected, checkFace, facing) {
  21098. if (checkFace === void 0) { checkFace = false; }
  21099. if (facing === void 0) { facing = true; }
  21100. var world = this.getWorldMatrix();
  21101. var invMat = BABYLON.Tmp.Matrix[5];
  21102. world.invertToRef(invMat);
  21103. var invVect = BABYLON.Tmp.Vector3[8];
  21104. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, y, z, invMat, invVect); // transform (x,y,z) to coordinates in the mesh local space
  21105. var closest = this.getClosestFacetAtLocalCoordinates(invVect.x, invVect.y, invVect.z, projected, checkFace, facing);
  21106. if (projected) {
  21107. // tranform the local computed projected vector to world coordinates
  21108. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(projected.x, projected.y, projected.z, world, projected);
  21109. }
  21110. return closest;
  21111. };
  21112. /**
  21113. * Returns the closest mesh facet index at (x,y,z) local coordinates, null if not found
  21114. * @param projected sets as the (x,y,z) local projection on the facet
  21115. * @param checkFace if true (default false), only the facet "facing" to (x,y,z) or only the ones "turning their backs", according to the parameter "facing" are returned
  21116. * @param facing if facing and checkFace are true, only the facet "facing" to (x, y, z) are returned : positive dot (x, y, z) * facet position. If facing si false and checkFace is true, only the facet "turning their backs" to (x, y, z) are returned : negative dot (x, y, z) * facet position
  21117. * @param x defines x coordinate
  21118. * @param y defines y coordinate
  21119. * @param z defines z coordinate
  21120. * @returns the face index if found (or null instead)
  21121. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  21122. */
  21123. AbstractMesh.prototype.getClosestFacetAtLocalCoordinates = function (x, y, z, projected, checkFace, facing) {
  21124. if (checkFace === void 0) { checkFace = false; }
  21125. if (facing === void 0) { facing = true; }
  21126. var closest = null;
  21127. var tmpx = 0.0;
  21128. var tmpy = 0.0;
  21129. var tmpz = 0.0;
  21130. var d = 0.0; // tmp dot facet normal * facet position
  21131. var t0 = 0.0;
  21132. var projx = 0.0;
  21133. var projy = 0.0;
  21134. var projz = 0.0;
  21135. // Get all the facets in the same partitioning block than (x, y, z)
  21136. var facetPositions = this.getFacetLocalPositions();
  21137. var facetNormals = this.getFacetLocalNormals();
  21138. var facetsInBlock = this.getFacetsAtLocalCoordinates(x, y, z);
  21139. if (!facetsInBlock) {
  21140. return null;
  21141. }
  21142. // Get the closest facet to (x, y, z)
  21143. var shortest = Number.MAX_VALUE; // init distance vars
  21144. var tmpDistance = shortest;
  21145. var fib; // current facet in the block
  21146. var norm; // current facet normal
  21147. var p0; // current facet barycenter position
  21148. // loop on all the facets in the current partitioning block
  21149. for (var idx = 0; idx < facetsInBlock.length; idx++) {
  21150. fib = facetsInBlock[idx];
  21151. norm = facetNormals[fib];
  21152. p0 = facetPositions[fib];
  21153. d = (x - p0.x) * norm.x + (y - p0.y) * norm.y + (z - p0.z) * norm.z;
  21154. if (!checkFace || (checkFace && facing && d >= 0.0) || (checkFace && !facing && d <= 0.0)) {
  21155. // compute (x,y,z) projection on the facet = (projx, projy, projz)
  21156. d = norm.x * p0.x + norm.y * p0.y + norm.z * p0.z;
  21157. t0 = -(norm.x * x + norm.y * y + norm.z * z - d) / (norm.x * norm.x + norm.y * norm.y + norm.z * norm.z);
  21158. projx = x + norm.x * t0;
  21159. projy = y + norm.y * t0;
  21160. projz = z + norm.z * t0;
  21161. tmpx = projx - x;
  21162. tmpy = projy - y;
  21163. tmpz = projz - z;
  21164. tmpDistance = tmpx * tmpx + tmpy * tmpy + tmpz * tmpz; // compute length between (x, y, z) and its projection on the facet
  21165. if (tmpDistance < shortest) { // just keep the closest facet to (x, y, z)
  21166. shortest = tmpDistance;
  21167. closest = fib;
  21168. if (projected) {
  21169. projected.x = projx;
  21170. projected.y = projy;
  21171. projected.z = projz;
  21172. }
  21173. }
  21174. }
  21175. }
  21176. return closest;
  21177. };
  21178. /**
  21179. * Returns the object "parameter" set with all the expected parameters for facetData computation by ComputeNormals()
  21180. * @returns the parameters
  21181. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  21182. */
  21183. AbstractMesh.prototype.getFacetDataParameters = function () {
  21184. return this._facetParameters;
  21185. };
  21186. /**
  21187. * Disables the feature FacetData and frees the related memory
  21188. * @returns the current mesh
  21189. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  21190. */
  21191. AbstractMesh.prototype.disableFacetData = function () {
  21192. if (this._facetDataEnabled) {
  21193. this._facetDataEnabled = false;
  21194. this._facetPositions = new Array();
  21195. this._facetNormals = new Array();
  21196. this._facetPartitioning = new Array();
  21197. this._facetParameters = null;
  21198. this._depthSortedIndices = new Uint32Array(0);
  21199. }
  21200. return this;
  21201. };
  21202. /**
  21203. * Updates the AbstractMesh indices array
  21204. * @param indices defines the data source
  21205. * @returns the current mesh
  21206. */
  21207. AbstractMesh.prototype.updateIndices = function (indices) {
  21208. return this;
  21209. };
  21210. /**
  21211. * Creates new normals data for the mesh
  21212. * @param updatable defines if the normal vertex buffer must be flagged as updatable
  21213. * @returns the current mesh
  21214. */
  21215. AbstractMesh.prototype.createNormals = function (updatable) {
  21216. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  21217. var indices = this.getIndices();
  21218. var normals;
  21219. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  21220. normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  21221. }
  21222. else {
  21223. normals = [];
  21224. }
  21225. BABYLON.VertexData.ComputeNormals(positions, indices, normals, { useRightHandedSystem: this.getScene().useRightHandedSystem });
  21226. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals, updatable);
  21227. return this;
  21228. };
  21229. /**
  21230. * Align the mesh with a normal
  21231. * @param normal defines the normal to use
  21232. * @param upDirection can be used to redefined the up vector to use (will use the (0, 1, 0) by default)
  21233. * @returns the current mesh
  21234. */
  21235. AbstractMesh.prototype.alignWithNormal = function (normal, upDirection) {
  21236. if (!upDirection) {
  21237. upDirection = BABYLON.Axis.Y;
  21238. }
  21239. var axisX = BABYLON.Tmp.Vector3[0];
  21240. var axisZ = BABYLON.Tmp.Vector3[1];
  21241. BABYLON.Vector3.CrossToRef(upDirection, normal, axisZ);
  21242. BABYLON.Vector3.CrossToRef(normal, axisZ, axisX);
  21243. if (this.rotationQuaternion) {
  21244. BABYLON.Quaternion.RotationQuaternionFromAxisToRef(axisX, normal, axisZ, this.rotationQuaternion);
  21245. }
  21246. else {
  21247. BABYLON.Vector3.RotationFromAxisToRef(axisX, normal, axisZ, this.rotation);
  21248. }
  21249. return this;
  21250. };
  21251. /** @hidden */
  21252. AbstractMesh.prototype._checkOcclusionQuery = function () {
  21253. var engine = this.getEngine();
  21254. if (engine.webGLVersion < 2 || this.occlusionType === AbstractMesh.OCCLUSION_TYPE_NONE) {
  21255. this._isOccluded = false;
  21256. return;
  21257. }
  21258. if (this.isOcclusionQueryInProgress && this._occlusionQuery) {
  21259. var isOcclusionQueryAvailable = engine.isQueryResultAvailable(this._occlusionQuery);
  21260. if (isOcclusionQueryAvailable) {
  21261. var occlusionQueryResult = engine.getQueryResult(this._occlusionQuery);
  21262. this._isOcclusionQueryInProgress = false;
  21263. this._occlusionInternalRetryCounter = 0;
  21264. this._isOccluded = occlusionQueryResult === 1 ? false : true;
  21265. }
  21266. else {
  21267. this._occlusionInternalRetryCounter++;
  21268. if (this.occlusionRetryCount !== -1 && this._occlusionInternalRetryCounter > this.occlusionRetryCount) {
  21269. this._isOcclusionQueryInProgress = false;
  21270. this._occlusionInternalRetryCounter = 0;
  21271. // if optimistic set isOccluded to false regardless of the status of isOccluded. (Render in the current render loop)
  21272. // if strict continue the last state of the object.
  21273. this._isOccluded = this.occlusionType === AbstractMesh.OCCLUSION_TYPE_OPTIMISTIC ? false : this._isOccluded;
  21274. }
  21275. else {
  21276. return;
  21277. }
  21278. }
  21279. }
  21280. var scene = this.getScene();
  21281. var occlusionBoundingBoxRenderer = scene.getBoundingBoxRenderer();
  21282. if (!this._occlusionQuery) {
  21283. this._occlusionQuery = engine.createQuery();
  21284. }
  21285. engine.beginOcclusionQuery(this.occlusionQueryAlgorithmType, this._occlusionQuery);
  21286. occlusionBoundingBoxRenderer.renderOcclusionBoundingBox(this);
  21287. engine.endOcclusionQuery(this.occlusionQueryAlgorithmType);
  21288. this._isOcclusionQueryInProgress = true;
  21289. };
  21290. /** No occlusion */
  21291. AbstractMesh.OCCLUSION_TYPE_NONE = 0;
  21292. /** Occlusion set to optimisitic */
  21293. AbstractMesh.OCCLUSION_TYPE_OPTIMISTIC = 1;
  21294. /** Occlusion set to strict */
  21295. AbstractMesh.OCCLUSION_TYPE_STRICT = 2;
  21296. /** Use an accurante occlusion algorithm */
  21297. AbstractMesh.OCCLUSION_ALGORITHM_TYPE_ACCURATE = 0;
  21298. /** Use a conservative occlusion algorithm */
  21299. AbstractMesh.OCCLUSION_ALGORITHM_TYPE_CONSERVATIVE = 1;
  21300. return AbstractMesh;
  21301. }(BABYLON.TransformNode));
  21302. BABYLON.AbstractMesh = AbstractMesh;
  21303. })(BABYLON || (BABYLON = {}));
  21304. //# sourceMappingURL=babylon.abstractMesh.js.map
  21305. var BABYLON;
  21306. (function (BABYLON) {
  21307. /**
  21308. * Base class of all the lights in Babylon. It groups all the generic information about lights.
  21309. * Lights are used, as you would expect, to affect how meshes are seen, in terms of both illumination and colour.
  21310. * 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.
  21311. */
  21312. var Light = /** @class */ (function (_super) {
  21313. __extends(Light, _super);
  21314. /**
  21315. * Creates a Light object in the scene.
  21316. * Documentation : http://doc.babylonjs.com/tutorials/lights
  21317. * @param name The firendly name of the light
  21318. * @param scene The scene the light belongs too
  21319. */
  21320. function Light(name, scene) {
  21321. var _this = _super.call(this, name, scene) || this;
  21322. /**
  21323. * Diffuse gives the basic color to an object.
  21324. */
  21325. _this.diffuse = new BABYLON.Color3(1.0, 1.0, 1.0);
  21326. /**
  21327. * Specular produces a highlight color on an object.
  21328. * Note: This is note affecting PBR materials.
  21329. */
  21330. _this.specular = new BABYLON.Color3(1.0, 1.0, 1.0);
  21331. /**
  21332. * Strength of the light.
  21333. * Note: By default it is define in the framework own unit.
  21334. * Note: In PBR materials the intensityMode can be use to chose what unit the intensity is defined in.
  21335. */
  21336. _this.intensity = 1.0;
  21337. /**
  21338. * Defines how far from the source the light is impacting in scene units.
  21339. * Note: Unused in PBR material as the distance light falloff is defined following the inverse squared falloff.
  21340. */
  21341. _this.range = Number.MAX_VALUE;
  21342. /**
  21343. * Cached photometric scale default to 1.0 as the automatic intensity mode defaults to 1.0 for every type
  21344. * of light.
  21345. */
  21346. _this._photometricScale = 1.0;
  21347. _this._intensityMode = Light.INTENSITYMODE_AUTOMATIC;
  21348. _this._radius = 0.00001;
  21349. /**
  21350. * Defines the rendering priority of the lights. It can help in case of fallback or number of lights
  21351. * exceeding the number allowed of the materials.
  21352. */
  21353. _this.renderPriority = 0;
  21354. /**
  21355. * Defines wether or not the shadows are enabled for this light. This can help turning off/on shadow without detaching
  21356. * the current shadow generator.
  21357. */
  21358. _this.shadowEnabled = true;
  21359. _this._excludeWithLayerMask = 0;
  21360. _this._includeOnlyWithLayerMask = 0;
  21361. _this._lightmapMode = 0;
  21362. /**
  21363. * @hidden Internal use only.
  21364. */
  21365. _this._excludedMeshesIds = new Array();
  21366. /**
  21367. * @hidden Internal use only.
  21368. */
  21369. _this._includedOnlyMeshesIds = new Array();
  21370. _this.getScene().addLight(_this);
  21371. _this._uniformBuffer = new BABYLON.UniformBuffer(_this.getScene().getEngine());
  21372. _this._buildUniformLayout();
  21373. _this.includedOnlyMeshes = new Array();
  21374. _this.excludedMeshes = new Array();
  21375. _this._resyncMeshes();
  21376. return _this;
  21377. }
  21378. Object.defineProperty(Light, "LIGHTMAP_DEFAULT", {
  21379. /**
  21380. * If every light affecting the material is in this lightmapMode,
  21381. * material.lightmapTexture adds or multiplies
  21382. * (depends on material.useLightmapAsShadowmap)
  21383. * after every other light calculations.
  21384. */
  21385. get: function () {
  21386. return Light._LIGHTMAP_DEFAULT;
  21387. },
  21388. enumerable: true,
  21389. configurable: true
  21390. });
  21391. Object.defineProperty(Light, "LIGHTMAP_SPECULAR", {
  21392. /**
  21393. * material.lightmapTexture as only diffuse lighting from this light
  21394. * adds only specular lighting from this light
  21395. * adds dynamic shadows
  21396. */
  21397. get: function () {
  21398. return Light._LIGHTMAP_SPECULAR;
  21399. },
  21400. enumerable: true,
  21401. configurable: true
  21402. });
  21403. Object.defineProperty(Light, "LIGHTMAP_SHADOWSONLY", {
  21404. /**
  21405. * material.lightmapTexture as only lighting
  21406. * no light calculation from this light
  21407. * only adds dynamic shadows from this light
  21408. */
  21409. get: function () {
  21410. return Light._LIGHTMAP_SHADOWSONLY;
  21411. },
  21412. enumerable: true,
  21413. configurable: true
  21414. });
  21415. Object.defineProperty(Light, "INTENSITYMODE_AUTOMATIC", {
  21416. /**
  21417. * Each light type uses the default quantity according to its type:
  21418. * point/spot lights use luminous intensity
  21419. * directional lights use illuminance
  21420. */
  21421. get: function () {
  21422. return Light._INTENSITYMODE_AUTOMATIC;
  21423. },
  21424. enumerable: true,
  21425. configurable: true
  21426. });
  21427. Object.defineProperty(Light, "INTENSITYMODE_LUMINOUSPOWER", {
  21428. /**
  21429. * lumen (lm)
  21430. */
  21431. get: function () {
  21432. return Light._INTENSITYMODE_LUMINOUSPOWER;
  21433. },
  21434. enumerable: true,
  21435. configurable: true
  21436. });
  21437. Object.defineProperty(Light, "INTENSITYMODE_LUMINOUSINTENSITY", {
  21438. /**
  21439. * candela (lm/sr)
  21440. */
  21441. get: function () {
  21442. return Light._INTENSITYMODE_LUMINOUSINTENSITY;
  21443. },
  21444. enumerable: true,
  21445. configurable: true
  21446. });
  21447. Object.defineProperty(Light, "INTENSITYMODE_ILLUMINANCE", {
  21448. /**
  21449. * lux (lm/m^2)
  21450. */
  21451. get: function () {
  21452. return Light._INTENSITYMODE_ILLUMINANCE;
  21453. },
  21454. enumerable: true,
  21455. configurable: true
  21456. });
  21457. Object.defineProperty(Light, "INTENSITYMODE_LUMINANCE", {
  21458. /**
  21459. * nit (cd/m^2)
  21460. */
  21461. get: function () {
  21462. return Light._INTENSITYMODE_LUMINANCE;
  21463. },
  21464. enumerable: true,
  21465. configurable: true
  21466. });
  21467. Object.defineProperty(Light, "LIGHTTYPEID_POINTLIGHT", {
  21468. /**
  21469. * Light type const id of the point light.
  21470. */
  21471. get: function () {
  21472. return Light._LIGHTTYPEID_POINTLIGHT;
  21473. },
  21474. enumerable: true,
  21475. configurable: true
  21476. });
  21477. Object.defineProperty(Light, "LIGHTTYPEID_DIRECTIONALLIGHT", {
  21478. /**
  21479. * Light type const id of the directional light.
  21480. */
  21481. get: function () {
  21482. return Light._LIGHTTYPEID_DIRECTIONALLIGHT;
  21483. },
  21484. enumerable: true,
  21485. configurable: true
  21486. });
  21487. Object.defineProperty(Light, "LIGHTTYPEID_SPOTLIGHT", {
  21488. /**
  21489. * Light type const id of the spot light.
  21490. */
  21491. get: function () {
  21492. return Light._LIGHTTYPEID_SPOTLIGHT;
  21493. },
  21494. enumerable: true,
  21495. configurable: true
  21496. });
  21497. Object.defineProperty(Light, "LIGHTTYPEID_HEMISPHERICLIGHT", {
  21498. /**
  21499. * Light type const id of the hemispheric light.
  21500. */
  21501. get: function () {
  21502. return Light._LIGHTTYPEID_HEMISPHERICLIGHT;
  21503. },
  21504. enumerable: true,
  21505. configurable: true
  21506. });
  21507. Object.defineProperty(Light.prototype, "intensityMode", {
  21508. /**
  21509. * Gets the photometric scale used to interpret the intensity.
  21510. * This is only relevant with PBR Materials where the light intensity can be defined in a physical way.
  21511. */
  21512. get: function () {
  21513. return this._intensityMode;
  21514. },
  21515. /**
  21516. * Sets the photometric scale used to interpret the intensity.
  21517. * This is only relevant with PBR Materials where the light intensity can be defined in a physical way.
  21518. */
  21519. set: function (value) {
  21520. this._intensityMode = value;
  21521. this._computePhotometricScale();
  21522. },
  21523. enumerable: true,
  21524. configurable: true
  21525. });
  21526. ;
  21527. ;
  21528. Object.defineProperty(Light.prototype, "radius", {
  21529. /**
  21530. * Gets the light radius used by PBR Materials to simulate soft area lights.
  21531. */
  21532. get: function () {
  21533. return this._radius;
  21534. },
  21535. /**
  21536. * sets the light radius used by PBR Materials to simulate soft area lights.
  21537. */
  21538. set: function (value) {
  21539. this._radius = value;
  21540. this._computePhotometricScale();
  21541. },
  21542. enumerable: true,
  21543. configurable: true
  21544. });
  21545. ;
  21546. ;
  21547. Object.defineProperty(Light.prototype, "includedOnlyMeshes", {
  21548. /**
  21549. * Gets the only meshes impacted by this light.
  21550. */
  21551. get: function () {
  21552. return this._includedOnlyMeshes;
  21553. },
  21554. /**
  21555. * Sets the only meshes impacted by this light.
  21556. */
  21557. set: function (value) {
  21558. this._includedOnlyMeshes = value;
  21559. this._hookArrayForIncludedOnly(value);
  21560. },
  21561. enumerable: true,
  21562. configurable: true
  21563. });
  21564. Object.defineProperty(Light.prototype, "excludedMeshes", {
  21565. /**
  21566. * Gets the meshes not impacted by this light.
  21567. */
  21568. get: function () {
  21569. return this._excludedMeshes;
  21570. },
  21571. /**
  21572. * Sets the meshes not impacted by this light.
  21573. */
  21574. set: function (value) {
  21575. this._excludedMeshes = value;
  21576. this._hookArrayForExcluded(value);
  21577. },
  21578. enumerable: true,
  21579. configurable: true
  21580. });
  21581. Object.defineProperty(Light.prototype, "excludeWithLayerMask", {
  21582. /**
  21583. * Gets the layer id use to find what meshes are not impacted by the light.
  21584. * Inactive if 0
  21585. */
  21586. get: function () {
  21587. return this._excludeWithLayerMask;
  21588. },
  21589. /**
  21590. * Sets the layer id use to find what meshes are not impacted by the light.
  21591. * Inactive if 0
  21592. */
  21593. set: function (value) {
  21594. this._excludeWithLayerMask = value;
  21595. this._resyncMeshes();
  21596. },
  21597. enumerable: true,
  21598. configurable: true
  21599. });
  21600. Object.defineProperty(Light.prototype, "includeOnlyWithLayerMask", {
  21601. /**
  21602. * Gets the layer id use to find what meshes are impacted by the light.
  21603. * Inactive if 0
  21604. */
  21605. get: function () {
  21606. return this._includeOnlyWithLayerMask;
  21607. },
  21608. /**
  21609. * Sets the layer id use to find what meshes are impacted by the light.
  21610. * Inactive if 0
  21611. */
  21612. set: function (value) {
  21613. this._includeOnlyWithLayerMask = value;
  21614. this._resyncMeshes();
  21615. },
  21616. enumerable: true,
  21617. configurable: true
  21618. });
  21619. Object.defineProperty(Light.prototype, "lightmapMode", {
  21620. /**
  21621. * Gets the lightmap mode of this light (should be one of the constants defined by Light.LIGHTMAP_x)
  21622. */
  21623. get: function () {
  21624. return this._lightmapMode;
  21625. },
  21626. /**
  21627. * Sets the lightmap mode of this light (should be one of the constants defined by Light.LIGHTMAP_x)
  21628. */
  21629. set: function (value) {
  21630. if (this._lightmapMode === value) {
  21631. return;
  21632. }
  21633. this._lightmapMode = value;
  21634. this._markMeshesAsLightDirty();
  21635. },
  21636. enumerable: true,
  21637. configurable: true
  21638. });
  21639. /**
  21640. * Returns the string "Light".
  21641. * @returns the class name
  21642. */
  21643. Light.prototype.getClassName = function () {
  21644. return "Light";
  21645. };
  21646. /**
  21647. * Converts the light information to a readable string for debug purpose.
  21648. * @param fullDetails Supports for multiple levels of logging within scene loading
  21649. * @returns the human readable light info
  21650. */
  21651. Light.prototype.toString = function (fullDetails) {
  21652. var ret = "Name: " + this.name;
  21653. ret += ", type: " + (["Point", "Directional", "Spot", "Hemispheric"])[this.getTypeID()];
  21654. if (this.animations) {
  21655. for (var i = 0; i < this.animations.length; i++) {
  21656. ret += ", animation[0]: " + this.animations[i].toString(fullDetails);
  21657. }
  21658. }
  21659. if (fullDetails) {
  21660. }
  21661. return ret;
  21662. };
  21663. /**
  21664. * Set the enabled state of this node.
  21665. * @param value - the new enabled state
  21666. */
  21667. Light.prototype.setEnabled = function (value) {
  21668. _super.prototype.setEnabled.call(this, value);
  21669. this._resyncMeshes();
  21670. };
  21671. /**
  21672. * Returns the Light associated shadow generator if any.
  21673. * @return the associated shadow generator.
  21674. */
  21675. Light.prototype.getShadowGenerator = function () {
  21676. return this._shadowGenerator;
  21677. };
  21678. /**
  21679. * Returns a Vector3, the absolute light position in the World.
  21680. * @returns the world space position of the light
  21681. */
  21682. Light.prototype.getAbsolutePosition = function () {
  21683. return BABYLON.Vector3.Zero();
  21684. };
  21685. /**
  21686. * Specifies if the light will affect the passed mesh.
  21687. * @param mesh The mesh to test against the light
  21688. * @return true the mesh is affected otherwise, false.
  21689. */
  21690. Light.prototype.canAffectMesh = function (mesh) {
  21691. if (!mesh) {
  21692. return true;
  21693. }
  21694. if (this.includedOnlyMeshes && this.includedOnlyMeshes.length > 0 && this.includedOnlyMeshes.indexOf(mesh) === -1) {
  21695. return false;
  21696. }
  21697. if (this.excludedMeshes && this.excludedMeshes.length > 0 && this.excludedMeshes.indexOf(mesh) !== -1) {
  21698. return false;
  21699. }
  21700. if (this.includeOnlyWithLayerMask !== 0 && (this.includeOnlyWithLayerMask & mesh.layerMask) === 0) {
  21701. return false;
  21702. }
  21703. if (this.excludeWithLayerMask !== 0 && this.excludeWithLayerMask & mesh.layerMask) {
  21704. return false;
  21705. }
  21706. return true;
  21707. };
  21708. /**
  21709. * Computes and Returns the light World matrix.
  21710. * @returns the world matrix
  21711. */
  21712. Light.prototype.getWorldMatrix = function () {
  21713. this._currentRenderId = this.getScene().getRenderId();
  21714. this._childRenderId = this._currentRenderId;
  21715. var worldMatrix = this._getWorldMatrix();
  21716. if (this.parent && this.parent.getWorldMatrix) {
  21717. if (!this._parentedWorldMatrix) {
  21718. this._parentedWorldMatrix = BABYLON.Matrix.Identity();
  21719. }
  21720. worldMatrix.multiplyToRef(this.parent.getWorldMatrix(), this._parentedWorldMatrix);
  21721. this._markSyncedWithParent();
  21722. return this._parentedWorldMatrix;
  21723. }
  21724. return worldMatrix;
  21725. };
  21726. /**
  21727. * Sort function to order lights for rendering.
  21728. * @param a First Light object to compare to second.
  21729. * @param b Second Light object to compare first.
  21730. * @return -1 to reduce's a's index relative to be, 0 for no change, 1 to increase a's index relative to b.
  21731. */
  21732. Light.CompareLightsPriority = function (a, b) {
  21733. //shadow-casting lights have priority over non-shadow-casting lights
  21734. //the renderPrioirty is a secondary sort criterion
  21735. if (a.shadowEnabled !== b.shadowEnabled) {
  21736. return (b.shadowEnabled ? 1 : 0) - (a.shadowEnabled ? 1 : 0);
  21737. }
  21738. return b.renderPriority - a.renderPriority;
  21739. };
  21740. /**
  21741. * Releases resources associated with this node.
  21742. * @param doNotRecurse Set to true to not recurse into each children (recurse into each children by default)
  21743. * @param disposeMaterialAndTextures Set to true to also dispose referenced materials and textures (false by default)
  21744. */
  21745. Light.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  21746. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  21747. if (this._shadowGenerator) {
  21748. this._shadowGenerator.dispose();
  21749. this._shadowGenerator = null;
  21750. }
  21751. // Animations
  21752. this.getScene().stopAnimation(this);
  21753. // Remove from meshes
  21754. for (var _i = 0, _a = this.getScene().meshes; _i < _a.length; _i++) {
  21755. var mesh = _a[_i];
  21756. mesh._removeLightSource(this);
  21757. }
  21758. this._uniformBuffer.dispose();
  21759. // Remove from scene
  21760. this.getScene().removeLight(this);
  21761. _super.prototype.dispose.call(this, doNotRecurse, disposeMaterialAndTextures);
  21762. };
  21763. /**
  21764. * Returns the light type ID (integer).
  21765. * @returns The light Type id as a constant defines in Light.LIGHTTYPEID_x
  21766. */
  21767. Light.prototype.getTypeID = function () {
  21768. return 0;
  21769. };
  21770. /**
  21771. * Returns the intensity scaled by the Photometric Scale according to the light type and intensity mode.
  21772. * @returns the scaled intensity in intensity mode unit
  21773. */
  21774. Light.prototype.getScaledIntensity = function () {
  21775. return this._photometricScale * this.intensity;
  21776. };
  21777. /**
  21778. * Returns a new Light object, named "name", from the current one.
  21779. * @param name The name of the cloned light
  21780. * @returns the new created light
  21781. */
  21782. Light.prototype.clone = function (name) {
  21783. var constructor = Light.GetConstructorFromName(this.getTypeID(), name, this.getScene());
  21784. if (!constructor) {
  21785. return null;
  21786. }
  21787. return BABYLON.SerializationHelper.Clone(constructor, this);
  21788. };
  21789. /**
  21790. * Serializes the current light into a Serialization object.
  21791. * @returns the serialized object.
  21792. */
  21793. Light.prototype.serialize = function () {
  21794. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  21795. // Type
  21796. serializationObject.type = this.getTypeID();
  21797. // Parent
  21798. if (this.parent) {
  21799. serializationObject.parentId = this.parent.id;
  21800. }
  21801. // Inclusion / exclusions
  21802. if (this.excludedMeshes.length > 0) {
  21803. serializationObject.excludedMeshesIds = [];
  21804. this.excludedMeshes.forEach(function (mesh) {
  21805. serializationObject.excludedMeshesIds.push(mesh.id);
  21806. });
  21807. }
  21808. if (this.includedOnlyMeshes.length > 0) {
  21809. serializationObject.includedOnlyMeshesIds = [];
  21810. this.includedOnlyMeshes.forEach(function (mesh) {
  21811. serializationObject.includedOnlyMeshesIds.push(mesh.id);
  21812. });
  21813. }
  21814. // Animations
  21815. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  21816. serializationObject.ranges = this.serializeAnimationRanges();
  21817. return serializationObject;
  21818. };
  21819. /**
  21820. * Creates a new typed light from the passed type (integer) : point light = 0, directional light = 1, spot light = 2, hemispheric light = 3.
  21821. * This new light is named "name" and added to the passed scene.
  21822. * @param type Type according to the types available in Light.LIGHTTYPEID_x
  21823. * @param name The friendly name of the light
  21824. * @param scene The scene the new light will belong to
  21825. * @returns the constructor function
  21826. */
  21827. Light.GetConstructorFromName = function (type, name, scene) {
  21828. switch (type) {
  21829. case 0:
  21830. return function () { return new BABYLON.PointLight(name, BABYLON.Vector3.Zero(), scene); };
  21831. case 1:
  21832. return function () { return new BABYLON.DirectionalLight(name, BABYLON.Vector3.Zero(), scene); };
  21833. case 2:
  21834. return function () { return new BABYLON.SpotLight(name, BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), 0, 0, scene); };
  21835. case 3:
  21836. return function () { return new BABYLON.HemisphericLight(name, BABYLON.Vector3.Zero(), scene); };
  21837. }
  21838. return null;
  21839. };
  21840. /**
  21841. * Parses the passed "parsedLight" and returns a new instanced Light from this parsing.
  21842. * @param parsedLight The JSON representation of the light
  21843. * @param scene The scene to create the parsed light in
  21844. * @returns the created light after parsing
  21845. */
  21846. Light.Parse = function (parsedLight, scene) {
  21847. var constructor = Light.GetConstructorFromName(parsedLight.type, parsedLight.name, scene);
  21848. if (!constructor) {
  21849. return null;
  21850. }
  21851. var light = BABYLON.SerializationHelper.Parse(constructor, parsedLight, scene);
  21852. // Inclusion / exclusions
  21853. if (parsedLight.excludedMeshesIds) {
  21854. light._excludedMeshesIds = parsedLight.excludedMeshesIds;
  21855. }
  21856. if (parsedLight.includedOnlyMeshesIds) {
  21857. light._includedOnlyMeshesIds = parsedLight.includedOnlyMeshesIds;
  21858. }
  21859. // Parent
  21860. if (parsedLight.parentId) {
  21861. light._waitingParentId = parsedLight.parentId;
  21862. }
  21863. // Animations
  21864. if (parsedLight.animations) {
  21865. for (var animationIndex = 0; animationIndex < parsedLight.animations.length; animationIndex++) {
  21866. var parsedAnimation = parsedLight.animations[animationIndex];
  21867. light.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  21868. }
  21869. BABYLON.Node.ParseAnimationRanges(light, parsedLight, scene);
  21870. }
  21871. if (parsedLight.autoAnimate) {
  21872. scene.beginAnimation(light, parsedLight.autoAnimateFrom, parsedLight.autoAnimateTo, parsedLight.autoAnimateLoop, parsedLight.autoAnimateSpeed || 1.0);
  21873. }
  21874. return light;
  21875. };
  21876. Light.prototype._hookArrayForExcluded = function (array) {
  21877. var _this = this;
  21878. var oldPush = array.push;
  21879. array.push = function () {
  21880. var items = [];
  21881. for (var _i = 0; _i < arguments.length; _i++) {
  21882. items[_i] = arguments[_i];
  21883. }
  21884. var result = oldPush.apply(array, items);
  21885. for (var _a = 0, items_1 = items; _a < items_1.length; _a++) {
  21886. var item = items_1[_a];
  21887. item._resyncLighSource(_this);
  21888. }
  21889. return result;
  21890. };
  21891. var oldSplice = array.splice;
  21892. array.splice = function (index, deleteCount) {
  21893. var deleted = oldSplice.apply(array, [index, deleteCount]);
  21894. for (var _i = 0, deleted_1 = deleted; _i < deleted_1.length; _i++) {
  21895. var item = deleted_1[_i];
  21896. item._resyncLighSource(_this);
  21897. }
  21898. return deleted;
  21899. };
  21900. for (var _i = 0, array_1 = array; _i < array_1.length; _i++) {
  21901. var item = array_1[_i];
  21902. item._resyncLighSource(this);
  21903. }
  21904. };
  21905. Light.prototype._hookArrayForIncludedOnly = function (array) {
  21906. var _this = this;
  21907. var oldPush = array.push;
  21908. array.push = function () {
  21909. var items = [];
  21910. for (var _i = 0; _i < arguments.length; _i++) {
  21911. items[_i] = arguments[_i];
  21912. }
  21913. var result = oldPush.apply(array, items);
  21914. _this._resyncMeshes();
  21915. return result;
  21916. };
  21917. var oldSplice = array.splice;
  21918. array.splice = function (index, deleteCount) {
  21919. var deleted = oldSplice.apply(array, [index, deleteCount]);
  21920. _this._resyncMeshes();
  21921. return deleted;
  21922. };
  21923. this._resyncMeshes();
  21924. };
  21925. Light.prototype._resyncMeshes = function () {
  21926. for (var _i = 0, _a = this.getScene().meshes; _i < _a.length; _i++) {
  21927. var mesh = _a[_i];
  21928. mesh._resyncLighSource(this);
  21929. }
  21930. };
  21931. /**
  21932. * Forces the meshes to update their light related information in their rendering used effects
  21933. * @hidden Internal Use Only
  21934. */
  21935. Light.prototype._markMeshesAsLightDirty = function () {
  21936. for (var _i = 0, _a = this.getScene().meshes; _i < _a.length; _i++) {
  21937. var mesh = _a[_i];
  21938. if (mesh._lightSources.indexOf(this) !== -1) {
  21939. mesh._markSubMeshesAsLightDirty();
  21940. }
  21941. }
  21942. };
  21943. /**
  21944. * Recomputes the cached photometric scale if needed.
  21945. */
  21946. Light.prototype._computePhotometricScale = function () {
  21947. this._photometricScale = this._getPhotometricScale();
  21948. this.getScene().resetCachedMaterial();
  21949. };
  21950. /**
  21951. * Returns the Photometric Scale according to the light type and intensity mode.
  21952. */
  21953. Light.prototype._getPhotometricScale = function () {
  21954. var photometricScale = 0.0;
  21955. var lightTypeID = this.getTypeID();
  21956. //get photometric mode
  21957. var photometricMode = this.intensityMode;
  21958. if (photometricMode === Light.INTENSITYMODE_AUTOMATIC) {
  21959. if (lightTypeID === Light.LIGHTTYPEID_DIRECTIONALLIGHT) {
  21960. photometricMode = Light.INTENSITYMODE_ILLUMINANCE;
  21961. }
  21962. else {
  21963. photometricMode = Light.INTENSITYMODE_LUMINOUSINTENSITY;
  21964. }
  21965. }
  21966. //compute photometric scale
  21967. switch (lightTypeID) {
  21968. case Light.LIGHTTYPEID_POINTLIGHT:
  21969. case Light.LIGHTTYPEID_SPOTLIGHT:
  21970. switch (photometricMode) {
  21971. case Light.INTENSITYMODE_LUMINOUSPOWER:
  21972. photometricScale = 1.0 / (4.0 * Math.PI);
  21973. break;
  21974. case Light.INTENSITYMODE_LUMINOUSINTENSITY:
  21975. photometricScale = 1.0;
  21976. break;
  21977. case Light.INTENSITYMODE_LUMINANCE:
  21978. photometricScale = this.radius * this.radius;
  21979. break;
  21980. }
  21981. break;
  21982. case Light.LIGHTTYPEID_DIRECTIONALLIGHT:
  21983. switch (photometricMode) {
  21984. case Light.INTENSITYMODE_ILLUMINANCE:
  21985. photometricScale = 1.0;
  21986. break;
  21987. case Light.INTENSITYMODE_LUMINANCE:
  21988. // When radius (and therefore solid angle) is non-zero a directional lights brightness can be specified via central (peak) luminance.
  21989. // For a directional light the 'radius' defines the angular radius (in radians) rather than world-space radius (e.g. in metres).
  21990. var apexAngleRadians = this.radius;
  21991. // Impose a minimum light angular size to avoid the light becoming an infinitely small angular light source (i.e. a dirac delta function).
  21992. apexAngleRadians = Math.max(apexAngleRadians, 0.001);
  21993. var solidAngle = 2.0 * Math.PI * (1.0 - Math.cos(apexAngleRadians));
  21994. photometricScale = solidAngle;
  21995. break;
  21996. }
  21997. break;
  21998. case Light.LIGHTTYPEID_HEMISPHERICLIGHT:
  21999. // No fall off in hemisperic light.
  22000. photometricScale = 1.0;
  22001. break;
  22002. }
  22003. return photometricScale;
  22004. };
  22005. /**
  22006. * Reorder the light in the scene according to their defined priority.
  22007. * @hidden Internal Use Only
  22008. */
  22009. Light.prototype._reorderLightsInScene = function () {
  22010. var scene = this.getScene();
  22011. if (this._renderPriority != 0) {
  22012. scene.requireLightSorting = true;
  22013. }
  22014. this.getScene().sortLightsByPriority();
  22015. };
  22016. //lightmapMode Consts
  22017. Light._LIGHTMAP_DEFAULT = 0;
  22018. Light._LIGHTMAP_SPECULAR = 1;
  22019. Light._LIGHTMAP_SHADOWSONLY = 2;
  22020. // Intensity Mode Consts
  22021. Light._INTENSITYMODE_AUTOMATIC = 0;
  22022. Light._INTENSITYMODE_LUMINOUSPOWER = 1;
  22023. Light._INTENSITYMODE_LUMINOUSINTENSITY = 2;
  22024. Light._INTENSITYMODE_ILLUMINANCE = 3;
  22025. Light._INTENSITYMODE_LUMINANCE = 4;
  22026. // Light types ids const.
  22027. Light._LIGHTTYPEID_POINTLIGHT = 0;
  22028. Light._LIGHTTYPEID_DIRECTIONALLIGHT = 1;
  22029. Light._LIGHTTYPEID_SPOTLIGHT = 2;
  22030. Light._LIGHTTYPEID_HEMISPHERICLIGHT = 3;
  22031. __decorate([
  22032. BABYLON.serializeAsColor3()
  22033. ], Light.prototype, "diffuse", void 0);
  22034. __decorate([
  22035. BABYLON.serializeAsColor3()
  22036. ], Light.prototype, "specular", void 0);
  22037. __decorate([
  22038. BABYLON.serialize()
  22039. ], Light.prototype, "intensity", void 0);
  22040. __decorate([
  22041. BABYLON.serialize()
  22042. ], Light.prototype, "range", void 0);
  22043. __decorate([
  22044. BABYLON.serialize()
  22045. ], Light.prototype, "intensityMode", null);
  22046. __decorate([
  22047. BABYLON.serialize()
  22048. ], Light.prototype, "radius", null);
  22049. __decorate([
  22050. BABYLON.serialize()
  22051. ], Light.prototype, "_renderPriority", void 0);
  22052. __decorate([
  22053. BABYLON.expandToProperty("_reorderLightsInScene")
  22054. ], Light.prototype, "renderPriority", void 0);
  22055. __decorate([
  22056. BABYLON.serialize()
  22057. ], Light.prototype, "shadowEnabled", void 0);
  22058. __decorate([
  22059. BABYLON.serialize("excludeWithLayerMask")
  22060. ], Light.prototype, "_excludeWithLayerMask", void 0);
  22061. __decorate([
  22062. BABYLON.serialize("includeOnlyWithLayerMask")
  22063. ], Light.prototype, "_includeOnlyWithLayerMask", void 0);
  22064. __decorate([
  22065. BABYLON.serialize("lightmapMode")
  22066. ], Light.prototype, "_lightmapMode", void 0);
  22067. return Light;
  22068. }(BABYLON.Node));
  22069. BABYLON.Light = Light;
  22070. })(BABYLON || (BABYLON = {}));
  22071. //# sourceMappingURL=babylon.light.js.map
  22072. var BABYLON;
  22073. (function (BABYLON) {
  22074. var Camera = /** @class */ (function (_super) {
  22075. __extends(Camera, _super);
  22076. function Camera(name, position, scene, setActiveOnSceneIfNoneActive) {
  22077. if (setActiveOnSceneIfNoneActive === void 0) { setActiveOnSceneIfNoneActive = true; }
  22078. var _this = _super.call(this, name, scene) || this;
  22079. /**
  22080. * The vector the camera should consider as up.
  22081. * (default is Vector3(0, 1, 0) aka Vector3.Up())
  22082. */
  22083. _this.upVector = BABYLON.Vector3.Up();
  22084. _this.orthoLeft = null;
  22085. _this.orthoRight = null;
  22086. _this.orthoBottom = null;
  22087. _this.orthoTop = null;
  22088. /**
  22089. * FOV is set in Radians. (default is 0.8)
  22090. */
  22091. _this.fov = 0.8;
  22092. _this.minZ = 1;
  22093. _this.maxZ = 10000.0;
  22094. _this.inertia = 0.9;
  22095. _this.mode = Camera.PERSPECTIVE_CAMERA;
  22096. _this.isIntermediate = false;
  22097. _this.viewport = new BABYLON.Viewport(0, 0, 1.0, 1.0);
  22098. /**
  22099. * Restricts the camera to viewing objects with the same layerMask.
  22100. * A camera with a layerMask of 1 will render mesh.layerMask & camera.layerMask!== 0
  22101. */
  22102. _this.layerMask = 0x0FFFFFFF;
  22103. /**
  22104. * fovMode sets the camera frustum bounds to the viewport bounds. (default is FOVMODE_VERTICAL_FIXED)
  22105. */
  22106. _this.fovMode = Camera.FOVMODE_VERTICAL_FIXED;
  22107. // Camera rig members
  22108. _this.cameraRigMode = Camera.RIG_MODE_NONE;
  22109. _this._rigCameras = new Array();
  22110. _this._webvrViewMatrix = BABYLON.Matrix.Identity();
  22111. _this._skipRendering = false;
  22112. _this.customRenderTargets = new Array();
  22113. // Observables
  22114. _this.onViewMatrixChangedObservable = new BABYLON.Observable();
  22115. _this.onProjectionMatrixChangedObservable = new BABYLON.Observable();
  22116. _this.onAfterCheckInputsObservable = new BABYLON.Observable();
  22117. _this.onRestoreStateObservable = new BABYLON.Observable();
  22118. // Cache
  22119. _this._computedViewMatrix = BABYLON.Matrix.Identity();
  22120. _this._projectionMatrix = new BABYLON.Matrix();
  22121. _this._doNotComputeProjectionMatrix = false;
  22122. _this._worldMatrix = BABYLON.Matrix.Identity();
  22123. _this._postProcesses = new Array();
  22124. _this._transformMatrix = BABYLON.Matrix.Zero();
  22125. _this._activeMeshes = new BABYLON.SmartArray(256);
  22126. _this._globalPosition = BABYLON.Vector3.Zero();
  22127. _this._refreshFrustumPlanes = true;
  22128. _this.getScene().addCamera(_this);
  22129. if (setActiveOnSceneIfNoneActive && !_this.getScene().activeCamera) {
  22130. _this.getScene().activeCamera = _this;
  22131. }
  22132. _this.position = position;
  22133. return _this;
  22134. }
  22135. Object.defineProperty(Camera, "PERSPECTIVE_CAMERA", {
  22136. get: function () {
  22137. return Camera._PERSPECTIVE_CAMERA;
  22138. },
  22139. enumerable: true,
  22140. configurable: true
  22141. });
  22142. Object.defineProperty(Camera, "ORTHOGRAPHIC_CAMERA", {
  22143. get: function () {
  22144. return Camera._ORTHOGRAPHIC_CAMERA;
  22145. },
  22146. enumerable: true,
  22147. configurable: true
  22148. });
  22149. Object.defineProperty(Camera, "FOVMODE_VERTICAL_FIXED", {
  22150. /**
  22151. * This is the default FOV mode for perspective cameras.
  22152. * This setting aligns the upper and lower bounds of the viewport to the upper and lower bounds of the camera frustum.
  22153. *
  22154. */
  22155. get: function () {
  22156. return Camera._FOVMODE_VERTICAL_FIXED;
  22157. },
  22158. enumerable: true,
  22159. configurable: true
  22160. });
  22161. Object.defineProperty(Camera, "FOVMODE_HORIZONTAL_FIXED", {
  22162. /**
  22163. * This setting aligns the left and right bounds of the viewport to the left and right bounds of the camera frustum.
  22164. *
  22165. */
  22166. get: function () {
  22167. return Camera._FOVMODE_HORIZONTAL_FIXED;
  22168. },
  22169. enumerable: true,
  22170. configurable: true
  22171. });
  22172. Object.defineProperty(Camera, "RIG_MODE_NONE", {
  22173. get: function () {
  22174. return Camera._RIG_MODE_NONE;
  22175. },
  22176. enumerable: true,
  22177. configurable: true
  22178. });
  22179. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_ANAGLYPH", {
  22180. get: function () {
  22181. return Camera._RIG_MODE_STEREOSCOPIC_ANAGLYPH;
  22182. },
  22183. enumerable: true,
  22184. configurable: true
  22185. });
  22186. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL", {
  22187. get: function () {
  22188. return Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL;
  22189. },
  22190. enumerable: true,
  22191. configurable: true
  22192. });
  22193. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED", {
  22194. get: function () {
  22195. return Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED;
  22196. },
  22197. enumerable: true,
  22198. configurable: true
  22199. });
  22200. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_OVERUNDER", {
  22201. get: function () {
  22202. return Camera._RIG_MODE_STEREOSCOPIC_OVERUNDER;
  22203. },
  22204. enumerable: true,
  22205. configurable: true
  22206. });
  22207. Object.defineProperty(Camera, "RIG_MODE_VR", {
  22208. get: function () {
  22209. return Camera._RIG_MODE_VR;
  22210. },
  22211. enumerable: true,
  22212. configurable: true
  22213. });
  22214. Object.defineProperty(Camera, "RIG_MODE_WEBVR", {
  22215. get: function () {
  22216. return Camera._RIG_MODE_WEBVR;
  22217. },
  22218. enumerable: true,
  22219. configurable: true
  22220. });
  22221. /**
  22222. * Store current camera state (fov, position, etc..)
  22223. */
  22224. Camera.prototype.storeState = function () {
  22225. this._stateStored = true;
  22226. this._storedFov = this.fov;
  22227. return this;
  22228. };
  22229. /**
  22230. * Restores the camera state values if it has been stored. You must call storeState() first
  22231. */
  22232. Camera.prototype._restoreStateValues = function () {
  22233. if (!this._stateStored) {
  22234. return false;
  22235. }
  22236. this.fov = this._storedFov;
  22237. return true;
  22238. };
  22239. /**
  22240. * Restored camera state. You must call storeState() first
  22241. */
  22242. Camera.prototype.restoreState = function () {
  22243. if (this._restoreStateValues()) {
  22244. this.onRestoreStateObservable.notifyObservers(this);
  22245. return true;
  22246. }
  22247. return false;
  22248. };
  22249. Camera.prototype.getClassName = function () {
  22250. return "Camera";
  22251. };
  22252. /**
  22253. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  22254. */
  22255. Camera.prototype.toString = function (fullDetails) {
  22256. var ret = "Name: " + this.name;
  22257. ret += ", type: " + this.getClassName();
  22258. if (this.animations) {
  22259. for (var i = 0; i < this.animations.length; i++) {
  22260. ret += ", animation[0]: " + this.animations[i].toString(fullDetails);
  22261. }
  22262. }
  22263. if (fullDetails) {
  22264. }
  22265. return ret;
  22266. };
  22267. Object.defineProperty(Camera.prototype, "globalPosition", {
  22268. get: function () {
  22269. return this._globalPosition;
  22270. },
  22271. enumerable: true,
  22272. configurable: true
  22273. });
  22274. Camera.prototype.getActiveMeshes = function () {
  22275. return this._activeMeshes;
  22276. };
  22277. Camera.prototype.isActiveMesh = function (mesh) {
  22278. return (this._activeMeshes.indexOf(mesh) !== -1);
  22279. };
  22280. /**
  22281. * Is this camera ready to be used/rendered
  22282. * @param completeCheck defines if a complete check (including post processes) has to be done (false by default)
  22283. * @return true if the camera is ready
  22284. */
  22285. Camera.prototype.isReady = function (completeCheck) {
  22286. if (completeCheck === void 0) { completeCheck = false; }
  22287. if (completeCheck) {
  22288. for (var _i = 0, _a = this._postProcesses; _i < _a.length; _i++) {
  22289. var pp = _a[_i];
  22290. if (pp && !pp.isReady()) {
  22291. return false;
  22292. }
  22293. }
  22294. }
  22295. return _super.prototype.isReady.call(this, completeCheck);
  22296. };
  22297. //Cache
  22298. Camera.prototype._initCache = function () {
  22299. _super.prototype._initCache.call(this);
  22300. this._cache.position = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  22301. this._cache.upVector = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  22302. this._cache.mode = undefined;
  22303. this._cache.minZ = undefined;
  22304. this._cache.maxZ = undefined;
  22305. this._cache.fov = undefined;
  22306. this._cache.fovMode = undefined;
  22307. this._cache.aspectRatio = undefined;
  22308. this._cache.orthoLeft = undefined;
  22309. this._cache.orthoRight = undefined;
  22310. this._cache.orthoBottom = undefined;
  22311. this._cache.orthoTop = undefined;
  22312. this._cache.renderWidth = undefined;
  22313. this._cache.renderHeight = undefined;
  22314. };
  22315. Camera.prototype._updateCache = function (ignoreParentClass) {
  22316. if (!ignoreParentClass) {
  22317. _super.prototype._updateCache.call(this);
  22318. }
  22319. this._cache.position.copyFrom(this.position);
  22320. this._cache.upVector.copyFrom(this.upVector);
  22321. };
  22322. // Synchronized
  22323. Camera.prototype._isSynchronized = function () {
  22324. return this._isSynchronizedViewMatrix() && this._isSynchronizedProjectionMatrix();
  22325. };
  22326. Camera.prototype._isSynchronizedViewMatrix = function () {
  22327. if (!_super.prototype._isSynchronized.call(this))
  22328. return false;
  22329. return this._cache.position.equals(this.position)
  22330. && this._cache.upVector.equals(this.upVector)
  22331. && this.isSynchronizedWithParent();
  22332. };
  22333. Camera.prototype._isSynchronizedProjectionMatrix = function () {
  22334. var check = this._cache.mode === this.mode
  22335. && this._cache.minZ === this.minZ
  22336. && this._cache.maxZ === this.maxZ;
  22337. if (!check) {
  22338. return false;
  22339. }
  22340. var engine = this.getEngine();
  22341. if (this.mode === Camera.PERSPECTIVE_CAMERA) {
  22342. check = this._cache.fov === this.fov
  22343. && this._cache.fovMode === this.fovMode
  22344. && this._cache.aspectRatio === engine.getAspectRatio(this);
  22345. }
  22346. else {
  22347. check = this._cache.orthoLeft === this.orthoLeft
  22348. && this._cache.orthoRight === this.orthoRight
  22349. && this._cache.orthoBottom === this.orthoBottom
  22350. && this._cache.orthoTop === this.orthoTop
  22351. && this._cache.renderWidth === engine.getRenderWidth()
  22352. && this._cache.renderHeight === engine.getRenderHeight();
  22353. }
  22354. return check;
  22355. };
  22356. // Controls
  22357. Camera.prototype.attachControl = function (element, noPreventDefault) {
  22358. };
  22359. Camera.prototype.detachControl = function (element) {
  22360. };
  22361. Camera.prototype.update = function () {
  22362. this._checkInputs();
  22363. if (this.cameraRigMode !== Camera.RIG_MODE_NONE) {
  22364. this._updateRigCameras();
  22365. }
  22366. };
  22367. Camera.prototype._checkInputs = function () {
  22368. this.onAfterCheckInputsObservable.notifyObservers(this);
  22369. };
  22370. Object.defineProperty(Camera.prototype, "rigCameras", {
  22371. get: function () {
  22372. return this._rigCameras;
  22373. },
  22374. enumerable: true,
  22375. configurable: true
  22376. });
  22377. Object.defineProperty(Camera.prototype, "rigPostProcess", {
  22378. get: function () {
  22379. return this._rigPostProcess;
  22380. },
  22381. enumerable: true,
  22382. configurable: true
  22383. });
  22384. /**
  22385. * Internal, gets the first post proces.
  22386. * @returns the first post process to be run on this camera.
  22387. */
  22388. Camera.prototype._getFirstPostProcess = function () {
  22389. for (var ppIndex = 0; ppIndex < this._postProcesses.length; ppIndex++) {
  22390. if (this._postProcesses[ppIndex] !== null) {
  22391. return this._postProcesses[ppIndex];
  22392. }
  22393. }
  22394. return null;
  22395. };
  22396. Camera.prototype._cascadePostProcessesToRigCams = function () {
  22397. // invalidate framebuffer
  22398. var firstPostProcess = this._getFirstPostProcess();
  22399. if (firstPostProcess) {
  22400. firstPostProcess.markTextureDirty();
  22401. }
  22402. // glue the rigPostProcess to the end of the user postprocesses & assign to each sub-camera
  22403. for (var i = 0, len = this._rigCameras.length; i < len; i++) {
  22404. var cam = this._rigCameras[i];
  22405. var rigPostProcess = cam._rigPostProcess;
  22406. // for VR rig, there does not have to be a post process
  22407. if (rigPostProcess) {
  22408. var isPass = rigPostProcess instanceof BABYLON.PassPostProcess;
  22409. if (isPass) {
  22410. // any rig which has a PassPostProcess for rig[0], cannot be isIntermediate when there are also user postProcesses
  22411. cam.isIntermediate = this._postProcesses.length === 0;
  22412. }
  22413. cam._postProcesses = this._postProcesses.slice(0).concat(rigPostProcess);
  22414. rigPostProcess.markTextureDirty();
  22415. }
  22416. else {
  22417. cam._postProcesses = this._postProcesses.slice(0);
  22418. }
  22419. }
  22420. };
  22421. Camera.prototype.attachPostProcess = function (postProcess, insertAt) {
  22422. if (insertAt === void 0) { insertAt = null; }
  22423. if (!postProcess.isReusable() && this._postProcesses.indexOf(postProcess) > -1) {
  22424. BABYLON.Tools.Error("You're trying to reuse a post process not defined as reusable.");
  22425. return 0;
  22426. }
  22427. if (insertAt == null || insertAt < 0) {
  22428. this._postProcesses.push(postProcess);
  22429. }
  22430. else if (this._postProcesses[insertAt] === null) {
  22431. this._postProcesses[insertAt] = postProcess;
  22432. }
  22433. else {
  22434. this._postProcesses.splice(insertAt, 0, postProcess);
  22435. }
  22436. this._cascadePostProcessesToRigCams(); // also ensures framebuffer invalidated
  22437. return this._postProcesses.indexOf(postProcess);
  22438. };
  22439. Camera.prototype.detachPostProcess = function (postProcess) {
  22440. var idx = this._postProcesses.indexOf(postProcess);
  22441. if (idx !== -1) {
  22442. this._postProcesses[idx] = null;
  22443. }
  22444. this._cascadePostProcessesToRigCams(); // also ensures framebuffer invalidated
  22445. };
  22446. Camera.prototype.getWorldMatrix = function () {
  22447. if (this._isSynchronizedViewMatrix()) {
  22448. return this._worldMatrix;
  22449. }
  22450. // Getting the the view matrix will also compute the world matrix.
  22451. this.getViewMatrix();
  22452. return this._worldMatrix;
  22453. };
  22454. Camera.prototype._getViewMatrix = function () {
  22455. return BABYLON.Matrix.Identity();
  22456. };
  22457. Camera.prototype.getViewMatrix = function (force) {
  22458. if (!force && this._isSynchronizedViewMatrix()) {
  22459. return this._computedViewMatrix;
  22460. }
  22461. this.updateCache();
  22462. this._computedViewMatrix = this._getViewMatrix();
  22463. this._currentRenderId = this.getScene().getRenderId();
  22464. this._childRenderId = this._currentRenderId;
  22465. this._refreshFrustumPlanes = true;
  22466. if (this._cameraRigParams && this._cameraRigParams.vrPreViewMatrix) {
  22467. this._computedViewMatrix.multiplyToRef(this._cameraRigParams.vrPreViewMatrix, this._computedViewMatrix);
  22468. }
  22469. this.onViewMatrixChangedObservable.notifyObservers(this);
  22470. this._computedViewMatrix.invertToRef(this._worldMatrix);
  22471. return this._computedViewMatrix;
  22472. };
  22473. Camera.prototype.freezeProjectionMatrix = function (projection) {
  22474. this._doNotComputeProjectionMatrix = true;
  22475. if (projection !== undefined) {
  22476. this._projectionMatrix = projection;
  22477. }
  22478. };
  22479. ;
  22480. Camera.prototype.unfreezeProjectionMatrix = function () {
  22481. this._doNotComputeProjectionMatrix = false;
  22482. };
  22483. ;
  22484. Camera.prototype.getProjectionMatrix = function (force) {
  22485. if (this._doNotComputeProjectionMatrix || (!force && this._isSynchronizedProjectionMatrix())) {
  22486. return this._projectionMatrix;
  22487. }
  22488. // Cache
  22489. this._cache.mode = this.mode;
  22490. this._cache.minZ = this.minZ;
  22491. this._cache.maxZ = this.maxZ;
  22492. // Matrix
  22493. this._refreshFrustumPlanes = true;
  22494. var engine = this.getEngine();
  22495. var scene = this.getScene();
  22496. if (this.mode === Camera.PERSPECTIVE_CAMERA) {
  22497. this._cache.fov = this.fov;
  22498. this._cache.fovMode = this.fovMode;
  22499. this._cache.aspectRatio = engine.getAspectRatio(this);
  22500. if (this.minZ <= 0) {
  22501. this.minZ = 0.1;
  22502. }
  22503. if (scene.useRightHandedSystem) {
  22504. BABYLON.Matrix.PerspectiveFovRHToRef(this.fov, engine.getAspectRatio(this), this.minZ, this.maxZ, this._projectionMatrix, this.fovMode === Camera.FOVMODE_VERTICAL_FIXED);
  22505. }
  22506. else {
  22507. BABYLON.Matrix.PerspectiveFovLHToRef(this.fov, engine.getAspectRatio(this), this.minZ, this.maxZ, this._projectionMatrix, this.fovMode === Camera.FOVMODE_VERTICAL_FIXED);
  22508. }
  22509. }
  22510. else {
  22511. var halfWidth = engine.getRenderWidth() / 2.0;
  22512. var halfHeight = engine.getRenderHeight() / 2.0;
  22513. if (scene.useRightHandedSystem) {
  22514. BABYLON.Matrix.OrthoOffCenterRHToRef(this.orthoLeft || -halfWidth, this.orthoRight || halfWidth, this.orthoBottom || -halfHeight, this.orthoTop || halfHeight, this.minZ, this.maxZ, this._projectionMatrix);
  22515. }
  22516. else {
  22517. BABYLON.Matrix.OrthoOffCenterLHToRef(this.orthoLeft || -halfWidth, this.orthoRight || halfWidth, this.orthoBottom || -halfHeight, this.orthoTop || halfHeight, this.minZ, this.maxZ, this._projectionMatrix);
  22518. }
  22519. this._cache.orthoLeft = this.orthoLeft;
  22520. this._cache.orthoRight = this.orthoRight;
  22521. this._cache.orthoBottom = this.orthoBottom;
  22522. this._cache.orthoTop = this.orthoTop;
  22523. this._cache.renderWidth = engine.getRenderWidth();
  22524. this._cache.renderHeight = engine.getRenderHeight();
  22525. }
  22526. this.onProjectionMatrixChangedObservable.notifyObservers(this);
  22527. return this._projectionMatrix;
  22528. };
  22529. Camera.prototype.getTranformationMatrix = function () {
  22530. this._computedViewMatrix.multiplyToRef(this._projectionMatrix, this._transformMatrix);
  22531. return this._transformMatrix;
  22532. };
  22533. Camera.prototype.updateFrustumPlanes = function () {
  22534. if (!this._refreshFrustumPlanes) {
  22535. return;
  22536. }
  22537. this.getTranformationMatrix();
  22538. if (!this._frustumPlanes) {
  22539. this._frustumPlanes = BABYLON.Frustum.GetPlanes(this._transformMatrix);
  22540. }
  22541. else {
  22542. BABYLON.Frustum.GetPlanesToRef(this._transformMatrix, this._frustumPlanes);
  22543. }
  22544. this._refreshFrustumPlanes = false;
  22545. };
  22546. Camera.prototype.isInFrustum = function (target) {
  22547. this.updateFrustumPlanes();
  22548. return target.isInFrustum(this._frustumPlanes);
  22549. };
  22550. Camera.prototype.isCompletelyInFrustum = function (target) {
  22551. this.updateFrustumPlanes();
  22552. return target.isCompletelyInFrustum(this._frustumPlanes);
  22553. };
  22554. Camera.prototype.getForwardRay = function (length, transform, origin) {
  22555. if (length === void 0) { length = 100; }
  22556. if (!transform) {
  22557. transform = this.getWorldMatrix();
  22558. }
  22559. if (!origin) {
  22560. origin = this.position;
  22561. }
  22562. var forward = new BABYLON.Vector3(0, 0, 1);
  22563. var forwardWorld = BABYLON.Vector3.TransformNormal(forward, transform);
  22564. var direction = BABYLON.Vector3.Normalize(forwardWorld);
  22565. return new BABYLON.Ray(origin, direction, length);
  22566. };
  22567. /**
  22568. * Releases resources associated with this node.
  22569. * @param doNotRecurse Set to true to not recurse into each children (recurse into each children by default)
  22570. * @param disposeMaterialAndTextures Set to true to also dispose referenced materials and textures (false by default)
  22571. */
  22572. Camera.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  22573. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  22574. // Observables
  22575. this.onViewMatrixChangedObservable.clear();
  22576. this.onProjectionMatrixChangedObservable.clear();
  22577. this.onAfterCheckInputsObservable.clear();
  22578. this.onRestoreStateObservable.clear();
  22579. // Inputs
  22580. if (this.inputs) {
  22581. this.inputs.clear();
  22582. }
  22583. // Animations
  22584. this.getScene().stopAnimation(this);
  22585. // Remove from scene
  22586. this.getScene().removeCamera(this);
  22587. while (this._rigCameras.length > 0) {
  22588. var camera = this._rigCameras.pop();
  22589. if (camera) {
  22590. camera.dispose();
  22591. }
  22592. }
  22593. // Postprocesses
  22594. if (this._rigPostProcess) {
  22595. this._rigPostProcess.dispose(this);
  22596. this._rigPostProcess = null;
  22597. this._postProcesses = [];
  22598. }
  22599. else if (this.cameraRigMode !== Camera.RIG_MODE_NONE) {
  22600. this._rigPostProcess = null;
  22601. this._postProcesses = [];
  22602. }
  22603. else {
  22604. var i = this._postProcesses.length;
  22605. while (--i >= 0) {
  22606. var postProcess = this._postProcesses[i];
  22607. if (postProcess) {
  22608. postProcess.dispose(this);
  22609. }
  22610. }
  22611. }
  22612. // Render targets
  22613. var i = this.customRenderTargets.length;
  22614. while (--i >= 0) {
  22615. this.customRenderTargets[i].dispose();
  22616. }
  22617. this.customRenderTargets = [];
  22618. // Active Meshes
  22619. this._activeMeshes.dispose();
  22620. _super.prototype.dispose.call(this, doNotRecurse, disposeMaterialAndTextures);
  22621. };
  22622. Object.defineProperty(Camera.prototype, "leftCamera", {
  22623. // ---- Camera rigs section ----
  22624. get: function () {
  22625. if (this._rigCameras.length < 1) {
  22626. return null;
  22627. }
  22628. return this._rigCameras[0];
  22629. },
  22630. enumerable: true,
  22631. configurable: true
  22632. });
  22633. Object.defineProperty(Camera.prototype, "rightCamera", {
  22634. get: function () {
  22635. if (this._rigCameras.length < 2) {
  22636. return null;
  22637. }
  22638. return this._rigCameras[1];
  22639. },
  22640. enumerable: true,
  22641. configurable: true
  22642. });
  22643. Camera.prototype.getLeftTarget = function () {
  22644. if (this._rigCameras.length < 1) {
  22645. return null;
  22646. }
  22647. return this._rigCameras[0].getTarget();
  22648. };
  22649. Camera.prototype.getRightTarget = function () {
  22650. if (this._rigCameras.length < 2) {
  22651. return null;
  22652. }
  22653. return this._rigCameras[1].getTarget();
  22654. };
  22655. Camera.prototype.setCameraRigMode = function (mode, rigParams) {
  22656. if (this.cameraRigMode === mode) {
  22657. return;
  22658. }
  22659. while (this._rigCameras.length > 0) {
  22660. var camera = this._rigCameras.pop();
  22661. if (camera) {
  22662. camera.dispose();
  22663. }
  22664. }
  22665. this.cameraRigMode = mode;
  22666. this._cameraRigParams = {};
  22667. //we have to implement stereo camera calcultating left and right viewpoints from interaxialDistance and target,
  22668. //not from a given angle as it is now, but until that complete code rewriting provisional stereoHalfAngle value is introduced
  22669. this._cameraRigParams.interaxialDistance = rigParams.interaxialDistance || 0.0637;
  22670. this._cameraRigParams.stereoHalfAngle = BABYLON.Tools.ToRadians(this._cameraRigParams.interaxialDistance / 0.0637);
  22671. // create the rig cameras, unless none
  22672. if (this.cameraRigMode !== Camera.RIG_MODE_NONE) {
  22673. var leftCamera = this.createRigCamera(this.name + "_L", 0);
  22674. var rightCamera = this.createRigCamera(this.name + "_R", 1);
  22675. if (leftCamera && rightCamera) {
  22676. this._rigCameras.push(leftCamera);
  22677. this._rigCameras.push(rightCamera);
  22678. }
  22679. }
  22680. switch (this.cameraRigMode) {
  22681. case Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  22682. this._rigCameras[0]._rigPostProcess = new BABYLON.PassPostProcess(this.name + "_passthru", 1.0, this._rigCameras[0]);
  22683. this._rigCameras[1]._rigPostProcess = new BABYLON.AnaglyphPostProcess(this.name + "_anaglyph", 1.0, this._rigCameras);
  22684. break;
  22685. case Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  22686. case Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  22687. case Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  22688. var isStereoscopicHoriz = this.cameraRigMode === Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL || this.cameraRigMode === Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED;
  22689. this._rigCameras[0]._rigPostProcess = new BABYLON.PassPostProcess(this.name + "_passthru", 1.0, this._rigCameras[0]);
  22690. this._rigCameras[1]._rigPostProcess = new BABYLON.StereoscopicInterlacePostProcess(this.name + "_stereoInterlace", this._rigCameras, isStereoscopicHoriz);
  22691. break;
  22692. case Camera.RIG_MODE_VR:
  22693. var metrics = rigParams.vrCameraMetrics || BABYLON.VRCameraMetrics.GetDefault();
  22694. this._rigCameras[0]._cameraRigParams.vrMetrics = metrics;
  22695. this._rigCameras[0].viewport = new BABYLON.Viewport(0, 0, 0.5, 1.0);
  22696. this._rigCameras[0]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  22697. this._rigCameras[0]._cameraRigParams.vrHMatrix = metrics.leftHMatrix;
  22698. this._rigCameras[0]._cameraRigParams.vrPreViewMatrix = metrics.leftPreViewMatrix;
  22699. this._rigCameras[0].getProjectionMatrix = this._rigCameras[0]._getVRProjectionMatrix;
  22700. this._rigCameras[1]._cameraRigParams.vrMetrics = metrics;
  22701. this._rigCameras[1].viewport = new BABYLON.Viewport(0.5, 0, 0.5, 1.0);
  22702. this._rigCameras[1]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  22703. this._rigCameras[1]._cameraRigParams.vrHMatrix = metrics.rightHMatrix;
  22704. this._rigCameras[1]._cameraRigParams.vrPreViewMatrix = metrics.rightPreViewMatrix;
  22705. this._rigCameras[1].getProjectionMatrix = this._rigCameras[1]._getVRProjectionMatrix;
  22706. if (metrics.compensateDistortion) {
  22707. this._rigCameras[0]._rigPostProcess = new BABYLON.VRDistortionCorrectionPostProcess("VR_Distort_Compensation_Left", this._rigCameras[0], false, metrics);
  22708. this._rigCameras[1]._rigPostProcess = new BABYLON.VRDistortionCorrectionPostProcess("VR_Distort_Compensation_Right", this._rigCameras[1], true, metrics);
  22709. }
  22710. break;
  22711. case Camera.RIG_MODE_WEBVR:
  22712. if (rigParams.vrDisplay) {
  22713. var leftEye = rigParams.vrDisplay.getEyeParameters('left');
  22714. var rightEye = rigParams.vrDisplay.getEyeParameters('right');
  22715. //Left eye
  22716. this._rigCameras[0].viewport = new BABYLON.Viewport(0, 0, 0.5, 1.0);
  22717. this._rigCameras[0].setCameraRigParameter("left", true);
  22718. //leaving this for future reference
  22719. this._rigCameras[0].setCameraRigParameter("specs", rigParams.specs);
  22720. this._rigCameras[0].setCameraRigParameter("eyeParameters", leftEye);
  22721. this._rigCameras[0].setCameraRigParameter("frameData", rigParams.frameData);
  22722. this._rigCameras[0].setCameraRigParameter("parentCamera", rigParams.parentCamera);
  22723. this._rigCameras[0]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  22724. this._rigCameras[0].getProjectionMatrix = this._getWebVRProjectionMatrix;
  22725. this._rigCameras[0].parent = this;
  22726. this._rigCameras[0]._getViewMatrix = this._getWebVRViewMatrix;
  22727. //Right eye
  22728. this._rigCameras[1].viewport = new BABYLON.Viewport(0.5, 0, 0.5, 1.0);
  22729. this._rigCameras[1].setCameraRigParameter('eyeParameters', rightEye);
  22730. this._rigCameras[1].setCameraRigParameter("specs", rigParams.specs);
  22731. this._rigCameras[1].setCameraRigParameter("frameData", rigParams.frameData);
  22732. this._rigCameras[1].setCameraRigParameter("parentCamera", rigParams.parentCamera);
  22733. this._rigCameras[1]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  22734. this._rigCameras[1].getProjectionMatrix = this._getWebVRProjectionMatrix;
  22735. this._rigCameras[1].parent = this;
  22736. this._rigCameras[1]._getViewMatrix = this._getWebVRViewMatrix;
  22737. if (Camera.UseAlternateWebVRRendering) {
  22738. this._rigCameras[1]._skipRendering = true;
  22739. this._rigCameras[0]._alternateCamera = this._rigCameras[1];
  22740. }
  22741. }
  22742. break;
  22743. }
  22744. this._cascadePostProcessesToRigCams();
  22745. this.update();
  22746. };
  22747. Camera.prototype._getVRProjectionMatrix = function () {
  22748. BABYLON.Matrix.PerspectiveFovLHToRef(this._cameraRigParams.vrMetrics.aspectRatioFov, this._cameraRigParams.vrMetrics.aspectRatio, this.minZ, this.maxZ, this._cameraRigParams.vrWorkMatrix);
  22749. this._cameraRigParams.vrWorkMatrix.multiplyToRef(this._cameraRigParams.vrHMatrix, this._projectionMatrix);
  22750. return this._projectionMatrix;
  22751. };
  22752. Camera.prototype._updateCameraRotationMatrix = function () {
  22753. //Here for WebVR
  22754. };
  22755. Camera.prototype._updateWebVRCameraRotationMatrix = function () {
  22756. //Here for WebVR
  22757. };
  22758. /**
  22759. * This function MUST be overwritten by the different WebVR cameras available.
  22760. * The context in which it is running is the RIG camera. So 'this' is the TargetCamera, left or right.
  22761. */
  22762. Camera.prototype._getWebVRProjectionMatrix = function () {
  22763. return BABYLON.Matrix.Identity();
  22764. };
  22765. /**
  22766. * This function MUST be overwritten by the different WebVR cameras available.
  22767. * The context in which it is running is the RIG camera. So 'this' is the TargetCamera, left or right.
  22768. */
  22769. Camera.prototype._getWebVRViewMatrix = function () {
  22770. return BABYLON.Matrix.Identity();
  22771. };
  22772. Camera.prototype.setCameraRigParameter = function (name, value) {
  22773. if (!this._cameraRigParams) {
  22774. this._cameraRigParams = {};
  22775. }
  22776. this._cameraRigParams[name] = value;
  22777. //provisionnally:
  22778. if (name === "interaxialDistance") {
  22779. this._cameraRigParams.stereoHalfAngle = BABYLON.Tools.ToRadians(value / 0.0637);
  22780. }
  22781. };
  22782. /**
  22783. * needs to be overridden by children so sub has required properties to be copied
  22784. */
  22785. Camera.prototype.createRigCamera = function (name, cameraIndex) {
  22786. return null;
  22787. };
  22788. /**
  22789. * May need to be overridden by children
  22790. */
  22791. Camera.prototype._updateRigCameras = function () {
  22792. for (var i = 0; i < this._rigCameras.length; i++) {
  22793. this._rigCameras[i].minZ = this.minZ;
  22794. this._rigCameras[i].maxZ = this.maxZ;
  22795. this._rigCameras[i].fov = this.fov;
  22796. }
  22797. // only update viewport when ANAGLYPH
  22798. if (this.cameraRigMode === Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH) {
  22799. this._rigCameras[0].viewport = this._rigCameras[1].viewport = this.viewport;
  22800. }
  22801. };
  22802. Camera.prototype._setupInputs = function () {
  22803. };
  22804. Camera.prototype.serialize = function () {
  22805. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  22806. // Type
  22807. serializationObject.type = this.getClassName();
  22808. // Parent
  22809. if (this.parent) {
  22810. serializationObject.parentId = this.parent.id;
  22811. }
  22812. if (this.inputs) {
  22813. this.inputs.serialize(serializationObject);
  22814. }
  22815. // Animations
  22816. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  22817. serializationObject.ranges = this.serializeAnimationRanges();
  22818. return serializationObject;
  22819. };
  22820. Camera.prototype.clone = function (name) {
  22821. return BABYLON.SerializationHelper.Clone(Camera.GetConstructorFromName(this.getClassName(), name, this.getScene(), this.interaxialDistance, this.isStereoscopicSideBySide), this);
  22822. };
  22823. Camera.prototype.getDirection = function (localAxis) {
  22824. var result = BABYLON.Vector3.Zero();
  22825. this.getDirectionToRef(localAxis, result);
  22826. return result;
  22827. };
  22828. Camera.prototype.getDirectionToRef = function (localAxis, result) {
  22829. BABYLON.Vector3.TransformNormalToRef(localAxis, this.getWorldMatrix(), result);
  22830. };
  22831. Camera.GetConstructorFromName = function (type, name, scene, interaxial_distance, isStereoscopicSideBySide) {
  22832. if (interaxial_distance === void 0) { interaxial_distance = 0; }
  22833. if (isStereoscopicSideBySide === void 0) { isStereoscopicSideBySide = true; }
  22834. switch (type) {
  22835. case "ArcRotateCamera":
  22836. return function () { return new BABYLON.ArcRotateCamera(name, 0, 0, 1.0, BABYLON.Vector3.Zero(), scene); };
  22837. case "DeviceOrientationCamera":
  22838. return function () { return new BABYLON.DeviceOrientationCamera(name, BABYLON.Vector3.Zero(), scene); };
  22839. case "FollowCamera":
  22840. return function () { return new BABYLON.FollowCamera(name, BABYLON.Vector3.Zero(), scene); };
  22841. case "ArcFollowCamera":
  22842. return function () { return new BABYLON.ArcFollowCamera(name, 0, 0, 1.0, null, scene); };
  22843. case "GamepadCamera":
  22844. return function () { return new BABYLON.GamepadCamera(name, BABYLON.Vector3.Zero(), scene); };
  22845. case "TouchCamera":
  22846. return function () { return new BABYLON.TouchCamera(name, BABYLON.Vector3.Zero(), scene); };
  22847. case "VirtualJoysticksCamera":
  22848. return function () { return new BABYLON.VirtualJoysticksCamera(name, BABYLON.Vector3.Zero(), scene); };
  22849. case "WebVRFreeCamera":
  22850. return function () { return new BABYLON.WebVRFreeCamera(name, BABYLON.Vector3.Zero(), scene); };
  22851. case "WebVRGamepadCamera":
  22852. return function () { return new BABYLON.WebVRFreeCamera(name, BABYLON.Vector3.Zero(), scene); };
  22853. case "VRDeviceOrientationFreeCamera":
  22854. return function () { return new BABYLON.VRDeviceOrientationFreeCamera(name, BABYLON.Vector3.Zero(), scene); };
  22855. case "VRDeviceOrientationGamepadCamera":
  22856. return function () { return new BABYLON.VRDeviceOrientationGamepadCamera(name, BABYLON.Vector3.Zero(), scene); };
  22857. case "AnaglyphArcRotateCamera":
  22858. return function () { return new BABYLON.AnaglyphArcRotateCamera(name, 0, 0, 1.0, BABYLON.Vector3.Zero(), interaxial_distance, scene); };
  22859. case "AnaglyphFreeCamera":
  22860. return function () { return new BABYLON.AnaglyphFreeCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, scene); };
  22861. case "AnaglyphGamepadCamera":
  22862. return function () { return new BABYLON.AnaglyphGamepadCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, scene); };
  22863. case "AnaglyphUniversalCamera":
  22864. return function () { return new BABYLON.AnaglyphUniversalCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, scene); };
  22865. case "StereoscopicArcRotateCamera":
  22866. return function () { return new BABYLON.StereoscopicArcRotateCamera(name, 0, 0, 1.0, BABYLON.Vector3.Zero(), interaxial_distance, isStereoscopicSideBySide, scene); };
  22867. case "StereoscopicFreeCamera":
  22868. return function () { return new BABYLON.StereoscopicFreeCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, isStereoscopicSideBySide, scene); };
  22869. case "StereoscopicGamepadCamera":
  22870. return function () { return new BABYLON.StereoscopicGamepadCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, isStereoscopicSideBySide, scene); };
  22871. case "StereoscopicUniversalCamera":
  22872. return function () { return new BABYLON.StereoscopicUniversalCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, isStereoscopicSideBySide, scene); };
  22873. case "FreeCamera": // Forcing Universal here
  22874. return function () { return new BABYLON.UniversalCamera(name, BABYLON.Vector3.Zero(), scene); };
  22875. default: // Universal Camera is the default value
  22876. return function () { return new BABYLON.UniversalCamera(name, BABYLON.Vector3.Zero(), scene); };
  22877. }
  22878. };
  22879. Camera.prototype.computeWorldMatrix = function () {
  22880. return this.getWorldMatrix();
  22881. };
  22882. Camera.Parse = function (parsedCamera, scene) {
  22883. var type = parsedCamera.type;
  22884. var construct = Camera.GetConstructorFromName(type, parsedCamera.name, scene, parsedCamera.interaxial_distance, parsedCamera.isStereoscopicSideBySide);
  22885. var camera = BABYLON.SerializationHelper.Parse(construct, parsedCamera, scene);
  22886. // Parent
  22887. if (parsedCamera.parentId) {
  22888. camera._waitingParentId = parsedCamera.parentId;
  22889. }
  22890. //If camera has an input manager, let it parse inputs settings
  22891. if (camera.inputs) {
  22892. camera.inputs.parse(parsedCamera);
  22893. camera._setupInputs();
  22894. }
  22895. if (camera.setPosition) { // need to force position
  22896. camera.position.copyFromFloats(0, 0, 0);
  22897. camera.setPosition(BABYLON.Vector3.FromArray(parsedCamera.position));
  22898. }
  22899. // Target
  22900. if (parsedCamera.target) {
  22901. if (camera.setTarget) {
  22902. camera.setTarget(BABYLON.Vector3.FromArray(parsedCamera.target));
  22903. }
  22904. }
  22905. // Apply 3d rig, when found
  22906. if (parsedCamera.cameraRigMode) {
  22907. var rigParams = (parsedCamera.interaxial_distance) ? { interaxialDistance: parsedCamera.interaxial_distance } : {};
  22908. camera.setCameraRigMode(parsedCamera.cameraRigMode, rigParams);
  22909. }
  22910. // Animations
  22911. if (parsedCamera.animations) {
  22912. for (var animationIndex = 0; animationIndex < parsedCamera.animations.length; animationIndex++) {
  22913. var parsedAnimation = parsedCamera.animations[animationIndex];
  22914. camera.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  22915. }
  22916. BABYLON.Node.ParseAnimationRanges(camera, parsedCamera, scene);
  22917. }
  22918. if (parsedCamera.autoAnimate) {
  22919. scene.beginAnimation(camera, parsedCamera.autoAnimateFrom, parsedCamera.autoAnimateTo, parsedCamera.autoAnimateLoop, parsedCamera.autoAnimateSpeed || 1.0);
  22920. }
  22921. return camera;
  22922. };
  22923. // Statics
  22924. Camera._PERSPECTIVE_CAMERA = 0;
  22925. Camera._ORTHOGRAPHIC_CAMERA = 1;
  22926. Camera._FOVMODE_VERTICAL_FIXED = 0;
  22927. Camera._FOVMODE_HORIZONTAL_FIXED = 1;
  22928. Camera._RIG_MODE_NONE = 0;
  22929. Camera._RIG_MODE_STEREOSCOPIC_ANAGLYPH = 10;
  22930. Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL = 11;
  22931. Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED = 12;
  22932. Camera._RIG_MODE_STEREOSCOPIC_OVERUNDER = 13;
  22933. Camera._RIG_MODE_VR = 20;
  22934. Camera._RIG_MODE_WEBVR = 21;
  22935. Camera.ForceAttachControlToAlwaysPreventDefault = false;
  22936. Camera.UseAlternateWebVRRendering = false;
  22937. __decorate([
  22938. BABYLON.serializeAsVector3()
  22939. ], Camera.prototype, "position", void 0);
  22940. __decorate([
  22941. BABYLON.serializeAsVector3()
  22942. ], Camera.prototype, "upVector", void 0);
  22943. __decorate([
  22944. BABYLON.serialize()
  22945. ], Camera.prototype, "orthoLeft", void 0);
  22946. __decorate([
  22947. BABYLON.serialize()
  22948. ], Camera.prototype, "orthoRight", void 0);
  22949. __decorate([
  22950. BABYLON.serialize()
  22951. ], Camera.prototype, "orthoBottom", void 0);
  22952. __decorate([
  22953. BABYLON.serialize()
  22954. ], Camera.prototype, "orthoTop", void 0);
  22955. __decorate([
  22956. BABYLON.serialize()
  22957. ], Camera.prototype, "fov", void 0);
  22958. __decorate([
  22959. BABYLON.serialize()
  22960. ], Camera.prototype, "minZ", void 0);
  22961. __decorate([
  22962. BABYLON.serialize()
  22963. ], Camera.prototype, "maxZ", void 0);
  22964. __decorate([
  22965. BABYLON.serialize()
  22966. ], Camera.prototype, "inertia", void 0);
  22967. __decorate([
  22968. BABYLON.serialize()
  22969. ], Camera.prototype, "mode", void 0);
  22970. __decorate([
  22971. BABYLON.serialize()
  22972. ], Camera.prototype, "layerMask", void 0);
  22973. __decorate([
  22974. BABYLON.serialize()
  22975. ], Camera.prototype, "fovMode", void 0);
  22976. __decorate([
  22977. BABYLON.serialize()
  22978. ], Camera.prototype, "cameraRigMode", void 0);
  22979. __decorate([
  22980. BABYLON.serialize()
  22981. ], Camera.prototype, "interaxialDistance", void 0);
  22982. __decorate([
  22983. BABYLON.serialize()
  22984. ], Camera.prototype, "isStereoscopicSideBySide", void 0);
  22985. return Camera;
  22986. }(BABYLON.Node));
  22987. BABYLON.Camera = Camera;
  22988. })(BABYLON || (BABYLON = {}));
  22989. //# sourceMappingURL=babylon.camera.js.map
  22990. var BABYLON;
  22991. (function (BABYLON) {
  22992. var RenderingManager = /** @class */ (function () {
  22993. function RenderingManager(scene) {
  22994. this._renderingGroups = new Array();
  22995. this._autoClearDepthStencil = {};
  22996. this._customOpaqueSortCompareFn = {};
  22997. this._customAlphaTestSortCompareFn = {};
  22998. this._customTransparentSortCompareFn = {};
  22999. this._renderinGroupInfo = null;
  23000. this._scene = scene;
  23001. for (var i = RenderingManager.MIN_RENDERINGGROUPS; i < RenderingManager.MAX_RENDERINGGROUPS; i++) {
  23002. this._autoClearDepthStencil[i] = { autoClear: true, depth: true, stencil: true };
  23003. }
  23004. }
  23005. RenderingManager.prototype._clearDepthStencilBuffer = function (depth, stencil) {
  23006. if (depth === void 0) { depth = true; }
  23007. if (stencil === void 0) { stencil = true; }
  23008. if (this._depthStencilBufferAlreadyCleaned) {
  23009. return;
  23010. }
  23011. this._scene.getEngine().clear(null, false, depth, stencil);
  23012. this._depthStencilBufferAlreadyCleaned = true;
  23013. };
  23014. RenderingManager.prototype.render = function (customRenderFunction, activeMeshes, renderParticles, renderSprites) {
  23015. // Check if there's at least on observer on the onRenderingGroupObservable and initialize things to fire it
  23016. var observable = this._scene.onRenderingGroupObservable.hasObservers() ? this._scene.onRenderingGroupObservable : null;
  23017. var info = null;
  23018. if (observable) {
  23019. if (!this._renderinGroupInfo) {
  23020. this._renderinGroupInfo = new BABYLON.RenderingGroupInfo();
  23021. }
  23022. info = this._renderinGroupInfo;
  23023. info.scene = this._scene;
  23024. info.camera = this._scene.activeCamera;
  23025. }
  23026. // Dispatch sprites
  23027. if (renderSprites) {
  23028. for (var index = 0; index < this._scene.spriteManagers.length; index++) {
  23029. var manager = this._scene.spriteManagers[index];
  23030. this.dispatchSprites(manager);
  23031. }
  23032. }
  23033. // Render
  23034. for (var index = RenderingManager.MIN_RENDERINGGROUPS; index < RenderingManager.MAX_RENDERINGGROUPS; index++) {
  23035. this._depthStencilBufferAlreadyCleaned = index === RenderingManager.MIN_RENDERINGGROUPS;
  23036. var renderingGroup = this._renderingGroups[index];
  23037. if (!renderingGroup && !observable)
  23038. continue;
  23039. var renderingGroupMask = 0;
  23040. // Fire PRECLEAR stage
  23041. if (observable && info) {
  23042. renderingGroupMask = Math.pow(2, index);
  23043. info.renderStage = BABYLON.RenderingGroupInfo.STAGE_PRECLEAR;
  23044. info.renderingGroupId = index;
  23045. observable.notifyObservers(info, renderingGroupMask);
  23046. }
  23047. // Clear depth/stencil if needed
  23048. if (RenderingManager.AUTOCLEAR) {
  23049. var autoClear = this._autoClearDepthStencil[index];
  23050. if (autoClear && autoClear.autoClear) {
  23051. this._clearDepthStencilBuffer(autoClear.depth, autoClear.stencil);
  23052. }
  23053. }
  23054. if (observable && info) {
  23055. // Fire PREOPAQUE stage
  23056. info.renderStage = BABYLON.RenderingGroupInfo.STAGE_PREOPAQUE;
  23057. observable.notifyObservers(info, renderingGroupMask);
  23058. // Fire PRETRANSPARENT stage
  23059. info.renderStage = BABYLON.RenderingGroupInfo.STAGE_PRETRANSPARENT;
  23060. observable.notifyObservers(info, renderingGroupMask);
  23061. }
  23062. if (renderingGroup)
  23063. renderingGroup.render(customRenderFunction, renderSprites, renderParticles, activeMeshes);
  23064. // Fire POSTTRANSPARENT stage
  23065. if (observable && info) {
  23066. info.renderStage = BABYLON.RenderingGroupInfo.STAGE_POSTTRANSPARENT;
  23067. observable.notifyObservers(info, renderingGroupMask);
  23068. }
  23069. }
  23070. };
  23071. RenderingManager.prototype.reset = function () {
  23072. for (var index = RenderingManager.MIN_RENDERINGGROUPS; index < RenderingManager.MAX_RENDERINGGROUPS; index++) {
  23073. var renderingGroup = this._renderingGroups[index];
  23074. if (renderingGroup) {
  23075. renderingGroup.prepare();
  23076. }
  23077. }
  23078. };
  23079. RenderingManager.prototype.dispose = function () {
  23080. this.freeRenderingGroups();
  23081. this._renderingGroups.length = 0;
  23082. };
  23083. /**
  23084. * Clear the info related to rendering groups preventing retention points during dispose.
  23085. */
  23086. RenderingManager.prototype.freeRenderingGroups = function () {
  23087. for (var index = RenderingManager.MIN_RENDERINGGROUPS; index < RenderingManager.MAX_RENDERINGGROUPS; index++) {
  23088. var renderingGroup = this._renderingGroups[index];
  23089. if (renderingGroup) {
  23090. renderingGroup.dispose();
  23091. }
  23092. }
  23093. };
  23094. RenderingManager.prototype._prepareRenderingGroup = function (renderingGroupId) {
  23095. if (this._renderingGroups[renderingGroupId] === undefined) {
  23096. this._renderingGroups[renderingGroupId] = new BABYLON.RenderingGroup(renderingGroupId, this._scene, this._customOpaqueSortCompareFn[renderingGroupId], this._customAlphaTestSortCompareFn[renderingGroupId], this._customTransparentSortCompareFn[renderingGroupId]);
  23097. }
  23098. };
  23099. RenderingManager.prototype.dispatchSprites = function (spriteManager) {
  23100. var renderingGroupId = spriteManager.renderingGroupId || 0;
  23101. this._prepareRenderingGroup(renderingGroupId);
  23102. this._renderingGroups[renderingGroupId].dispatchSprites(spriteManager);
  23103. };
  23104. RenderingManager.prototype.dispatchParticles = function (particleSystem) {
  23105. var renderingGroupId = particleSystem.renderingGroupId || 0;
  23106. this._prepareRenderingGroup(renderingGroupId);
  23107. this._renderingGroups[renderingGroupId].dispatchParticles(particleSystem);
  23108. };
  23109. /**
  23110. * @param subMesh The submesh to dispatch
  23111. * @param [mesh] Optional reference to the submeshes's mesh. Provide if you have an exiting reference to improve performance.
  23112. * @param [material] Optional reference to the submeshes's material. Provide if you have an exiting reference to improve performance.
  23113. */
  23114. RenderingManager.prototype.dispatch = function (subMesh, mesh, material) {
  23115. if (mesh === undefined) {
  23116. mesh = subMesh.getMesh();
  23117. }
  23118. var renderingGroupId = mesh.renderingGroupId || 0;
  23119. this._prepareRenderingGroup(renderingGroupId);
  23120. this._renderingGroups[renderingGroupId].dispatch(subMesh, mesh, material);
  23121. };
  23122. /**
  23123. * Overrides the default sort function applied in the renderging group to prepare the meshes.
  23124. * This allowed control for front to back rendering or reversly depending of the special needs.
  23125. *
  23126. * @param renderingGroupId The rendering group id corresponding to its index
  23127. * @param opaqueSortCompareFn The opaque queue comparison function use to sort.
  23128. * @param alphaTestSortCompareFn The alpha test queue comparison function use to sort.
  23129. * @param transparentSortCompareFn The transparent queue comparison function use to sort.
  23130. */
  23131. RenderingManager.prototype.setRenderingOrder = function (renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn) {
  23132. if (opaqueSortCompareFn === void 0) { opaqueSortCompareFn = null; }
  23133. if (alphaTestSortCompareFn === void 0) { alphaTestSortCompareFn = null; }
  23134. if (transparentSortCompareFn === void 0) { transparentSortCompareFn = null; }
  23135. this._customOpaqueSortCompareFn[renderingGroupId] = opaqueSortCompareFn;
  23136. this._customAlphaTestSortCompareFn[renderingGroupId] = alphaTestSortCompareFn;
  23137. this._customTransparentSortCompareFn[renderingGroupId] = transparentSortCompareFn;
  23138. if (this._renderingGroups[renderingGroupId]) {
  23139. var group = this._renderingGroups[renderingGroupId];
  23140. group.opaqueSortCompareFn = this._customOpaqueSortCompareFn[renderingGroupId];
  23141. group.alphaTestSortCompareFn = this._customAlphaTestSortCompareFn[renderingGroupId];
  23142. group.transparentSortCompareFn = this._customTransparentSortCompareFn[renderingGroupId];
  23143. }
  23144. };
  23145. /**
  23146. * Specifies whether or not the stencil and depth buffer are cleared between two rendering groups.
  23147. *
  23148. * @param renderingGroupId The rendering group id corresponding to its index
  23149. * @param autoClearDepthStencil Automatically clears depth and stencil between groups if true.
  23150. * @param depth Automatically clears depth between groups if true and autoClear is true.
  23151. * @param stencil Automatically clears stencil between groups if true and autoClear is true.
  23152. */
  23153. RenderingManager.prototype.setRenderingAutoClearDepthStencil = function (renderingGroupId, autoClearDepthStencil, depth, stencil) {
  23154. if (depth === void 0) { depth = true; }
  23155. if (stencil === void 0) { stencil = true; }
  23156. this._autoClearDepthStencil[renderingGroupId] = {
  23157. autoClear: autoClearDepthStencil,
  23158. depth: depth,
  23159. stencil: stencil
  23160. };
  23161. };
  23162. /**
  23163. * The max id used for rendering groups (not included)
  23164. */
  23165. RenderingManager.MAX_RENDERINGGROUPS = 4;
  23166. /**
  23167. * The min id used for rendering groups (included)
  23168. */
  23169. RenderingManager.MIN_RENDERINGGROUPS = 0;
  23170. /**
  23171. * Used to globally prevent autoclearing scenes.
  23172. */
  23173. RenderingManager.AUTOCLEAR = true;
  23174. return RenderingManager;
  23175. }());
  23176. BABYLON.RenderingManager = RenderingManager;
  23177. })(BABYLON || (BABYLON = {}));
  23178. //# sourceMappingURL=babylon.renderingManager.js.map
  23179. var BABYLON;
  23180. (function (BABYLON) {
  23181. var RenderingGroup = /** @class */ (function () {
  23182. /**
  23183. * Creates a new rendering group.
  23184. * @param index The rendering group index
  23185. * @param opaqueSortCompareFn The opaque sort comparison function. If null no order is applied
  23186. * @param alphaTestSortCompareFn The alpha test sort comparison function. If null no order is applied
  23187. * @param transparentSortCompareFn The transparent sort comparison function. If null back to front + alpha index sort is applied
  23188. */
  23189. function RenderingGroup(index, scene, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn) {
  23190. if (opaqueSortCompareFn === void 0) { opaqueSortCompareFn = null; }
  23191. if (alphaTestSortCompareFn === void 0) { alphaTestSortCompareFn = null; }
  23192. if (transparentSortCompareFn === void 0) { transparentSortCompareFn = null; }
  23193. this.index = index;
  23194. this._opaqueSubMeshes = new BABYLON.SmartArray(256);
  23195. this._transparentSubMeshes = new BABYLON.SmartArray(256);
  23196. this._alphaTestSubMeshes = new BABYLON.SmartArray(256);
  23197. this._depthOnlySubMeshes = new BABYLON.SmartArray(256);
  23198. this._particleSystems = new BABYLON.SmartArray(256);
  23199. this._spriteManagers = new BABYLON.SmartArray(256);
  23200. this._edgesRenderers = new BABYLON.SmartArray(16);
  23201. this._scene = scene;
  23202. this.opaqueSortCompareFn = opaqueSortCompareFn;
  23203. this.alphaTestSortCompareFn = alphaTestSortCompareFn;
  23204. this.transparentSortCompareFn = transparentSortCompareFn;
  23205. }
  23206. Object.defineProperty(RenderingGroup.prototype, "opaqueSortCompareFn", {
  23207. /**
  23208. * Set the opaque sort comparison function.
  23209. * If null the sub meshes will be render in the order they were created
  23210. */
  23211. set: function (value) {
  23212. this._opaqueSortCompareFn = value;
  23213. if (value) {
  23214. this._renderOpaque = this.renderOpaqueSorted;
  23215. }
  23216. else {
  23217. this._renderOpaque = RenderingGroup.renderUnsorted;
  23218. }
  23219. },
  23220. enumerable: true,
  23221. configurable: true
  23222. });
  23223. Object.defineProperty(RenderingGroup.prototype, "alphaTestSortCompareFn", {
  23224. /**
  23225. * Set the alpha test sort comparison function.
  23226. * If null the sub meshes will be render in the order they were created
  23227. */
  23228. set: function (value) {
  23229. this._alphaTestSortCompareFn = value;
  23230. if (value) {
  23231. this._renderAlphaTest = this.renderAlphaTestSorted;
  23232. }
  23233. else {
  23234. this._renderAlphaTest = RenderingGroup.renderUnsorted;
  23235. }
  23236. },
  23237. enumerable: true,
  23238. configurable: true
  23239. });
  23240. Object.defineProperty(RenderingGroup.prototype, "transparentSortCompareFn", {
  23241. /**
  23242. * Set the transparent sort comparison function.
  23243. * If null the sub meshes will be render in the order they were created
  23244. */
  23245. set: function (value) {
  23246. if (value) {
  23247. this._transparentSortCompareFn = value;
  23248. }
  23249. else {
  23250. this._transparentSortCompareFn = RenderingGroup.defaultTransparentSortCompare;
  23251. }
  23252. this._renderTransparent = this.renderTransparentSorted;
  23253. },
  23254. enumerable: true,
  23255. configurable: true
  23256. });
  23257. /**
  23258. * Render all the sub meshes contained in the group.
  23259. * @param customRenderFunction Used to override the default render behaviour of the group.
  23260. * @returns true if rendered some submeshes.
  23261. */
  23262. RenderingGroup.prototype.render = function (customRenderFunction, renderSprites, renderParticles, activeMeshes) {
  23263. if (customRenderFunction) {
  23264. customRenderFunction(this._opaqueSubMeshes, this._alphaTestSubMeshes, this._transparentSubMeshes, this._depthOnlySubMeshes);
  23265. return;
  23266. }
  23267. var engine = this._scene.getEngine();
  23268. // Depth only
  23269. if (this._depthOnlySubMeshes.length !== 0) {
  23270. engine.setColorWrite(false);
  23271. this._renderAlphaTest(this._depthOnlySubMeshes);
  23272. engine.setColorWrite(true);
  23273. }
  23274. // Opaque
  23275. if (this._opaqueSubMeshes.length !== 0) {
  23276. this._renderOpaque(this._opaqueSubMeshes);
  23277. }
  23278. // Alpha test
  23279. if (this._alphaTestSubMeshes.length !== 0) {
  23280. this._renderAlphaTest(this._alphaTestSubMeshes);
  23281. }
  23282. var stencilState = engine.getStencilBuffer();
  23283. engine.setStencilBuffer(false);
  23284. // Sprites
  23285. if (renderSprites) {
  23286. this._renderSprites();
  23287. }
  23288. // Particles
  23289. if (renderParticles) {
  23290. this._renderParticles(activeMeshes);
  23291. }
  23292. if (this.onBeforeTransparentRendering) {
  23293. this.onBeforeTransparentRendering();
  23294. }
  23295. // Transparent
  23296. if (this._transparentSubMeshes.length !== 0) {
  23297. this._renderTransparent(this._transparentSubMeshes);
  23298. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  23299. }
  23300. // Set back stencil to false in case it changes before the edge renderer.
  23301. engine.setStencilBuffer(false);
  23302. // Edges
  23303. for (var edgesRendererIndex = 0; edgesRendererIndex < this._edgesRenderers.length; edgesRendererIndex++) {
  23304. this._edgesRenderers.data[edgesRendererIndex].render();
  23305. }
  23306. // Restore Stencil state.
  23307. engine.setStencilBuffer(stencilState);
  23308. };
  23309. /**
  23310. * Renders the opaque submeshes in the order from the opaqueSortCompareFn.
  23311. * @param subMeshes The submeshes to render
  23312. */
  23313. RenderingGroup.prototype.renderOpaqueSorted = function (subMeshes) {
  23314. return RenderingGroup.renderSorted(subMeshes, this._opaqueSortCompareFn, this._scene.activeCamera, false);
  23315. };
  23316. /**
  23317. * Renders the opaque submeshes in the order from the alphatestSortCompareFn.
  23318. * @param subMeshes The submeshes to render
  23319. */
  23320. RenderingGroup.prototype.renderAlphaTestSorted = function (subMeshes) {
  23321. return RenderingGroup.renderSorted(subMeshes, this._alphaTestSortCompareFn, this._scene.activeCamera, false);
  23322. };
  23323. /**
  23324. * Renders the opaque submeshes in the order from the transparentSortCompareFn.
  23325. * @param subMeshes The submeshes to render
  23326. */
  23327. RenderingGroup.prototype.renderTransparentSorted = function (subMeshes) {
  23328. return RenderingGroup.renderSorted(subMeshes, this._transparentSortCompareFn, this._scene.activeCamera, true);
  23329. };
  23330. /**
  23331. * Renders the submeshes in a specified order.
  23332. * @param subMeshes The submeshes to sort before render
  23333. * @param sortCompareFn The comparison function use to sort
  23334. * @param cameraPosition The camera position use to preprocess the submeshes to help sorting
  23335. * @param transparent Specifies to activate blending if true
  23336. */
  23337. RenderingGroup.renderSorted = function (subMeshes, sortCompareFn, camera, transparent) {
  23338. var subIndex = 0;
  23339. var subMesh;
  23340. var cameraPosition = camera ? camera.globalPosition : BABYLON.Vector3.Zero();
  23341. for (; subIndex < subMeshes.length; subIndex++) {
  23342. subMesh = subMeshes.data[subIndex];
  23343. subMesh._alphaIndex = subMesh.getMesh().alphaIndex;
  23344. subMesh._distanceToCamera = subMesh.getBoundingInfo().boundingSphere.centerWorld.subtract(cameraPosition).length();
  23345. }
  23346. var sortedArray = subMeshes.data.slice(0, subMeshes.length);
  23347. if (sortCompareFn) {
  23348. sortedArray.sort(sortCompareFn);
  23349. }
  23350. for (subIndex = 0; subIndex < sortedArray.length; subIndex++) {
  23351. subMesh = sortedArray[subIndex];
  23352. if (transparent) {
  23353. var material = subMesh.getMaterial();
  23354. if (material && material.needDepthPrePass) {
  23355. var engine = material.getScene().getEngine();
  23356. engine.setColorWrite(false);
  23357. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  23358. subMesh.render(false);
  23359. engine.setColorWrite(true);
  23360. }
  23361. }
  23362. subMesh.render(transparent);
  23363. }
  23364. };
  23365. /**
  23366. * Renders the submeshes in the order they were dispatched (no sort applied).
  23367. * @param subMeshes The submeshes to render
  23368. */
  23369. RenderingGroup.renderUnsorted = function (subMeshes) {
  23370. for (var subIndex = 0; subIndex < subMeshes.length; subIndex++) {
  23371. var submesh = subMeshes.data[subIndex];
  23372. submesh.render(false);
  23373. }
  23374. };
  23375. /**
  23376. * Build in function which can be applied to ensure meshes of a special queue (opaque, alpha test, transparent)
  23377. * are rendered back to front if in the same alpha index.
  23378. *
  23379. * @param a The first submesh
  23380. * @param b The second submesh
  23381. * @returns The result of the comparison
  23382. */
  23383. RenderingGroup.defaultTransparentSortCompare = function (a, b) {
  23384. // Alpha index first
  23385. if (a._alphaIndex > b._alphaIndex) {
  23386. return 1;
  23387. }
  23388. if (a._alphaIndex < b._alphaIndex) {
  23389. return -1;
  23390. }
  23391. // Then distance to camera
  23392. return RenderingGroup.backToFrontSortCompare(a, b);
  23393. };
  23394. /**
  23395. * Build in function which can be applied to ensure meshes of a special queue (opaque, alpha test, transparent)
  23396. * are rendered back to front.
  23397. *
  23398. * @param a The first submesh
  23399. * @param b The second submesh
  23400. * @returns The result of the comparison
  23401. */
  23402. RenderingGroup.backToFrontSortCompare = function (a, b) {
  23403. // Then distance to camera
  23404. if (a._distanceToCamera < b._distanceToCamera) {
  23405. return 1;
  23406. }
  23407. if (a._distanceToCamera > b._distanceToCamera) {
  23408. return -1;
  23409. }
  23410. return 0;
  23411. };
  23412. /**
  23413. * Build in function which can be applied to ensure meshes of a special queue (opaque, alpha test, transparent)
  23414. * are rendered front to back (prevent overdraw).
  23415. *
  23416. * @param a The first submesh
  23417. * @param b The second submesh
  23418. * @returns The result of the comparison
  23419. */
  23420. RenderingGroup.frontToBackSortCompare = function (a, b) {
  23421. // Then distance to camera
  23422. if (a._distanceToCamera < b._distanceToCamera) {
  23423. return -1;
  23424. }
  23425. if (a._distanceToCamera > b._distanceToCamera) {
  23426. return 1;
  23427. }
  23428. return 0;
  23429. };
  23430. /**
  23431. * Resets the different lists of submeshes to prepare a new frame.
  23432. */
  23433. RenderingGroup.prototype.prepare = function () {
  23434. this._opaqueSubMeshes.reset();
  23435. this._transparentSubMeshes.reset();
  23436. this._alphaTestSubMeshes.reset();
  23437. this._depthOnlySubMeshes.reset();
  23438. this._particleSystems.reset();
  23439. this._spriteManagers.reset();
  23440. this._edgesRenderers.reset();
  23441. };
  23442. RenderingGroup.prototype.dispose = function () {
  23443. this._opaqueSubMeshes.dispose();
  23444. this._transparentSubMeshes.dispose();
  23445. this._alphaTestSubMeshes.dispose();
  23446. this._depthOnlySubMeshes.dispose();
  23447. this._particleSystems.dispose();
  23448. this._spriteManagers.dispose();
  23449. this._edgesRenderers.dispose();
  23450. };
  23451. /**
  23452. * Inserts the submesh in its correct queue depending on its material.
  23453. * @param subMesh The submesh to dispatch
  23454. * @param [mesh] Optional reference to the submeshes's mesh. Provide if you have an exiting reference to improve performance.
  23455. * @param [material] Optional reference to the submeshes's material. Provide if you have an exiting reference to improve performance.
  23456. */
  23457. RenderingGroup.prototype.dispatch = function (subMesh, mesh, material) {
  23458. // Get mesh and materials if not provided
  23459. if (mesh === undefined) {
  23460. mesh = subMesh.getMesh();
  23461. }
  23462. if (material === undefined) {
  23463. material = subMesh.getMaterial();
  23464. }
  23465. if (material === null || material === undefined) {
  23466. return;
  23467. }
  23468. if (material.needAlphaBlendingForMesh(mesh)) { // Transparent
  23469. this._transparentSubMeshes.push(subMesh);
  23470. }
  23471. else if (material.needAlphaTesting()) { // Alpha test
  23472. if (material.needDepthPrePass) {
  23473. this._depthOnlySubMeshes.push(subMesh);
  23474. }
  23475. this._alphaTestSubMeshes.push(subMesh);
  23476. }
  23477. else {
  23478. if (material.needDepthPrePass) {
  23479. this._depthOnlySubMeshes.push(subMesh);
  23480. }
  23481. this._opaqueSubMeshes.push(subMesh); // Opaque
  23482. }
  23483. if (mesh._edgesRenderer !== null && mesh._edgesRenderer !== undefined) {
  23484. this._edgesRenderers.push(mesh._edgesRenderer);
  23485. }
  23486. };
  23487. RenderingGroup.prototype.dispatchSprites = function (spriteManager) {
  23488. this._spriteManagers.push(spriteManager);
  23489. };
  23490. RenderingGroup.prototype.dispatchParticles = function (particleSystem) {
  23491. this._particleSystems.push(particleSystem);
  23492. };
  23493. RenderingGroup.prototype._renderParticles = function (activeMeshes) {
  23494. if (this._particleSystems.length === 0) {
  23495. return;
  23496. }
  23497. // Particles
  23498. var activeCamera = this._scene.activeCamera;
  23499. this._scene.onBeforeParticlesRenderingObservable.notifyObservers(this._scene);
  23500. for (var particleIndex = 0; particleIndex < this._particleSystems.length; particleIndex++) {
  23501. var particleSystem = this._particleSystems.data[particleIndex];
  23502. if ((activeCamera && activeCamera.layerMask & particleSystem.layerMask) === 0) {
  23503. continue;
  23504. }
  23505. var emitter = particleSystem.emitter;
  23506. if (!emitter.position || !activeMeshes || activeMeshes.indexOf(emitter) !== -1) {
  23507. this._scene._activeParticles.addCount(particleSystem.render(), false);
  23508. }
  23509. }
  23510. this._scene.onAfterParticlesRenderingObservable.notifyObservers(this._scene);
  23511. };
  23512. RenderingGroup.prototype._renderSprites = function () {
  23513. if (!this._scene.spritesEnabled || this._spriteManagers.length === 0) {
  23514. return;
  23515. }
  23516. // Sprites
  23517. var activeCamera = this._scene.activeCamera;
  23518. this._scene.onBeforeSpritesRenderingObservable.notifyObservers(this._scene);
  23519. for (var id = 0; id < this._spriteManagers.length; id++) {
  23520. var spriteManager = this._spriteManagers.data[id];
  23521. if (((activeCamera && activeCamera.layerMask & spriteManager.layerMask) !== 0)) {
  23522. spriteManager.render();
  23523. }
  23524. }
  23525. this._scene.onAfterSpritesRenderingObservable.notifyObservers(this._scene);
  23526. };
  23527. return RenderingGroup;
  23528. }());
  23529. BABYLON.RenderingGroup = RenderingGroup;
  23530. })(BABYLON || (BABYLON = {}));
  23531. //# sourceMappingURL=babylon.renderingGroup.js.map
  23532. var BABYLON;
  23533. (function (BABYLON) {
  23534. /** @hidden */
  23535. var ClickInfo = /** @class */ (function () {
  23536. function ClickInfo() {
  23537. this._singleClick = false;
  23538. this._doubleClick = false;
  23539. this._hasSwiped = false;
  23540. this._ignore = false;
  23541. }
  23542. Object.defineProperty(ClickInfo.prototype, "singleClick", {
  23543. get: function () {
  23544. return this._singleClick;
  23545. },
  23546. set: function (b) {
  23547. this._singleClick = b;
  23548. },
  23549. enumerable: true,
  23550. configurable: true
  23551. });
  23552. Object.defineProperty(ClickInfo.prototype, "doubleClick", {
  23553. get: function () {
  23554. return this._doubleClick;
  23555. },
  23556. set: function (b) {
  23557. this._doubleClick = b;
  23558. },
  23559. enumerable: true,
  23560. configurable: true
  23561. });
  23562. Object.defineProperty(ClickInfo.prototype, "hasSwiped", {
  23563. get: function () {
  23564. return this._hasSwiped;
  23565. },
  23566. set: function (b) {
  23567. this._hasSwiped = b;
  23568. },
  23569. enumerable: true,
  23570. configurable: true
  23571. });
  23572. Object.defineProperty(ClickInfo.prototype, "ignore", {
  23573. get: function () {
  23574. return this._ignore;
  23575. },
  23576. set: function (b) {
  23577. this._ignore = b;
  23578. },
  23579. enumerable: true,
  23580. configurable: true
  23581. });
  23582. return ClickInfo;
  23583. }());
  23584. /**
  23585. * This class is used by the onRenderingGroupObservable
  23586. */
  23587. var RenderingGroupInfo = /** @class */ (function () {
  23588. function RenderingGroupInfo() {
  23589. }
  23590. /**
  23591. * Stage corresponding to the very first hook in the renderingGroup phase: before the render buffer may be cleared
  23592. * This stage will be fired no matter what
  23593. */
  23594. RenderingGroupInfo.STAGE_PRECLEAR = 1;
  23595. /**
  23596. * Called before opaque object are rendered.
  23597. * This stage will be fired only if there's 3D Opaque content to render
  23598. */
  23599. RenderingGroupInfo.STAGE_PREOPAQUE = 2;
  23600. /**
  23601. * Called after the opaque objects are rendered and before the transparent ones
  23602. * This stage will be fired only if there's 3D transparent content to render
  23603. */
  23604. RenderingGroupInfo.STAGE_PRETRANSPARENT = 3;
  23605. /**
  23606. * Called after the transparent object are rendered, last hook of the renderingGroup phase
  23607. * This stage will be fired no matter what
  23608. */
  23609. RenderingGroupInfo.STAGE_POSTTRANSPARENT = 4;
  23610. return RenderingGroupInfo;
  23611. }());
  23612. BABYLON.RenderingGroupInfo = RenderingGroupInfo;
  23613. /**
  23614. * Represents a scene to be rendered by the engine.
  23615. * @see http://doc.babylonjs.com/features/scene
  23616. */
  23617. var Scene = /** @class */ (function () {
  23618. /**
  23619. * Creates a new Scene
  23620. * @param engine defines the engine to use to render this scene
  23621. */
  23622. function Scene(engine) {
  23623. // Members
  23624. /**
  23625. * Gets or sets a boolean that indicates if the scene must clear the render buffer before rendering a frame
  23626. */
  23627. this.autoClear = true;
  23628. /**
  23629. * Gets or sets a boolean that indicates if the scene must clear the depth and stencil buffers before rendering a frame
  23630. */
  23631. this.autoClearDepthAndStencil = true;
  23632. /**
  23633. * Defines the color used to clear the render buffer (Default is (0.2, 0.2, 0.3, 1.0))
  23634. */
  23635. this.clearColor = new BABYLON.Color4(0.2, 0.2, 0.3, 1.0);
  23636. /**
  23637. * Defines the color used to simulate the ambient color (Default is (0, 0, 0))
  23638. */
  23639. this.ambientColor = new BABYLON.Color3(0, 0, 0);
  23640. this._forceWireframe = false;
  23641. this._forcePointsCloud = false;
  23642. /**
  23643. * Gets or sets a boolean indicating if all bounding boxes must be rendered
  23644. */
  23645. this.forceShowBoundingBoxes = false;
  23646. /**
  23647. * Gets or sets a boolean indicating if animations are enabled
  23648. */
  23649. this.animationsEnabled = true;
  23650. this._animationPropertiesOverride = null;
  23651. /**
  23652. * Gets or sets a boolean indicating if a constant deltatime has to be used
  23653. * This is mostly useful for testing purposes when you do not want the animations to scale with the framerate
  23654. */
  23655. this.useConstantAnimationDeltaTime = false;
  23656. /**
  23657. * Gets or sets a boolean indicating if the scene must keep the meshUnderPointer property updated
  23658. * Please note that it requires to run a ray cast through the scene on every frame
  23659. */
  23660. this.constantlyUpdateMeshUnderPointer = false;
  23661. /**
  23662. * Defines the HTML cursor to use when hovering over interactive elements
  23663. */
  23664. this.hoverCursor = "pointer";
  23665. /**
  23666. * Defines the HTML default cursor to use (empty by default)
  23667. */
  23668. this.defaultCursor = "";
  23669. /**
  23670. * This is used to call preventDefault() on pointer down
  23671. * in order to block unwanted artifacts like system double clicks
  23672. */
  23673. this.preventDefaultOnPointerDown = true;
  23674. // Metadata
  23675. /**
  23676. * Gets or sets user defined metadata
  23677. */
  23678. this.metadata = null;
  23679. /**
  23680. * Use this array to add regular expressions used to disable offline support for specific urls
  23681. */
  23682. this.disableOfflineSupportExceptionRules = new Array();
  23683. /**
  23684. * An event triggered when the scene is disposed.
  23685. */
  23686. this.onDisposeObservable = new BABYLON.Observable();
  23687. this._onDisposeObserver = null;
  23688. /**
  23689. * An event triggered before rendering the scene (right after animations and physics)
  23690. */
  23691. this.onBeforeRenderObservable = new BABYLON.Observable();
  23692. this._onBeforeRenderObserver = null;
  23693. /**
  23694. * An event triggered after rendering the scene
  23695. */
  23696. this.onAfterRenderObservable = new BABYLON.Observable();
  23697. this._onAfterRenderObserver = null;
  23698. /**
  23699. * An event triggered before animating the scene
  23700. */
  23701. this.onBeforeAnimationsObservable = new BABYLON.Observable();
  23702. /**
  23703. * An event triggered after animations processing
  23704. */
  23705. this.onAfterAnimationsObservable = new BABYLON.Observable();
  23706. /**
  23707. * An event triggered before draw calls are ready to be sent
  23708. */
  23709. this.onBeforeDrawPhaseObservable = new BABYLON.Observable();
  23710. /**
  23711. * An event triggered after draw calls have been sent
  23712. */
  23713. this.onAfterDrawPhaseObservable = new BABYLON.Observable();
  23714. /**
  23715. * An event triggered when physic simulation is about to be run
  23716. */
  23717. this.onBeforePhysicsObservable = new BABYLON.Observable();
  23718. /**
  23719. * An event triggered when physic simulation has been done
  23720. */
  23721. this.onAfterPhysicsObservable = new BABYLON.Observable();
  23722. /**
  23723. * An event triggered when the scene is ready
  23724. */
  23725. this.onReadyObservable = new BABYLON.Observable();
  23726. /**
  23727. * An event triggered before rendering a camera
  23728. */
  23729. this.onBeforeCameraRenderObservable = new BABYLON.Observable();
  23730. this._onBeforeCameraRenderObserver = null;
  23731. /**
  23732. * An event triggered after rendering a camera
  23733. */
  23734. this.onAfterCameraRenderObservable = new BABYLON.Observable();
  23735. this._onAfterCameraRenderObserver = null;
  23736. /**
  23737. * An event triggered when active meshes evaluation is about to start
  23738. */
  23739. this.onBeforeActiveMeshesEvaluationObservable = new BABYLON.Observable();
  23740. /**
  23741. * An event triggered when active meshes evaluation is done
  23742. */
  23743. this.onAfterActiveMeshesEvaluationObservable = new BABYLON.Observable();
  23744. /**
  23745. * An event triggered when particles rendering is about to start
  23746. * Note: This event can be trigger more than once per frame (because particles can be rendered by render target textures as well)
  23747. */
  23748. this.onBeforeParticlesRenderingObservable = new BABYLON.Observable();
  23749. /**
  23750. * An event triggered when particles rendering is done
  23751. * Note: This event can be trigger more than once per frame (because particles can be rendered by render target textures as well)
  23752. */
  23753. this.onAfterParticlesRenderingObservable = new BABYLON.Observable();
  23754. /**
  23755. * An event triggered when sprites rendering is about to start
  23756. * Note: This event can be trigger more than once per frame (because sprites can be rendered by render target textures as well)
  23757. */
  23758. this.onBeforeSpritesRenderingObservable = new BABYLON.Observable();
  23759. /**
  23760. * An event triggered when sprites rendering is done
  23761. * Note: This event can be trigger more than once per frame (because sprites can be rendered by render target textures as well)
  23762. */
  23763. this.onAfterSpritesRenderingObservable = new BABYLON.Observable();
  23764. /**
  23765. * An event triggered when SceneLoader.Append or SceneLoader.Load or SceneLoader.ImportMesh were successfully executed
  23766. */
  23767. this.onDataLoadedObservable = new BABYLON.Observable();
  23768. /**
  23769. * An event triggered when a camera is created
  23770. */
  23771. this.onNewCameraAddedObservable = new BABYLON.Observable();
  23772. /**
  23773. * An event triggered when a camera is removed
  23774. */
  23775. this.onCameraRemovedObservable = new BABYLON.Observable();
  23776. /**
  23777. * An event triggered when a light is created
  23778. */
  23779. this.onNewLightAddedObservable = new BABYLON.Observable();
  23780. /**
  23781. * An event triggered when a light is removed
  23782. */
  23783. this.onLightRemovedObservable = new BABYLON.Observable();
  23784. /**
  23785. * An event triggered when a geometry is created
  23786. */
  23787. this.onNewGeometryAddedObservable = new BABYLON.Observable();
  23788. /**
  23789. * An event triggered when a geometry is removed
  23790. */
  23791. this.onGeometryRemovedObservable = new BABYLON.Observable();
  23792. /**
  23793. * An event triggered when a transform node is created
  23794. */
  23795. this.onNewTransformNodeAddedObservable = new BABYLON.Observable();
  23796. /**
  23797. * An event triggered when a transform node is removed
  23798. */
  23799. this.onTransformNodeRemovedObservable = new BABYLON.Observable();
  23800. /**
  23801. * An event triggered when a mesh is created
  23802. */
  23803. this.onNewMeshAddedObservable = new BABYLON.Observable();
  23804. /**
  23805. * An event triggered when a mesh is removed
  23806. */
  23807. this.onMeshRemovedObservable = new BABYLON.Observable();
  23808. /**
  23809. * An event triggered when render targets are about to be rendered
  23810. * Can happen multiple times per frame.
  23811. */
  23812. this.onBeforeRenderTargetsRenderObservable = new BABYLON.Observable();
  23813. /**
  23814. * An event triggered when render targets were rendered.
  23815. * Can happen multiple times per frame.
  23816. */
  23817. this.onAfterRenderTargetsRenderObservable = new BABYLON.Observable();
  23818. /**
  23819. * An event triggered before calculating deterministic simulation step
  23820. */
  23821. this.onBeforeStepObservable = new BABYLON.Observable();
  23822. /**
  23823. * An event triggered after calculating deterministic simulation step
  23824. */
  23825. this.onAfterStepObservable = new BABYLON.Observable();
  23826. /**
  23827. * This Observable will be triggered for each stage of each renderingGroup of each rendered camera.
  23828. * The RenderinGroupInfo class contains all the information about the context in which the observable is called
  23829. * 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)
  23830. */
  23831. this.onRenderingGroupObservable = new BABYLON.Observable();
  23832. // Animations
  23833. /**
  23834. * Gets a list of Animations associated with the scene
  23835. */
  23836. this.animations = [];
  23837. this._registeredForLateAnimationBindings = new BABYLON.SmartArrayNoDuplicate(256);
  23838. /**
  23839. * 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).
  23840. * You have the possibility to skip the process and the call to onPointerObservable by setting PointerInfoPre.skipOnPointerObservable to true
  23841. */
  23842. this.onPrePointerObservable = new BABYLON.Observable();
  23843. /**
  23844. * Observable event triggered each time an input event is received from the rendering canvas
  23845. */
  23846. this.onPointerObservable = new BABYLON.Observable();
  23847. this._meshPickProceed = false;
  23848. this._currentPickResult = null;
  23849. this._previousPickResult = null;
  23850. this._totalPointersPressed = 0;
  23851. this._doubleClickOccured = false;
  23852. /** Define this parameter if you are using multiple cameras and you want to specify which one should be used for pointer position */
  23853. this.cameraToUseForPointers = null;
  23854. this._startingPointerPosition = new BABYLON.Vector2(0, 0);
  23855. this._previousStartingPointerPosition = new BABYLON.Vector2(0, 0);
  23856. this._startingPointerTime = 0;
  23857. this._previousStartingPointerTime = 0;
  23858. // Deterministic lockstep
  23859. this._timeAccumulator = 0;
  23860. this._currentStepId = 0;
  23861. this._currentInternalStep = 0;
  23862. // Keyboard
  23863. /**
  23864. * This observable event is triggered when any keyboard event si raised and registered during Scene.attachControl()
  23865. * You have the possibility to skip the process and the call to onKeyboardObservable by setting KeyboardInfoPre.skipOnPointerObservable to true
  23866. */
  23867. this.onPreKeyboardObservable = new BABYLON.Observable();
  23868. /**
  23869. * Observable event triggered each time an keyboard event is received from the hosting window
  23870. */
  23871. this.onKeyboardObservable = new BABYLON.Observable();
  23872. // Coordinates system
  23873. this._useRightHandedSystem = false;
  23874. // Fog
  23875. this._fogEnabled = true;
  23876. this._fogMode = Scene.FOGMODE_NONE;
  23877. /**
  23878. * Gets or sets the fog color to use
  23879. * @see http://doc.babylonjs.com/babylon101/environment#fog
  23880. */
  23881. this.fogColor = new BABYLON.Color3(0.2, 0.2, 0.3);
  23882. /**
  23883. * Gets or sets the fog density to use
  23884. * @see http://doc.babylonjs.com/babylon101/environment#fog
  23885. */
  23886. this.fogDensity = 0.1;
  23887. /**
  23888. * Gets or sets the fog start distance to use
  23889. * @see http://doc.babylonjs.com/babylon101/environment#fog
  23890. */
  23891. this.fogStart = 0;
  23892. /**
  23893. * Gets or sets the fog end distance to use
  23894. * @see http://doc.babylonjs.com/babylon101/environment#fog
  23895. */
  23896. this.fogEnd = 1000.0;
  23897. // Lights
  23898. this._shadowsEnabled = true;
  23899. this._lightsEnabled = true;
  23900. /**
  23901. * All of the lights added to this scene
  23902. * @see http://doc.babylonjs.com/babylon101/lights
  23903. */
  23904. this.lights = new Array();
  23905. // Cameras
  23906. /** All of the cameras added to this scene.
  23907. * @see http://doc.babylonjs.com/babylon101/cameras
  23908. */
  23909. this.cameras = new Array();
  23910. /** All of the active cameras added to this scene. */
  23911. this.activeCameras = new Array();
  23912. // Meshes
  23913. /**
  23914. * All of the tranform nodes added to this scene
  23915. * @see http://doc.babylonjs.com/how_to/transformnode
  23916. */
  23917. this.transformNodes = new Array();
  23918. /**
  23919. * All of the (abstract) meshes added to this scene
  23920. */
  23921. this.meshes = new Array();
  23922. /**
  23923. * All of the animation groups added to this scene
  23924. * @see http://doc.babylonjs.com/how_to/group
  23925. */
  23926. this.animationGroups = new Array();
  23927. // Geometries
  23928. this._geometries = new Array();
  23929. /**
  23930. * All of the materials added to this scene
  23931. * @see http://doc.babylonjs.com/babylon101/materials
  23932. */
  23933. this.materials = new Array();
  23934. /**
  23935. * All of the multi-materials added to this scene
  23936. * @see http://doc.babylonjs.com/how_to/multi_materials
  23937. */
  23938. this.multiMaterials = new Array();
  23939. // Textures
  23940. this._texturesEnabled = true;
  23941. /**
  23942. * All of the textures added to this scene
  23943. */
  23944. this.textures = new Array();
  23945. // Particles
  23946. /**
  23947. * Gets or sets a boolean indicating if particles are enabled on this scene
  23948. */
  23949. this.particlesEnabled = true;
  23950. /**
  23951. * All of the particle systems added to this scene
  23952. * @see http://doc.babylonjs.com/babylon101/particles
  23953. */
  23954. this.particleSystems = new Array();
  23955. // Sprites
  23956. /**
  23957. * Gets or sets a boolean indicating if sprites are enabled on this scene
  23958. */
  23959. this.spritesEnabled = true;
  23960. /**
  23961. * All of the sprite managers added to this scene
  23962. * @see http://doc.babylonjs.com/babylon101/sprites
  23963. */
  23964. this.spriteManagers = new Array();
  23965. /**
  23966. * The list of layers (background and foreground) of the scene
  23967. */
  23968. this.layers = new Array();
  23969. /**
  23970. * The list of effect layers (highlights/glow) added to the scene
  23971. * @see http://doc.babylonjs.com/how_to/highlight_layer
  23972. * @see http://doc.babylonjs.com/how_to/glow_layer
  23973. */
  23974. this.effectLayers = new Array();
  23975. // Skeletons
  23976. this._skeletonsEnabled = true;
  23977. /**
  23978. * The list of skeletons added to the scene
  23979. * @see http://doc.babylonjs.com/how_to/how_to_use_bones_and_skeletons
  23980. */
  23981. this.skeletons = new Array();
  23982. // Morph targets
  23983. /**
  23984. * The list of morph target managers added to the scene
  23985. * @see http://doc.babylonjs.com/how_to/how_to_dynamically_morph_a_mesh
  23986. */
  23987. this.morphTargetManagers = new Array();
  23988. // Lens flares
  23989. /**
  23990. * Gets or sets a boolean indicating if lens flares are enabled on this scene
  23991. */
  23992. this.lensFlaresEnabled = true;
  23993. /**
  23994. * The list of lens flare system added to the scene
  23995. * @see http://doc.babylonjs.com/how_to/how_to_use_lens_flares
  23996. */
  23997. this.lensFlareSystems = new Array();
  23998. // Collisions
  23999. /**
  24000. * Gets or sets a boolean indicating if collisions are enabled on this scene
  24001. * @see http://doc.babylonjs.com/babylon101/cameras,_mesh_collisions_and_gravity
  24002. */
  24003. this.collisionsEnabled = true;
  24004. /**
  24005. * Defines the gravity applied to this scene (used only for collisions)
  24006. * @see http://doc.babylonjs.com/babylon101/cameras,_mesh_collisions_and_gravity
  24007. */
  24008. this.gravity = new BABYLON.Vector3(0, -9.807, 0);
  24009. // Postprocesses
  24010. /**
  24011. * Gets or sets a boolean indicating if postprocesses are enabled on this scene
  24012. */
  24013. this.postProcessesEnabled = true;
  24014. /**
  24015. * The list of postprocesses added to the scene
  24016. */
  24017. this.postProcesses = new Array();
  24018. // Customs render targets
  24019. /**
  24020. * Gets or sets a boolean indicating if render targets are enabled on this scene
  24021. */
  24022. this.renderTargetsEnabled = true;
  24023. /**
  24024. * Gets or sets a boolean indicating if next render targets must be dumped as image for debugging purposes
  24025. * We recommend not using it and instead rely on Spector.js: http://spector.babylonjs.com
  24026. */
  24027. this.dumpNextRenderTargets = false;
  24028. /**
  24029. * The list of user defined render targets added to the scene
  24030. */
  24031. this.customRenderTargets = new Array();
  24032. /**
  24033. * Gets the list of meshes imported to the scene through SceneLoader
  24034. */
  24035. this.importedMeshesFiles = new Array();
  24036. // Probes
  24037. /**
  24038. * Gets or sets a boolean indicating if probes are enabled on this scene
  24039. */
  24040. this.probesEnabled = true;
  24041. /**
  24042. * The list of reflection probes added to the scene
  24043. * @see http://doc.babylonjs.com/how_to/how_to_use_reflection_probes
  24044. */
  24045. this.reflectionProbes = new Array();
  24046. /** @hidden */
  24047. this._actionManagers = new Array();
  24048. this._meshesForIntersections = new BABYLON.SmartArrayNoDuplicate(256);
  24049. // Procedural textures
  24050. /**
  24051. * Gets or sets a boolean indicating if procedural textures are enabled on this scene
  24052. */
  24053. this.proceduralTexturesEnabled = true;
  24054. /**
  24055. * The list of procedural textures added to the scene
  24056. * @see http://doc.babylonjs.com/how_to/how_to_use_procedural_textures
  24057. */
  24058. this.proceduralTextures = new Array();
  24059. /**
  24060. * The list of sound tracks added to the scene
  24061. * @see http://doc.babylonjs.com/how_to/playing_sounds_and_music
  24062. */
  24063. this.soundTracks = new Array();
  24064. this._audioEnabled = true;
  24065. this._headphone = false;
  24066. // Performance counters
  24067. this._totalVertices = new BABYLON.PerfCounter();
  24068. /** @hidden */
  24069. this._activeIndices = new BABYLON.PerfCounter();
  24070. /** @hidden */
  24071. this._activeParticles = new BABYLON.PerfCounter();
  24072. /** @hidden */
  24073. this._activeBones = new BABYLON.PerfCounter();
  24074. this._animationTime = 0;
  24075. /**
  24076. * Gets or sets a general scale for animation speed
  24077. * @see https://www.babylonjs-playground.com/#IBU2W7#3
  24078. */
  24079. this.animationTimeScale = 1;
  24080. this._renderId = 0;
  24081. this._executeWhenReadyTimeoutId = -1;
  24082. this._intermediateRendering = false;
  24083. this._viewUpdateFlag = -1;
  24084. this._projectionUpdateFlag = -1;
  24085. this._alternateViewUpdateFlag = -1;
  24086. this._alternateProjectionUpdateFlag = -1;
  24087. /** @hidden */
  24088. this._toBeDisposed = new BABYLON.SmartArray(256);
  24089. this._activeRequests = new Array();
  24090. this._pendingData = new Array();
  24091. this._isDisposed = false;
  24092. /**
  24093. * Gets or sets a boolean indicating that all submeshes of active meshes must be rendered
  24094. * Use this boolean to avoid computing frustum clipping on submeshes (This could help when you are CPU bound)
  24095. */
  24096. this.dispatchAllSubMeshesOfActiveMeshes = false;
  24097. this._activeMeshes = new BABYLON.SmartArray(256);
  24098. this._processedMaterials = new BABYLON.SmartArray(256);
  24099. this._renderTargets = new BABYLON.SmartArrayNoDuplicate(256);
  24100. /** @hidden */
  24101. this._activeParticleSystems = new BABYLON.SmartArray(256);
  24102. this._activeSkeletons = new BABYLON.SmartArrayNoDuplicate(32);
  24103. this._softwareSkinnedMeshes = new BABYLON.SmartArrayNoDuplicate(32);
  24104. /** @hidden */
  24105. this._activeAnimatables = new Array();
  24106. this._transformMatrix = BABYLON.Matrix.Zero();
  24107. this._useAlternateCameraConfiguration = false;
  24108. this._alternateRendering = false;
  24109. /**
  24110. * Gets or sets a boolean indicating if lights must be sorted by priority (off by default)
  24111. * This is useful if there are more lights that the maximum simulteanous authorized
  24112. */
  24113. this.requireLightSorting = false;
  24114. this._depthRenderer = {};
  24115. this._activeMeshesFrozen = false;
  24116. this._tempPickingRay = BABYLON.Ray ? BABYLON.Ray.Zero() : null;
  24117. this._engine = engine || BABYLON.Engine.LastCreatedEngine;
  24118. this._engine.scenes.push(this);
  24119. this._uid = null;
  24120. this._renderingManager = new BABYLON.RenderingManager(this);
  24121. this.postProcessManager = new BABYLON.PostProcessManager(this);
  24122. if (BABYLON.OutlineRenderer) {
  24123. this._outlineRenderer = new BABYLON.OutlineRenderer(this);
  24124. }
  24125. if (BABYLON.Tools.IsWindowObjectExist()) {
  24126. this.attachControl();
  24127. }
  24128. //simplification queue
  24129. if (BABYLON.SimplificationQueue) {
  24130. this.simplificationQueue = new BABYLON.SimplificationQueue();
  24131. }
  24132. //collision coordinator initialization. For now legacy per default.
  24133. this.workerCollisions = false; //(!!Worker && (!!BABYLON.CollisionWorker || BABYLON.WorkerIncluded));
  24134. // Uniform Buffer
  24135. this._createUbo();
  24136. // Default Image processing definition.
  24137. this._imageProcessingConfiguration = new BABYLON.ImageProcessingConfiguration();
  24138. }
  24139. Object.defineProperty(Scene, "FOGMODE_NONE", {
  24140. /** The fog is deactivated */
  24141. get: function () {
  24142. return Scene._FOGMODE_NONE;
  24143. },
  24144. enumerable: true,
  24145. configurable: true
  24146. });
  24147. Object.defineProperty(Scene, "FOGMODE_EXP", {
  24148. /** The fog density is following an exponential function */
  24149. get: function () {
  24150. return Scene._FOGMODE_EXP;
  24151. },
  24152. enumerable: true,
  24153. configurable: true
  24154. });
  24155. Object.defineProperty(Scene, "FOGMODE_EXP2", {
  24156. /** The fog density is following an exponential function faster than FOGMODE_EXP */
  24157. get: function () {
  24158. return Scene._FOGMODE_EXP2;
  24159. },
  24160. enumerable: true,
  24161. configurable: true
  24162. });
  24163. Object.defineProperty(Scene, "FOGMODE_LINEAR", {
  24164. /** The fog density is following a linear function. */
  24165. get: function () {
  24166. return Scene._FOGMODE_LINEAR;
  24167. },
  24168. enumerable: true,
  24169. configurable: true
  24170. });
  24171. Object.defineProperty(Scene.prototype, "environmentTexture", {
  24172. /**
  24173. * Texture used in all pbr material as the reflection texture.
  24174. * As in the majority of the scene they are the same (exception for multi room and so on),
  24175. * this is easier to reference from here than from all the materials.
  24176. */
  24177. get: function () {
  24178. return this._environmentTexture;
  24179. },
  24180. /**
  24181. * Texture used in all pbr material as the reflection texture.
  24182. * As in the majority of the scene they are the same (exception for multi room and so on),
  24183. * this is easier to set here than in all the materials.
  24184. */
  24185. set: function (value) {
  24186. if (this._environmentTexture === value) {
  24187. return;
  24188. }
  24189. this._environmentTexture = value;
  24190. this.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  24191. },
  24192. enumerable: true,
  24193. configurable: true
  24194. });
  24195. Object.defineProperty(Scene.prototype, "imageProcessingConfiguration", {
  24196. /**
  24197. * Default image processing configuration used either in the rendering
  24198. * Forward main pass or through the imageProcessingPostProcess if present.
  24199. * As in the majority of the scene they are the same (exception for multi camera),
  24200. * this is easier to reference from here than from all the materials and post process.
  24201. *
  24202. * No setter as we it is a shared configuration, you can set the values instead.
  24203. */
  24204. get: function () {
  24205. return this._imageProcessingConfiguration;
  24206. },
  24207. enumerable: true,
  24208. configurable: true
  24209. });
  24210. Object.defineProperty(Scene.prototype, "forceWireframe", {
  24211. get: function () {
  24212. return this._forceWireframe;
  24213. },
  24214. /**
  24215. * Gets or sets a boolean indicating if all rendering must be done in wireframe
  24216. */
  24217. set: function (value) {
  24218. if (this._forceWireframe === value) {
  24219. return;
  24220. }
  24221. this._forceWireframe = value;
  24222. this.markAllMaterialsAsDirty(BABYLON.Material.MiscDirtyFlag);
  24223. },
  24224. enumerable: true,
  24225. configurable: true
  24226. });
  24227. Object.defineProperty(Scene.prototype, "forcePointsCloud", {
  24228. get: function () {
  24229. return this._forcePointsCloud;
  24230. },
  24231. /**
  24232. * Gets or sets a boolean indicating if all rendering must be done in point cloud
  24233. */
  24234. set: function (value) {
  24235. if (this._forcePointsCloud === value) {
  24236. return;
  24237. }
  24238. this._forcePointsCloud = value;
  24239. this.markAllMaterialsAsDirty(BABYLON.Material.MiscDirtyFlag);
  24240. },
  24241. enumerable: true,
  24242. configurable: true
  24243. });
  24244. Object.defineProperty(Scene.prototype, "animationPropertiesOverride", {
  24245. /**
  24246. * Gets or sets the animation properties override
  24247. */
  24248. get: function () {
  24249. return this._animationPropertiesOverride;
  24250. },
  24251. set: function (value) {
  24252. this._animationPropertiesOverride = value;
  24253. },
  24254. enumerable: true,
  24255. configurable: true
  24256. });
  24257. Object.defineProperty(Scene.prototype, "onDispose", {
  24258. /** Sets a function to be executed when this scene is disposed. */
  24259. set: function (callback) {
  24260. if (this._onDisposeObserver) {
  24261. this.onDisposeObservable.remove(this._onDisposeObserver);
  24262. }
  24263. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  24264. },
  24265. enumerable: true,
  24266. configurable: true
  24267. });
  24268. Object.defineProperty(Scene.prototype, "beforeRender", {
  24269. /** Sets a function to be executed before rendering this scene */
  24270. set: function (callback) {
  24271. if (this._onBeforeRenderObserver) {
  24272. this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
  24273. }
  24274. if (callback) {
  24275. this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
  24276. }
  24277. },
  24278. enumerable: true,
  24279. configurable: true
  24280. });
  24281. Object.defineProperty(Scene.prototype, "afterRender", {
  24282. /** Sets a function to be executed after rendering this scene */
  24283. set: function (callback) {
  24284. if (this._onAfterRenderObserver) {
  24285. this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  24286. }
  24287. if (callback) {
  24288. this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
  24289. }
  24290. },
  24291. enumerable: true,
  24292. configurable: true
  24293. });
  24294. Object.defineProperty(Scene.prototype, "beforeCameraRender", {
  24295. /** Sets a function to be executed before rendering a camera*/
  24296. set: function (callback) {
  24297. if (this._onBeforeCameraRenderObserver) {
  24298. this.onBeforeCameraRenderObservable.remove(this._onBeforeCameraRenderObserver);
  24299. }
  24300. this._onBeforeCameraRenderObserver = this.onBeforeCameraRenderObservable.add(callback);
  24301. },
  24302. enumerable: true,
  24303. configurable: true
  24304. });
  24305. Object.defineProperty(Scene.prototype, "afterCameraRender", {
  24306. /** Sets a function to be executed after rendering a camera*/
  24307. set: function (callback) {
  24308. if (this._onAfterCameraRenderObserver) {
  24309. this.onAfterCameraRenderObservable.remove(this._onAfterCameraRenderObserver);
  24310. }
  24311. this._onAfterCameraRenderObserver = this.onAfterCameraRenderObservable.add(callback);
  24312. },
  24313. enumerable: true,
  24314. configurable: true
  24315. });
  24316. Object.defineProperty(Scene.prototype, "gamepadManager", {
  24317. /**
  24318. * Gets the gamepad manager associated with the scene
  24319. * @see http://doc.babylonjs.com/how_to/how_to_use_gamepads
  24320. */
  24321. get: function () {
  24322. if (!this._gamepadManager) {
  24323. this._gamepadManager = new BABYLON.GamepadManager(this);
  24324. }
  24325. return this._gamepadManager;
  24326. },
  24327. enumerable: true,
  24328. configurable: true
  24329. });
  24330. Object.defineProperty(Scene.prototype, "unTranslatedPointer", {
  24331. /**
  24332. * Gets the pointer coordinates without any translation (ie. straight out of the pointer event)
  24333. */
  24334. get: function () {
  24335. return new BABYLON.Vector2(this._unTranslatedPointerX, this._unTranslatedPointerY);
  24336. },
  24337. enumerable: true,
  24338. configurable: true
  24339. });
  24340. Object.defineProperty(Scene.prototype, "useRightHandedSystem", {
  24341. get: function () {
  24342. return this._useRightHandedSystem;
  24343. },
  24344. /**
  24345. * Gets or sets a boolean indicating if the scene must use right-handed coordinates system
  24346. */
  24347. set: function (value) {
  24348. if (this._useRightHandedSystem === value) {
  24349. return;
  24350. }
  24351. this._useRightHandedSystem = value;
  24352. this.markAllMaterialsAsDirty(BABYLON.Material.MiscDirtyFlag);
  24353. },
  24354. enumerable: true,
  24355. configurable: true
  24356. });
  24357. /**
  24358. * Sets the step Id used by deterministic lock step
  24359. * @see http://doc.babylonjs.com/babylon101/animations#deterministic-lockstep
  24360. * @param newStepId defines the step Id
  24361. */
  24362. Scene.prototype.setStepId = function (newStepId) {
  24363. this._currentStepId = newStepId;
  24364. };
  24365. ;
  24366. /**
  24367. * Gets the step Id used by deterministic lock step
  24368. * @see http://doc.babylonjs.com/babylon101/animations#deterministic-lockstep
  24369. * @returns the step Id
  24370. */
  24371. Scene.prototype.getStepId = function () {
  24372. return this._currentStepId;
  24373. };
  24374. ;
  24375. /**
  24376. * Gets the internal step used by deterministic lock step
  24377. * @see http://doc.babylonjs.com/babylon101/animations#deterministic-lockstep
  24378. * @returns the internal step
  24379. */
  24380. Scene.prototype.getInternalStep = function () {
  24381. return this._currentInternalStep;
  24382. };
  24383. ;
  24384. Object.defineProperty(Scene.prototype, "fogEnabled", {
  24385. get: function () {
  24386. return this._fogEnabled;
  24387. },
  24388. /**
  24389. * Gets or sets a boolean indicating if fog is enabled on this scene
  24390. * @see http://doc.babylonjs.com/babylon101/environment#fog
  24391. */
  24392. set: function (value) {
  24393. if (this._fogEnabled === value) {
  24394. return;
  24395. }
  24396. this._fogEnabled = value;
  24397. this.markAllMaterialsAsDirty(BABYLON.Material.MiscDirtyFlag);
  24398. },
  24399. enumerable: true,
  24400. configurable: true
  24401. });
  24402. Object.defineProperty(Scene.prototype, "fogMode", {
  24403. get: function () {
  24404. return this._fogMode;
  24405. },
  24406. /**
  24407. * Gets or sets the fog mode to use
  24408. * @see http://doc.babylonjs.com/babylon101/environment#fog
  24409. */
  24410. set: function (value) {
  24411. if (this._fogMode === value) {
  24412. return;
  24413. }
  24414. this._fogMode = value;
  24415. this.markAllMaterialsAsDirty(BABYLON.Material.MiscDirtyFlag);
  24416. },
  24417. enumerable: true,
  24418. configurable: true
  24419. });
  24420. Object.defineProperty(Scene.prototype, "shadowsEnabled", {
  24421. get: function () {
  24422. return this._shadowsEnabled;
  24423. },
  24424. /**
  24425. * Gets or sets a boolean indicating if shadows are enabled on this scene
  24426. */
  24427. set: function (value) {
  24428. if (this._shadowsEnabled === value) {
  24429. return;
  24430. }
  24431. this._shadowsEnabled = value;
  24432. this.markAllMaterialsAsDirty(BABYLON.Material.LightDirtyFlag);
  24433. },
  24434. enumerable: true,
  24435. configurable: true
  24436. });
  24437. Object.defineProperty(Scene.prototype, "lightsEnabled", {
  24438. get: function () {
  24439. return this._lightsEnabled;
  24440. },
  24441. /**
  24442. * Gets or sets a boolean indicating if lights are enabled on this scene
  24443. */
  24444. set: function (value) {
  24445. if (this._lightsEnabled === value) {
  24446. return;
  24447. }
  24448. this._lightsEnabled = value;
  24449. this.markAllMaterialsAsDirty(BABYLON.Material.LightDirtyFlag);
  24450. },
  24451. enumerable: true,
  24452. configurable: true
  24453. });
  24454. Object.defineProperty(Scene.prototype, "defaultMaterial", {
  24455. /** The default material used on meshes when no material is affected */
  24456. get: function () {
  24457. if (!this._defaultMaterial) {
  24458. this._defaultMaterial = new BABYLON.StandardMaterial("default material", this);
  24459. }
  24460. return this._defaultMaterial;
  24461. },
  24462. /** The default material used on meshes when no material is affected */
  24463. set: function (value) {
  24464. this._defaultMaterial = value;
  24465. },
  24466. enumerable: true,
  24467. configurable: true
  24468. });
  24469. Object.defineProperty(Scene.prototype, "texturesEnabled", {
  24470. get: function () {
  24471. return this._texturesEnabled;
  24472. },
  24473. /**
  24474. * Gets or sets a boolean indicating if textures are enabled on this scene
  24475. */
  24476. set: function (value) {
  24477. if (this._texturesEnabled === value) {
  24478. return;
  24479. }
  24480. this._texturesEnabled = value;
  24481. this.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  24482. },
  24483. enumerable: true,
  24484. configurable: true
  24485. });
  24486. Object.defineProperty(Scene.prototype, "skeletonsEnabled", {
  24487. get: function () {
  24488. return this._skeletonsEnabled;
  24489. },
  24490. /**
  24491. * Gets or sets a boolean indicating if skeletons are enabled on this scene
  24492. */
  24493. set: function (value) {
  24494. if (this._skeletonsEnabled === value) {
  24495. return;
  24496. }
  24497. this._skeletonsEnabled = value;
  24498. this.markAllMaterialsAsDirty(BABYLON.Material.AttributesDirtyFlag);
  24499. },
  24500. enumerable: true,
  24501. configurable: true
  24502. });
  24503. Object.defineProperty(Scene.prototype, "postProcessRenderPipelineManager", {
  24504. /**
  24505. * Gets the postprocess render pipeline manager
  24506. * @see http://doc.babylonjs.com/how_to/how_to_use_postprocessrenderpipeline
  24507. * @see http://doc.babylonjs.com/how_to/using_default_rendering_pipeline
  24508. */
  24509. get: function () {
  24510. if (!this._postProcessRenderPipelineManager) {
  24511. this._postProcessRenderPipelineManager = new BABYLON.PostProcessRenderPipelineManager();
  24512. }
  24513. return this._postProcessRenderPipelineManager;
  24514. },
  24515. enumerable: true,
  24516. configurable: true
  24517. });
  24518. Object.defineProperty(Scene.prototype, "mainSoundTrack", {
  24519. /**
  24520. * Gets the main soundtrack associated with the scene
  24521. */
  24522. get: function () {
  24523. if (!this._mainSoundTrack) {
  24524. this._mainSoundTrack = new BABYLON.SoundTrack(this, { mainTrack: true });
  24525. }
  24526. return this._mainSoundTrack;
  24527. },
  24528. enumerable: true,
  24529. configurable: true
  24530. });
  24531. Object.defineProperty(Scene.prototype, "_isAlternateRenderingEnabled", {
  24532. /** @hidden */
  24533. get: function () {
  24534. return this._alternateRendering;
  24535. },
  24536. enumerable: true,
  24537. configurable: true
  24538. });
  24539. Object.defineProperty(Scene.prototype, "frustumPlanes", {
  24540. /**
  24541. * Gets the list of frustum planes (built from the active camera)
  24542. */
  24543. get: function () {
  24544. return this._frustumPlanes;
  24545. },
  24546. enumerable: true,
  24547. configurable: true
  24548. });
  24549. Object.defineProperty(Scene.prototype, "geometryBufferRenderer", {
  24550. /**
  24551. * Gets the current geometry buffer associated to the scene.
  24552. */
  24553. get: function () {
  24554. return this._geometryBufferRenderer;
  24555. },
  24556. /**
  24557. * Sets the current geometry buffer for the scene.
  24558. */
  24559. set: function (geometryBufferRenderer) {
  24560. if (geometryBufferRenderer && geometryBufferRenderer.isSupported) {
  24561. this._geometryBufferRenderer = geometryBufferRenderer;
  24562. }
  24563. },
  24564. enumerable: true,
  24565. configurable: true
  24566. });
  24567. Object.defineProperty(Scene.prototype, "debugLayer", {
  24568. /**
  24569. * Gets the debug layer associated with the scene
  24570. * @see http://doc.babylonjs.com/features/playground_debuglayer
  24571. */
  24572. get: function () {
  24573. if (!this._debugLayer) {
  24574. this._debugLayer = new BABYLON.DebugLayer(this);
  24575. }
  24576. return this._debugLayer;
  24577. },
  24578. enumerable: true,
  24579. configurable: true
  24580. });
  24581. Object.defineProperty(Scene.prototype, "workerCollisions", {
  24582. /**
  24583. * Gets a boolean indicating if collisions are processed on a web worker
  24584. * @see http://doc.babylonjs.com/babylon101/cameras,_mesh_collisions_and_gravity#web-worker-based-collision-system-since-21
  24585. */
  24586. get: function () {
  24587. return this._workerCollisions;
  24588. },
  24589. set: function (enabled) {
  24590. if (!BABYLON.CollisionCoordinatorLegacy) {
  24591. return;
  24592. }
  24593. enabled = (enabled && !!Worker && !!BABYLON.CollisionWorker);
  24594. this._workerCollisions = enabled;
  24595. if (this.collisionCoordinator) {
  24596. this.collisionCoordinator.destroy();
  24597. }
  24598. this.collisionCoordinator = enabled ? new BABYLON.CollisionCoordinatorWorker() : new BABYLON.CollisionCoordinatorLegacy();
  24599. this.collisionCoordinator.init(this);
  24600. },
  24601. enumerable: true,
  24602. configurable: true
  24603. });
  24604. Object.defineProperty(Scene.prototype, "selectionOctree", {
  24605. /**
  24606. * Gets the octree used to boost mesh selection (picking)
  24607. * @see http://doc.babylonjs.com/how_to/optimizing_your_scene_with_octrees
  24608. */
  24609. get: function () {
  24610. return this._selectionOctree;
  24611. },
  24612. enumerable: true,
  24613. configurable: true
  24614. });
  24615. Object.defineProperty(Scene.prototype, "meshUnderPointer", {
  24616. /**
  24617. * Gets the mesh that is currently under the pointer
  24618. */
  24619. get: function () {
  24620. return this._pointerOverMesh;
  24621. },
  24622. enumerable: true,
  24623. configurable: true
  24624. });
  24625. Object.defineProperty(Scene.prototype, "pointerX", {
  24626. /**
  24627. * Gets the current on-screen X position of the pointer
  24628. */
  24629. get: function () {
  24630. return this._pointerX;
  24631. },
  24632. enumerable: true,
  24633. configurable: true
  24634. });
  24635. Object.defineProperty(Scene.prototype, "pointerY", {
  24636. /**
  24637. * Gets the current on-screen Y position of the pointer
  24638. */
  24639. get: function () {
  24640. return this._pointerY;
  24641. },
  24642. enumerable: true,
  24643. configurable: true
  24644. });
  24645. /**
  24646. * Gets the cached material (ie. the latest rendered one)
  24647. * @returns the cached material
  24648. */
  24649. Scene.prototype.getCachedMaterial = function () {
  24650. return this._cachedMaterial;
  24651. };
  24652. /**
  24653. * Gets the cached effect (ie. the latest rendered one)
  24654. * @returns the cached effect
  24655. */
  24656. Scene.prototype.getCachedEffect = function () {
  24657. return this._cachedEffect;
  24658. };
  24659. /**
  24660. * Gets the cached visibility state (ie. the latest rendered one)
  24661. * @returns the cached visibility state
  24662. */
  24663. Scene.prototype.getCachedVisibility = function () {
  24664. return this._cachedVisibility;
  24665. };
  24666. /**
  24667. * Gets a boolean indicating if the current material / effect / visibility must be bind again
  24668. * @param material defines the current material
  24669. * @param effect defines the current effect
  24670. * @param visibility defines the current visibility state
  24671. * @returns true if one parameter is not cached
  24672. */
  24673. Scene.prototype.isCachedMaterialInvalid = function (material, effect, visibility) {
  24674. if (visibility === void 0) { visibility = 1; }
  24675. return this._cachedEffect !== effect || this._cachedMaterial !== material || this._cachedVisibility !== visibility;
  24676. };
  24677. /**
  24678. * Gets the bounding box renderer associated with the scene
  24679. * @returns a BoundingBoxRenderer
  24680. */
  24681. Scene.prototype.getBoundingBoxRenderer = function () {
  24682. if (!this._boundingBoxRenderer) {
  24683. this._boundingBoxRenderer = new BABYLON.BoundingBoxRenderer(this);
  24684. }
  24685. return this._boundingBoxRenderer;
  24686. };
  24687. /**
  24688. * Gets the outline renderer associated with the scene
  24689. * @returns a OutlineRenderer
  24690. */
  24691. Scene.prototype.getOutlineRenderer = function () {
  24692. return this._outlineRenderer;
  24693. };
  24694. /**
  24695. * Gets the engine associated with the scene
  24696. * @returns an Engine
  24697. */
  24698. Scene.prototype.getEngine = function () {
  24699. return this._engine;
  24700. };
  24701. /**
  24702. * Gets the total number of vertices rendered per frame
  24703. * @returns the total number of vertices rendered per frame
  24704. */
  24705. Scene.prototype.getTotalVertices = function () {
  24706. return this._totalVertices.current;
  24707. };
  24708. Object.defineProperty(Scene.prototype, "totalVerticesPerfCounter", {
  24709. /**
  24710. * Gets the performance counter for total vertices
  24711. * @see http://doc.babylonjs.com/how_to/optimizing_your_scene#instrumentation
  24712. */
  24713. get: function () {
  24714. return this._totalVertices;
  24715. },
  24716. enumerable: true,
  24717. configurable: true
  24718. });
  24719. /**
  24720. * Gets the total number of active indices rendered per frame (You can deduce the number of rendered triangles by dividing this number by 3)
  24721. * @returns the total number of active indices rendered per frame
  24722. */
  24723. Scene.prototype.getActiveIndices = function () {
  24724. return this._activeIndices.current;
  24725. };
  24726. Object.defineProperty(Scene.prototype, "totalActiveIndicesPerfCounter", {
  24727. /**
  24728. * Gets the performance counter for active indices
  24729. * @see http://doc.babylonjs.com/how_to/optimizing_your_scene#instrumentation
  24730. */
  24731. get: function () {
  24732. return this._activeIndices;
  24733. },
  24734. enumerable: true,
  24735. configurable: true
  24736. });
  24737. /**
  24738. * Gets the total number of active particles rendered per frame
  24739. * @returns the total number of active particles rendered per frame
  24740. */
  24741. Scene.prototype.getActiveParticles = function () {
  24742. return this._activeParticles.current;
  24743. };
  24744. Object.defineProperty(Scene.prototype, "activeParticlesPerfCounter", {
  24745. /**
  24746. * Gets the performance counter for active particles
  24747. * @see http://doc.babylonjs.com/how_to/optimizing_your_scene#instrumentation
  24748. */
  24749. get: function () {
  24750. return this._activeParticles;
  24751. },
  24752. enumerable: true,
  24753. configurable: true
  24754. });
  24755. /**
  24756. * Gets the total number of active bones rendered per frame
  24757. * @returns the total number of active bones rendered per frame
  24758. */
  24759. Scene.prototype.getActiveBones = function () {
  24760. return this._activeBones.current;
  24761. };
  24762. Object.defineProperty(Scene.prototype, "activeBonesPerfCounter", {
  24763. /**
  24764. * Gets the performance counter for active bones
  24765. * @see http://doc.babylonjs.com/how_to/optimizing_your_scene#instrumentation
  24766. */
  24767. get: function () {
  24768. return this._activeBones;
  24769. },
  24770. enumerable: true,
  24771. configurable: true
  24772. });
  24773. /** @hidden */
  24774. Scene.prototype.getInterFramePerfCounter = function () {
  24775. BABYLON.Tools.Warn("getInterFramePerfCounter is deprecated. Please use SceneInstrumentation class");
  24776. return 0;
  24777. };
  24778. Object.defineProperty(Scene.prototype, "interFramePerfCounter", {
  24779. /** @hidden */
  24780. get: function () {
  24781. BABYLON.Tools.Warn("interFramePerfCounter is deprecated. Please use SceneInstrumentation class");
  24782. return null;
  24783. },
  24784. enumerable: true,
  24785. configurable: true
  24786. });
  24787. /** @hidden */
  24788. Scene.prototype.getLastFrameDuration = function () {
  24789. BABYLON.Tools.Warn("getLastFrameDuration is deprecated. Please use SceneInstrumentation class");
  24790. return 0;
  24791. };
  24792. Object.defineProperty(Scene.prototype, "lastFramePerfCounter", {
  24793. /** @hidden */
  24794. get: function () {
  24795. BABYLON.Tools.Warn("lastFramePerfCounter is deprecated. Please use SceneInstrumentation class");
  24796. return null;
  24797. },
  24798. enumerable: true,
  24799. configurable: true
  24800. });
  24801. /** @hidden */
  24802. Scene.prototype.getEvaluateActiveMeshesDuration = function () {
  24803. BABYLON.Tools.Warn("getEvaluateActiveMeshesDuration is deprecated. Please use SceneInstrumentation class");
  24804. return 0;
  24805. };
  24806. Object.defineProperty(Scene.prototype, "evaluateActiveMeshesDurationPerfCounter", {
  24807. /** @hidden */
  24808. get: function () {
  24809. BABYLON.Tools.Warn("evaluateActiveMeshesDurationPerfCounter is deprecated. Please use SceneInstrumentation class");
  24810. return null;
  24811. },
  24812. enumerable: true,
  24813. configurable: true
  24814. });
  24815. /**
  24816. * Gets the array of active meshes
  24817. * @returns an array of AbstractMesh
  24818. */
  24819. Scene.prototype.getActiveMeshes = function () {
  24820. return this._activeMeshes;
  24821. };
  24822. /** @hidden */
  24823. Scene.prototype.getRenderTargetsDuration = function () {
  24824. BABYLON.Tools.Warn("getRenderTargetsDuration is deprecated. Please use SceneInstrumentation class");
  24825. return 0;
  24826. };
  24827. /** @hidden */
  24828. Scene.prototype.getRenderDuration = function () {
  24829. BABYLON.Tools.Warn("getRenderDuration is deprecated. Please use SceneInstrumentation class");
  24830. return 0;
  24831. };
  24832. Object.defineProperty(Scene.prototype, "renderDurationPerfCounter", {
  24833. /** @hidden */
  24834. get: function () {
  24835. BABYLON.Tools.Warn("renderDurationPerfCounter is deprecated. Please use SceneInstrumentation class");
  24836. return null;
  24837. },
  24838. enumerable: true,
  24839. configurable: true
  24840. });
  24841. /** @hidden */
  24842. Scene.prototype.getParticlesDuration = function () {
  24843. BABYLON.Tools.Warn("getParticlesDuration is deprecated. Please use SceneInstrumentation class");
  24844. return 0;
  24845. };
  24846. Object.defineProperty(Scene.prototype, "particlesDurationPerfCounter", {
  24847. /** @hidden */
  24848. get: function () {
  24849. BABYLON.Tools.Warn("particlesDurationPerfCounter is deprecated. Please use SceneInstrumentation class");
  24850. return null;
  24851. },
  24852. enumerable: true,
  24853. configurable: true
  24854. });
  24855. /** @hidden */
  24856. Scene.prototype.getSpritesDuration = function () {
  24857. BABYLON.Tools.Warn("getSpritesDuration is deprecated. Please use SceneInstrumentation class");
  24858. return 0;
  24859. };
  24860. Object.defineProperty(Scene.prototype, "spriteDuractionPerfCounter", {
  24861. /** @hidden */
  24862. get: function () {
  24863. BABYLON.Tools.Warn("spriteDuractionPerfCounter is deprecated. Please use SceneInstrumentation class");
  24864. return null;
  24865. },
  24866. enumerable: true,
  24867. configurable: true
  24868. });
  24869. /**
  24870. * Gets the animation ratio (which is 1.0 is the scene renders at 60fps and 2 if the scene renders at 30fps, etc.)
  24871. * @returns a number
  24872. */
  24873. Scene.prototype.getAnimationRatio = function () {
  24874. return this._animationRatio;
  24875. };
  24876. /**
  24877. * Gets an unique Id for the current frame
  24878. * @returns a number
  24879. */
  24880. Scene.prototype.getRenderId = function () {
  24881. return this._renderId;
  24882. };
  24883. /** Call this function if you want to manually increment the render Id*/
  24884. Scene.prototype.incrementRenderId = function () {
  24885. this._renderId++;
  24886. };
  24887. Scene.prototype._updatePointerPosition = function (evt) {
  24888. var canvasRect = this._engine.getRenderingCanvasClientRect();
  24889. if (!canvasRect) {
  24890. return;
  24891. }
  24892. this._pointerX = evt.clientX - canvasRect.left;
  24893. this._pointerY = evt.clientY - canvasRect.top;
  24894. this._unTranslatedPointerX = this._pointerX;
  24895. this._unTranslatedPointerY = this._pointerY;
  24896. };
  24897. Scene.prototype._createUbo = function () {
  24898. this._sceneUbo = new BABYLON.UniformBuffer(this._engine, undefined, true);
  24899. this._sceneUbo.addUniform("viewProjection", 16);
  24900. this._sceneUbo.addUniform("view", 16);
  24901. };
  24902. Scene.prototype._createAlternateUbo = function () {
  24903. this._alternateSceneUbo = new BABYLON.UniformBuffer(this._engine, undefined, true);
  24904. this._alternateSceneUbo.addUniform("viewProjection", 16);
  24905. this._alternateSceneUbo.addUniform("view", 16);
  24906. };
  24907. // Pointers handling
  24908. /**
  24909. * Use this method to simulate a pointer move on a mesh
  24910. * The pickResult parameter can be obtained from a scene.pick or scene.pickWithRay
  24911. * @param pickResult pickingInfo of the object wished to simulate pointer event on
  24912. * @param pointerEventInit pointer event state to be used when simulating the pointer event (eg. pointer id for multitouch)
  24913. * @returns the current scene
  24914. */
  24915. Scene.prototype.simulatePointerMove = function (pickResult, pointerEventInit) {
  24916. var evt = new PointerEvent("pointermove", pointerEventInit);
  24917. return this._processPointerMove(pickResult, evt);
  24918. };
  24919. Scene.prototype._processPointerMove = function (pickResult, evt) {
  24920. var canvas = this._engine.getRenderingCanvas();
  24921. if (!canvas) {
  24922. return this;
  24923. }
  24924. if (pickResult && pickResult.hit && pickResult.pickedMesh) {
  24925. this.setPointerOverSprite(null);
  24926. this.setPointerOverMesh(pickResult.pickedMesh);
  24927. if (this._pointerOverMesh && this._pointerOverMesh.actionManager && this._pointerOverMesh.actionManager.hasPointerTriggers) {
  24928. if (this._pointerOverMesh.actionManager.hoverCursor) {
  24929. canvas.style.cursor = this._pointerOverMesh.actionManager.hoverCursor;
  24930. }
  24931. else {
  24932. canvas.style.cursor = this.hoverCursor;
  24933. }
  24934. }
  24935. else {
  24936. canvas.style.cursor = this.defaultCursor;
  24937. }
  24938. }
  24939. else {
  24940. this.setPointerOverMesh(null);
  24941. // Sprites
  24942. pickResult = this.pickSprite(this._unTranslatedPointerX, this._unTranslatedPointerY, this._spritePredicate, false, this.cameraToUseForPointers || undefined);
  24943. if (pickResult && pickResult.hit && pickResult.pickedSprite) {
  24944. this.setPointerOverSprite(pickResult.pickedSprite);
  24945. if (this._pointerOverSprite && this._pointerOverSprite.actionManager && this._pointerOverSprite.actionManager.hoverCursor) {
  24946. canvas.style.cursor = this._pointerOverSprite.actionManager.hoverCursor;
  24947. }
  24948. else {
  24949. canvas.style.cursor = this.hoverCursor;
  24950. }
  24951. }
  24952. else {
  24953. this.setPointerOverSprite(null);
  24954. // Restore pointer
  24955. canvas.style.cursor = this.defaultCursor;
  24956. }
  24957. }
  24958. if (pickResult) {
  24959. var type = evt.type === "mousewheel" || evt.type === "DOMMouseScroll" ? BABYLON.PointerEventTypes.POINTERWHEEL : BABYLON.PointerEventTypes.POINTERMOVE;
  24960. if (this.onPointerMove) {
  24961. this.onPointerMove(evt, pickResult, type);
  24962. }
  24963. if (this.onPointerObservable.hasObservers()) {
  24964. var pi = new BABYLON.PointerInfo(type, evt, pickResult);
  24965. this.onPointerObservable.notifyObservers(pi, type);
  24966. }
  24967. }
  24968. return this;
  24969. };
  24970. /**
  24971. * Use this method to simulate a pointer down on a mesh
  24972. * The pickResult parameter can be obtained from a scene.pick or scene.pickWithRay
  24973. * @param pickResult pickingInfo of the object wished to simulate pointer event on
  24974. * @param pointerEventInit pointer event state to be used when simulating the pointer event (eg. pointer id for multitouch)
  24975. * @returns the current scene
  24976. */
  24977. Scene.prototype.simulatePointerDown = function (pickResult, pointerEventInit) {
  24978. var evt = new PointerEvent("pointerdown", pointerEventInit);
  24979. return this._processPointerDown(pickResult, evt);
  24980. };
  24981. Scene.prototype._processPointerDown = function (pickResult, evt) {
  24982. var _this = this;
  24983. if (pickResult && pickResult.hit && pickResult.pickedMesh) {
  24984. this._pickedDownMesh = pickResult.pickedMesh;
  24985. var actionManager = pickResult.pickedMesh.actionManager;
  24986. if (actionManager) {
  24987. if (actionManager.hasPickTriggers) {
  24988. actionManager.processTrigger(BABYLON.ActionManager.OnPickDownTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  24989. switch (evt.button) {
  24990. case 0:
  24991. actionManager.processTrigger(BABYLON.ActionManager.OnLeftPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  24992. break;
  24993. case 1:
  24994. actionManager.processTrigger(BABYLON.ActionManager.OnCenterPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  24995. break;
  24996. case 2:
  24997. actionManager.processTrigger(BABYLON.ActionManager.OnRightPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  24998. break;
  24999. }
  25000. }
  25001. if (actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnLongPressTrigger)) {
  25002. window.setTimeout(function () {
  25003. 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);
  25004. if (pickResult && pickResult.hit && pickResult.pickedMesh && actionManager) {
  25005. if (_this._totalPointersPressed !== 0 &&
  25006. ((Date.now() - _this._startingPointerTime) > Scene.LongPressDelay) &&
  25007. (Math.abs(_this._startingPointerPosition.x - _this._pointerX) < Scene.DragMovementThreshold &&
  25008. Math.abs(_this._startingPointerPosition.y - _this._pointerY) < Scene.DragMovementThreshold)) {
  25009. _this._startingPointerTime = 0;
  25010. actionManager.processTrigger(BABYLON.ActionManager.OnLongPressTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  25011. }
  25012. }
  25013. }, Scene.LongPressDelay);
  25014. }
  25015. }
  25016. }
  25017. if (pickResult) {
  25018. var type = BABYLON.PointerEventTypes.POINTERDOWN;
  25019. if (this.onPointerDown) {
  25020. this.onPointerDown(evt, pickResult, type);
  25021. }
  25022. if (this.onPointerObservable.hasObservers()) {
  25023. var pi = new BABYLON.PointerInfo(type, evt, pickResult);
  25024. this.onPointerObservable.notifyObservers(pi, type);
  25025. }
  25026. }
  25027. return this;
  25028. };
  25029. /**
  25030. * Use this method to simulate a pointer up on a mesh
  25031. * The pickResult parameter can be obtained from a scene.pick or scene.pickWithRay
  25032. * @param pickResult pickingInfo of the object wished to simulate pointer event on
  25033. * @param pointerEventInit pointer event state to be used when simulating the pointer event (eg. pointer id for multitouch)
  25034. * @returns the current scene
  25035. */
  25036. Scene.prototype.simulatePointerUp = function (pickResult, pointerEventInit) {
  25037. var evt = new PointerEvent("pointerup", pointerEventInit);
  25038. var clickInfo = new ClickInfo();
  25039. clickInfo.singleClick = true;
  25040. clickInfo.ignore = true;
  25041. return this._processPointerUp(pickResult, evt, clickInfo);
  25042. };
  25043. Scene.prototype._processPointerUp = function (pickResult, evt, clickInfo) {
  25044. if (pickResult && pickResult && pickResult.pickedMesh) {
  25045. this._pickedUpMesh = pickResult.pickedMesh;
  25046. if (this._pickedDownMesh === this._pickedUpMesh) {
  25047. if (this.onPointerPick) {
  25048. this.onPointerPick(evt, pickResult);
  25049. }
  25050. if (clickInfo.singleClick && !clickInfo.ignore && this.onPointerObservable.hasObservers()) {
  25051. var type_1 = BABYLON.PointerEventTypes.POINTERPICK;
  25052. var pi = new BABYLON.PointerInfo(type_1, evt, pickResult);
  25053. this.onPointerObservable.notifyObservers(pi, type_1);
  25054. }
  25055. }
  25056. if (pickResult.pickedMesh.actionManager) {
  25057. if (clickInfo.ignore) {
  25058. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPickUpTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  25059. }
  25060. if (!clickInfo.hasSwiped && !clickInfo.ignore && clickInfo.singleClick) {
  25061. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  25062. }
  25063. if (clickInfo.doubleClick && !clickInfo.ignore && pickResult.pickedMesh.actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger)) {
  25064. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnDoublePickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  25065. }
  25066. }
  25067. }
  25068. if (this._pickedDownMesh &&
  25069. this._pickedDownMesh.actionManager &&
  25070. this._pickedDownMesh.actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnPickOutTrigger) &&
  25071. this._pickedDownMesh !== this._pickedUpMesh) {
  25072. this._pickedDownMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPickOutTrigger, BABYLON.ActionEvent.CreateNew(this._pickedDownMesh, evt));
  25073. }
  25074. var type = BABYLON.PointerEventTypes.POINTERUP;
  25075. if (this.onPointerObservable.hasObservers()) {
  25076. if (!clickInfo.ignore) {
  25077. if (!clickInfo.hasSwiped) {
  25078. if (clickInfo.singleClick && this.onPointerObservable.hasSpecificMask(BABYLON.PointerEventTypes.POINTERTAP)) {
  25079. var type_2 = BABYLON.PointerEventTypes.POINTERTAP;
  25080. var pi = new BABYLON.PointerInfo(type_2, evt, pickResult);
  25081. this.onPointerObservable.notifyObservers(pi, type_2);
  25082. }
  25083. if (clickInfo.doubleClick && this.onPointerObservable.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP)) {
  25084. var type_3 = BABYLON.PointerEventTypes.POINTERDOUBLETAP;
  25085. var pi = new BABYLON.PointerInfo(type_3, evt, pickResult);
  25086. this.onPointerObservable.notifyObservers(pi, type_3);
  25087. }
  25088. }
  25089. }
  25090. else {
  25091. var pi = new BABYLON.PointerInfo(type, evt, pickResult);
  25092. this.onPointerObservable.notifyObservers(pi, type);
  25093. }
  25094. }
  25095. if (this.onPointerUp) {
  25096. this.onPointerUp(evt, pickResult, type);
  25097. }
  25098. return this;
  25099. };
  25100. /**
  25101. * Attach events to the canvas (To handle actionManagers triggers and raise onPointerMove, onPointerDown and onPointerUp
  25102. * @param attachUp defines if you want to attach events to pointerup
  25103. * @param attachDown defines if you want to attach events to pointerdown
  25104. * @param attachMove defines if you want to attach events to pointermove
  25105. */
  25106. Scene.prototype.attachControl = function (attachUp, attachDown, attachMove) {
  25107. var _this = this;
  25108. if (attachUp === void 0) { attachUp = true; }
  25109. if (attachDown === void 0) { attachDown = true; }
  25110. if (attachMove === void 0) { attachMove = true; }
  25111. this._initActionManager = function (act, clickInfo) {
  25112. if (!_this._meshPickProceed) {
  25113. var pickResult = _this.pick(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this.pointerDownPredicate, false, _this.cameraToUseForPointers);
  25114. _this._currentPickResult = pickResult;
  25115. if (pickResult) {
  25116. act = (pickResult.hit && pickResult.pickedMesh) ? pickResult.pickedMesh.actionManager : null;
  25117. }
  25118. _this._meshPickProceed = true;
  25119. }
  25120. return act;
  25121. };
  25122. this._delayedSimpleClick = function (btn, clickInfo, cb) {
  25123. // double click delay is over and that no double click has been raised since, or the 2 consecutive keys pressed are different
  25124. if ((Date.now() - _this._previousStartingPointerTime > Scene.DoubleClickDelay && !_this._doubleClickOccured) ||
  25125. btn !== _this._previousButtonPressed) {
  25126. _this._doubleClickOccured = false;
  25127. clickInfo.singleClick = true;
  25128. clickInfo.ignore = false;
  25129. cb(clickInfo, _this._currentPickResult);
  25130. }
  25131. };
  25132. this._initClickEvent = function (obs1, obs2, evt, cb) {
  25133. var clickInfo = new ClickInfo();
  25134. _this._currentPickResult = null;
  25135. var act = null;
  25136. var checkPicking = obs1.hasSpecificMask(BABYLON.PointerEventTypes.POINTERPICK) || obs2.hasSpecificMask(BABYLON.PointerEventTypes.POINTERPICK)
  25137. || obs1.hasSpecificMask(BABYLON.PointerEventTypes.POINTERTAP) || obs2.hasSpecificMask(BABYLON.PointerEventTypes.POINTERTAP)
  25138. || obs1.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP) || obs2.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP);
  25139. if (!checkPicking && BABYLON.ActionManager && BABYLON.ActionManager.HasPickTriggers) {
  25140. act = _this._initActionManager(act, clickInfo);
  25141. if (act)
  25142. checkPicking = act.hasPickTriggers;
  25143. }
  25144. if (checkPicking) {
  25145. var btn = evt.button;
  25146. clickInfo.hasSwiped = Math.abs(_this._startingPointerPosition.x - _this._pointerX) > Scene.DragMovementThreshold ||
  25147. Math.abs(_this._startingPointerPosition.y - _this._pointerY) > Scene.DragMovementThreshold;
  25148. if (!clickInfo.hasSwiped) {
  25149. var checkSingleClickImmediately = !Scene.ExclusiveDoubleClickMode;
  25150. if (!checkSingleClickImmediately) {
  25151. checkSingleClickImmediately = !obs1.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP) &&
  25152. !obs2.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP);
  25153. if (checkSingleClickImmediately && !BABYLON.ActionManager.HasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger)) {
  25154. act = _this._initActionManager(act, clickInfo);
  25155. if (act)
  25156. checkSingleClickImmediately = !act.hasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger);
  25157. }
  25158. }
  25159. if (checkSingleClickImmediately) {
  25160. // single click detected if double click delay is over or two different successive keys pressed without exclusive double click or no double click required
  25161. if (Date.now() - _this._previousStartingPointerTime > Scene.DoubleClickDelay ||
  25162. btn !== _this._previousButtonPressed) {
  25163. clickInfo.singleClick = true;
  25164. cb(clickInfo, _this._currentPickResult);
  25165. }
  25166. }
  25167. // at least one double click is required to be check and exclusive double click is enabled
  25168. else {
  25169. // wait that no double click has been raised during the double click delay
  25170. _this._previousDelayedSimpleClickTimeout = _this._delayedSimpleClickTimeout;
  25171. _this._delayedSimpleClickTimeout = window.setTimeout(_this._delayedSimpleClick.bind(_this, btn, clickInfo, cb), Scene.DoubleClickDelay);
  25172. }
  25173. var checkDoubleClick = obs1.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP) ||
  25174. obs2.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP);
  25175. if (!checkDoubleClick && BABYLON.ActionManager.HasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger)) {
  25176. act = _this._initActionManager(act, clickInfo);
  25177. if (act)
  25178. checkDoubleClick = act.hasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger);
  25179. }
  25180. if (checkDoubleClick) {
  25181. // two successive keys pressed are equal, double click delay is not over and double click has not just occurred
  25182. if (btn === _this._previousButtonPressed &&
  25183. Date.now() - _this._previousStartingPointerTime < Scene.DoubleClickDelay &&
  25184. !_this._doubleClickOccured) {
  25185. // pointer has not moved for 2 clicks, it's a double click
  25186. if (!clickInfo.hasSwiped &&
  25187. Math.abs(_this._previousStartingPointerPosition.x - _this._startingPointerPosition.x) < Scene.DragMovementThreshold &&
  25188. Math.abs(_this._previousStartingPointerPosition.y - _this._startingPointerPosition.y) < Scene.DragMovementThreshold) {
  25189. _this._previousStartingPointerTime = 0;
  25190. _this._doubleClickOccured = true;
  25191. clickInfo.doubleClick = true;
  25192. clickInfo.ignore = false;
  25193. if (Scene.ExclusiveDoubleClickMode && _this._previousDelayedSimpleClickTimeout) {
  25194. clearTimeout(_this._previousDelayedSimpleClickTimeout);
  25195. }
  25196. _this._previousDelayedSimpleClickTimeout = _this._delayedSimpleClickTimeout;
  25197. cb(clickInfo, _this._currentPickResult);
  25198. }
  25199. // if the two successive clicks are too far, it's just two simple clicks
  25200. else {
  25201. _this._doubleClickOccured = false;
  25202. _this._previousStartingPointerTime = _this._startingPointerTime;
  25203. _this._previousStartingPointerPosition.x = _this._startingPointerPosition.x;
  25204. _this._previousStartingPointerPosition.y = _this._startingPointerPosition.y;
  25205. _this._previousButtonPressed = btn;
  25206. if (Scene.ExclusiveDoubleClickMode) {
  25207. if (_this._previousDelayedSimpleClickTimeout) {
  25208. clearTimeout(_this._previousDelayedSimpleClickTimeout);
  25209. }
  25210. _this._previousDelayedSimpleClickTimeout = _this._delayedSimpleClickTimeout;
  25211. cb(clickInfo, _this._previousPickResult);
  25212. }
  25213. else {
  25214. cb(clickInfo, _this._currentPickResult);
  25215. }
  25216. }
  25217. }
  25218. // just the first click of the double has been raised
  25219. else {
  25220. _this._doubleClickOccured = false;
  25221. _this._previousStartingPointerTime = _this._startingPointerTime;
  25222. _this._previousStartingPointerPosition.x = _this._startingPointerPosition.x;
  25223. _this._previousStartingPointerPosition.y = _this._startingPointerPosition.y;
  25224. _this._previousButtonPressed = btn;
  25225. }
  25226. }
  25227. }
  25228. }
  25229. clickInfo.ignore = true;
  25230. cb(clickInfo, _this._currentPickResult);
  25231. };
  25232. this._spritePredicate = function (sprite) {
  25233. return sprite.isPickable && sprite.actionManager && sprite.actionManager.hasPointerTriggers;
  25234. };
  25235. this._onPointerMove = function (evt) {
  25236. _this._updatePointerPosition(evt);
  25237. // PreObservable support
  25238. if (_this.onPrePointerObservable.hasObservers()) {
  25239. var type = evt.type === "mousewheel" || evt.type === "DOMMouseScroll" ? BABYLON.PointerEventTypes.POINTERWHEEL : BABYLON.PointerEventTypes.POINTERMOVE;
  25240. var pi = new BABYLON.PointerInfoPre(type, evt, _this._unTranslatedPointerX, _this._unTranslatedPointerY);
  25241. _this.onPrePointerObservable.notifyObservers(pi, type);
  25242. if (pi.skipOnPointerObservable) {
  25243. return;
  25244. }
  25245. }
  25246. if (!_this.cameraToUseForPointers && !_this.activeCamera) {
  25247. return;
  25248. }
  25249. if (!_this.pointerMovePredicate) {
  25250. _this.pointerMovePredicate = function (mesh) { return mesh.isPickable && mesh.isVisible && mesh.isReady() && mesh.isEnabled() && (mesh.enablePointerMoveEvents || _this.constantlyUpdateMeshUnderPointer || (mesh.actionManager !== null && mesh.actionManager !== undefined)); };
  25251. }
  25252. // Meshes
  25253. var pickResult = _this.pick(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this.pointerMovePredicate, false, _this.cameraToUseForPointers);
  25254. _this._processPointerMove(pickResult, evt);
  25255. };
  25256. this._onPointerDown = function (evt) {
  25257. _this._totalPointersPressed++;
  25258. _this._pickedDownMesh = null;
  25259. _this._meshPickProceed = false;
  25260. _this._updatePointerPosition(evt);
  25261. if (_this.preventDefaultOnPointerDown && canvas) {
  25262. evt.preventDefault();
  25263. canvas.focus();
  25264. }
  25265. // PreObservable support
  25266. if (_this.onPrePointerObservable.hasObservers()) {
  25267. var type = BABYLON.PointerEventTypes.POINTERDOWN;
  25268. var pi = new BABYLON.PointerInfoPre(type, evt, _this._unTranslatedPointerX, _this._unTranslatedPointerY);
  25269. _this.onPrePointerObservable.notifyObservers(pi, type);
  25270. if (pi.skipOnPointerObservable) {
  25271. return;
  25272. }
  25273. }
  25274. if (!_this.cameraToUseForPointers && !_this.activeCamera) {
  25275. return;
  25276. }
  25277. _this._startingPointerPosition.x = _this._pointerX;
  25278. _this._startingPointerPosition.y = _this._pointerY;
  25279. _this._startingPointerTime = Date.now();
  25280. if (!_this.pointerDownPredicate) {
  25281. _this.pointerDownPredicate = function (mesh) {
  25282. return mesh.isPickable && mesh.isVisible && mesh.isReady() && mesh.isEnabled();
  25283. };
  25284. }
  25285. // Meshes
  25286. _this._pickedDownMesh = null;
  25287. var pickResult = _this.pick(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this.pointerDownPredicate, false, _this.cameraToUseForPointers);
  25288. _this._processPointerDown(pickResult, evt);
  25289. // Sprites
  25290. _this._pickedDownSprite = null;
  25291. if (_this.spriteManagers.length > 0) {
  25292. pickResult = _this.pickSprite(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this._spritePredicate, false, _this.cameraToUseForPointers || undefined);
  25293. if (pickResult && pickResult.hit && pickResult.pickedSprite) {
  25294. if (pickResult.pickedSprite.actionManager) {
  25295. _this._pickedDownSprite = pickResult.pickedSprite;
  25296. switch (evt.button) {
  25297. case 0:
  25298. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnLeftPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  25299. break;
  25300. case 1:
  25301. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnCenterPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  25302. break;
  25303. case 2:
  25304. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnRightPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  25305. break;
  25306. }
  25307. if (pickResult.pickedSprite.actionManager) {
  25308. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickDownTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  25309. }
  25310. }
  25311. }
  25312. }
  25313. };
  25314. this._onPointerUp = function (evt) {
  25315. if (_this._totalPointersPressed === 0) { // We are attaching the pointer up to windows because of a bug in FF
  25316. return; // So we need to test it the pointer down was pressed before.
  25317. }
  25318. _this._totalPointersPressed--;
  25319. _this._pickedUpMesh = null;
  25320. _this._meshPickProceed = false;
  25321. _this._updatePointerPosition(evt);
  25322. _this._initClickEvent(_this.onPrePointerObservable, _this.onPointerObservable, evt, function (clickInfo, pickResult) {
  25323. // PreObservable support
  25324. if (_this.onPrePointerObservable.hasObservers()) {
  25325. if (!clickInfo.ignore) {
  25326. if (!clickInfo.hasSwiped) {
  25327. if (clickInfo.singleClick && _this.onPrePointerObservable.hasSpecificMask(BABYLON.PointerEventTypes.POINTERTAP)) {
  25328. var type = BABYLON.PointerEventTypes.POINTERTAP;
  25329. var pi = new BABYLON.PointerInfoPre(type, evt, _this._unTranslatedPointerX, _this._unTranslatedPointerY);
  25330. _this.onPrePointerObservable.notifyObservers(pi, type);
  25331. if (pi.skipOnPointerObservable) {
  25332. return;
  25333. }
  25334. }
  25335. if (clickInfo.doubleClick && _this.onPrePointerObservable.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP)) {
  25336. var type = BABYLON.PointerEventTypes.POINTERDOUBLETAP;
  25337. var pi = new BABYLON.PointerInfoPre(type, evt, _this._unTranslatedPointerX, _this._unTranslatedPointerY);
  25338. _this.onPrePointerObservable.notifyObservers(pi, type);
  25339. if (pi.skipOnPointerObservable) {
  25340. return;
  25341. }
  25342. }
  25343. }
  25344. }
  25345. else {
  25346. var type = BABYLON.PointerEventTypes.POINTERUP;
  25347. var pi = new BABYLON.PointerInfoPre(type, evt, _this._unTranslatedPointerX, _this._unTranslatedPointerY);
  25348. _this.onPrePointerObservable.notifyObservers(pi, type);
  25349. if (pi.skipOnPointerObservable) {
  25350. return;
  25351. }
  25352. }
  25353. }
  25354. if (!_this.cameraToUseForPointers && !_this.activeCamera) {
  25355. return;
  25356. }
  25357. if (!_this.pointerUpPredicate) {
  25358. _this.pointerUpPredicate = function (mesh) {
  25359. return mesh.isPickable && mesh.isVisible && mesh.isReady() && mesh.isEnabled();
  25360. };
  25361. }
  25362. // Meshes
  25363. if (!_this._meshPickProceed && (BABYLON.ActionManager && BABYLON.ActionManager.HasTriggers || _this.onPointerObservable.hasObservers())) {
  25364. _this._initActionManager(null, clickInfo);
  25365. }
  25366. if (!pickResult) {
  25367. pickResult = _this._currentPickResult;
  25368. }
  25369. _this._processPointerUp(pickResult, evt, clickInfo);
  25370. // Sprites
  25371. if (_this.spriteManagers.length > 0) {
  25372. var spritePickResult = _this.pickSprite(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this._spritePredicate, false, _this.cameraToUseForPointers || undefined);
  25373. if (spritePickResult) {
  25374. if (spritePickResult.hit && spritePickResult.pickedSprite) {
  25375. if (spritePickResult.pickedSprite.actionManager) {
  25376. spritePickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickUpTrigger, BABYLON.ActionEvent.CreateNewFromSprite(spritePickResult.pickedSprite, _this, evt));
  25377. if (spritePickResult.pickedSprite.actionManager) {
  25378. if (Math.abs(_this._startingPointerPosition.x - _this._pointerX) < Scene.DragMovementThreshold && Math.abs(_this._startingPointerPosition.y - _this._pointerY) < Scene.DragMovementThreshold) {
  25379. spritePickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(spritePickResult.pickedSprite, _this, evt));
  25380. }
  25381. }
  25382. }
  25383. }
  25384. if (_this._pickedDownSprite && _this._pickedDownSprite.actionManager && _this._pickedDownSprite !== spritePickResult.pickedSprite) {
  25385. _this._pickedDownSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickOutTrigger, BABYLON.ActionEvent.CreateNewFromSprite(_this._pickedDownSprite, _this, evt));
  25386. }
  25387. }
  25388. }
  25389. _this._previousPickResult = _this._currentPickResult;
  25390. });
  25391. };
  25392. this._onKeyDown = function (evt) {
  25393. var type = BABYLON.KeyboardEventTypes.KEYDOWN;
  25394. if (_this.onPreKeyboardObservable.hasObservers()) {
  25395. var pi = new BABYLON.KeyboardInfoPre(type, evt);
  25396. _this.onPreKeyboardObservable.notifyObservers(pi, type);
  25397. if (pi.skipOnPointerObservable) {
  25398. return;
  25399. }
  25400. }
  25401. if (_this.onKeyboardObservable.hasObservers()) {
  25402. var pi = new BABYLON.KeyboardInfo(type, evt);
  25403. _this.onKeyboardObservable.notifyObservers(pi, type);
  25404. }
  25405. if (_this.actionManager) {
  25406. _this.actionManager.processTrigger(BABYLON.ActionManager.OnKeyDownTrigger, BABYLON.ActionEvent.CreateNewFromScene(_this, evt));
  25407. }
  25408. };
  25409. this._onKeyUp = function (evt) {
  25410. var type = BABYLON.KeyboardEventTypes.KEYUP;
  25411. if (_this.onPreKeyboardObservable.hasObservers()) {
  25412. var pi = new BABYLON.KeyboardInfoPre(type, evt);
  25413. _this.onPreKeyboardObservable.notifyObservers(pi, type);
  25414. if (pi.skipOnPointerObservable) {
  25415. return;
  25416. }
  25417. }
  25418. if (_this.onKeyboardObservable.hasObservers()) {
  25419. var pi = new BABYLON.KeyboardInfo(type, evt);
  25420. _this.onKeyboardObservable.notifyObservers(pi, type);
  25421. }
  25422. if (_this.actionManager) {
  25423. _this.actionManager.processTrigger(BABYLON.ActionManager.OnKeyUpTrigger, BABYLON.ActionEvent.CreateNewFromScene(_this, evt));
  25424. }
  25425. };
  25426. var engine = this.getEngine();
  25427. this._onCanvasFocusObserver = engine.onCanvasFocusObservable.add(function () {
  25428. if (!canvas) {
  25429. return;
  25430. }
  25431. canvas.addEventListener("keydown", _this._onKeyDown, false);
  25432. canvas.addEventListener("keyup", _this._onKeyUp, false);
  25433. });
  25434. this._onCanvasBlurObserver = engine.onCanvasBlurObservable.add(function () {
  25435. if (!canvas) {
  25436. return;
  25437. }
  25438. canvas.removeEventListener("keydown", _this._onKeyDown);
  25439. canvas.removeEventListener("keyup", _this._onKeyUp);
  25440. });
  25441. var eventPrefix = BABYLON.Tools.GetPointerPrefix();
  25442. var canvas = this._engine.getRenderingCanvas();
  25443. if (!canvas) {
  25444. return;
  25445. }
  25446. if (attachMove) {
  25447. canvas.addEventListener(eventPrefix + "move", this._onPointerMove, false);
  25448. // Wheel
  25449. canvas.addEventListener('mousewheel', this._onPointerMove, false);
  25450. canvas.addEventListener('DOMMouseScroll', this._onPointerMove, false);
  25451. }
  25452. if (attachDown) {
  25453. canvas.addEventListener(eventPrefix + "down", this._onPointerDown, false);
  25454. }
  25455. if (attachUp) {
  25456. window.addEventListener(eventPrefix + "up", this._onPointerUp, false);
  25457. }
  25458. canvas.tabIndex = 1;
  25459. };
  25460. /** Detaches all event handlers*/
  25461. Scene.prototype.detachControl = function () {
  25462. var engine = this.getEngine();
  25463. var eventPrefix = BABYLON.Tools.GetPointerPrefix();
  25464. var canvas = engine.getRenderingCanvas();
  25465. if (!canvas) {
  25466. return;
  25467. }
  25468. canvas.removeEventListener(eventPrefix + "move", this._onPointerMove);
  25469. canvas.removeEventListener(eventPrefix + "down", this._onPointerDown);
  25470. window.removeEventListener(eventPrefix + "up", this._onPointerUp);
  25471. if (this._onCanvasBlurObserver) {
  25472. engine.onCanvasBlurObservable.remove(this._onCanvasBlurObserver);
  25473. }
  25474. if (this._onCanvasFocusObserver) {
  25475. engine.onCanvasFocusObservable.remove(this._onCanvasFocusObserver);
  25476. }
  25477. // Wheel
  25478. canvas.removeEventListener('mousewheel', this._onPointerMove);
  25479. canvas.removeEventListener('DOMMouseScroll', this._onPointerMove);
  25480. // Keyboard
  25481. canvas.removeEventListener("keydown", this._onKeyDown);
  25482. canvas.removeEventListener("keyup", this._onKeyUp);
  25483. // Observables
  25484. this.onKeyboardObservable.clear();
  25485. this.onPreKeyboardObservable.clear();
  25486. this.onPointerObservable.clear();
  25487. this.onPrePointerObservable.clear();
  25488. };
  25489. /**
  25490. * This function will check if the scene can be rendered (textures are loaded, shaders are compiled)
  25491. * Delay loaded resources are not taking in account
  25492. * @return true if all required resources are ready
  25493. */
  25494. Scene.prototype.isReady = function () {
  25495. if (this._isDisposed) {
  25496. return false;
  25497. }
  25498. if (this._pendingData.length > 0) {
  25499. return false;
  25500. }
  25501. var index;
  25502. var engine = this.getEngine();
  25503. // Geometries
  25504. for (index = 0; index < this._geometries.length; index++) {
  25505. var geometry = this._geometries[index];
  25506. if (geometry.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  25507. return false;
  25508. }
  25509. }
  25510. // Meshes
  25511. for (index = 0; index < this.meshes.length; index++) {
  25512. var mesh = this.meshes[index];
  25513. if (!mesh.isEnabled()) {
  25514. continue;
  25515. }
  25516. if (!mesh.subMeshes || mesh.subMeshes.length === 0) {
  25517. continue;
  25518. }
  25519. if (!mesh.isReady(true)) {
  25520. return false;
  25521. }
  25522. // Effect layers
  25523. var hardwareInstancedRendering = mesh.getClassName() === "InstancedMesh" || engine.getCaps().instancedArrays && mesh.instances.length > 0;
  25524. for (var _i = 0, _a = this.effectLayers; _i < _a.length; _i++) {
  25525. var layer = _a[_i];
  25526. if (!layer.hasMesh(mesh)) {
  25527. continue;
  25528. }
  25529. for (var _b = 0, _c = mesh.subMeshes; _b < _c.length; _b++) {
  25530. var subMesh = _c[_b];
  25531. if (!layer.isReady(subMesh, hardwareInstancedRendering)) {
  25532. return false;
  25533. }
  25534. }
  25535. }
  25536. }
  25537. // Post-processes
  25538. if (this.activeCameras && this.activeCameras.length > 0) {
  25539. for (var _d = 0, _e = this.activeCameras; _d < _e.length; _d++) {
  25540. var camera = _e[_d];
  25541. if (!camera.isReady(true)) {
  25542. return false;
  25543. }
  25544. }
  25545. }
  25546. else if (this.activeCamera) {
  25547. if (!this.activeCamera.isReady(true)) {
  25548. return false;
  25549. }
  25550. }
  25551. // Particles
  25552. for (var _f = 0, _g = this.particleSystems; _f < _g.length; _f++) {
  25553. var particleSystem = _g[_f];
  25554. if (!particleSystem.isReady()) {
  25555. return false;
  25556. }
  25557. }
  25558. return true;
  25559. };
  25560. /** Resets all cached information relative to material (including effect and visibility) */
  25561. Scene.prototype.resetCachedMaterial = function () {
  25562. this._cachedMaterial = null;
  25563. this._cachedEffect = null;
  25564. this._cachedVisibility = null;
  25565. };
  25566. /**
  25567. * Registers a function to be called before every frame render
  25568. * @param func defines the function to register
  25569. */
  25570. Scene.prototype.registerBeforeRender = function (func) {
  25571. this.onBeforeRenderObservable.add(func);
  25572. };
  25573. /**
  25574. * Unregisters a function called before every frame render
  25575. * @param func defines the function to unregister
  25576. */
  25577. Scene.prototype.unregisterBeforeRender = function (func) {
  25578. this.onBeforeRenderObservable.removeCallback(func);
  25579. };
  25580. /**
  25581. * Registers a function to be called after every frame render
  25582. * @param func defines the function to register
  25583. */
  25584. Scene.prototype.registerAfterRender = function (func) {
  25585. this.onAfterRenderObservable.add(func);
  25586. };
  25587. /**
  25588. * Unregisters a function called after every frame render
  25589. * @param func defines the function to unregister
  25590. */
  25591. Scene.prototype.unregisterAfterRender = function (func) {
  25592. this.onAfterRenderObservable.removeCallback(func);
  25593. };
  25594. Scene.prototype._executeOnceBeforeRender = function (func) {
  25595. var _this = this;
  25596. var execFunc = function () {
  25597. func();
  25598. setTimeout(function () {
  25599. _this.unregisterBeforeRender(execFunc);
  25600. });
  25601. };
  25602. this.registerBeforeRender(execFunc);
  25603. };
  25604. /**
  25605. * The provided function will run before render once and will be disposed afterwards.
  25606. * A timeout delay can be provided so that the function will be executed in N ms.
  25607. * The timeout is using the browser's native setTimeout so time percision cannot be guaranteed.
  25608. * @param func The function to be executed.
  25609. * @param timeout optional delay in ms
  25610. */
  25611. Scene.prototype.executeOnceBeforeRender = function (func, timeout) {
  25612. var _this = this;
  25613. if (timeout !== undefined) {
  25614. setTimeout(function () {
  25615. _this._executeOnceBeforeRender(func);
  25616. }, timeout);
  25617. }
  25618. else {
  25619. this._executeOnceBeforeRender(func);
  25620. }
  25621. };
  25622. /** @hidden */
  25623. Scene.prototype._addPendingData = function (data) {
  25624. this._pendingData.push(data);
  25625. };
  25626. /** @hidden */
  25627. Scene.prototype._removePendingData = function (data) {
  25628. var wasLoading = this.isLoading;
  25629. var index = this._pendingData.indexOf(data);
  25630. if (index !== -1) {
  25631. this._pendingData.splice(index, 1);
  25632. }
  25633. if (wasLoading && !this.isLoading) {
  25634. this.onDataLoadedObservable.notifyObservers(this);
  25635. }
  25636. };
  25637. /**
  25638. * Returns the number of items waiting to be loaded
  25639. * @returns the number of items waiting to be loaded
  25640. */
  25641. Scene.prototype.getWaitingItemsCount = function () {
  25642. return this._pendingData.length;
  25643. };
  25644. Object.defineProperty(Scene.prototype, "isLoading", {
  25645. /**
  25646. * Returns a boolean indicating if the scene is still loading data
  25647. */
  25648. get: function () {
  25649. return this._pendingData.length > 0;
  25650. },
  25651. enumerable: true,
  25652. configurable: true
  25653. });
  25654. /**
  25655. * Registers a function to be executed when the scene is ready
  25656. * @param {Function} func - the function to be executed
  25657. */
  25658. Scene.prototype.executeWhenReady = function (func) {
  25659. var _this = this;
  25660. this.onReadyObservable.add(func);
  25661. if (this._executeWhenReadyTimeoutId !== -1) {
  25662. return;
  25663. }
  25664. this._executeWhenReadyTimeoutId = setTimeout(function () {
  25665. _this._checkIsReady();
  25666. }, 150);
  25667. };
  25668. /**
  25669. * Returns a promise that resolves when the scene is ready
  25670. * @returns A promise that resolves when the scene is ready
  25671. */
  25672. Scene.prototype.whenReadyAsync = function () {
  25673. var _this = this;
  25674. return new Promise(function (resolve) {
  25675. _this.executeWhenReady(function () {
  25676. resolve();
  25677. });
  25678. });
  25679. };
  25680. /** @hidden */
  25681. Scene.prototype._checkIsReady = function () {
  25682. var _this = this;
  25683. if (this.isReady()) {
  25684. this.onReadyObservable.notifyObservers(this);
  25685. this.onReadyObservable.clear();
  25686. this._executeWhenReadyTimeoutId = -1;
  25687. return;
  25688. }
  25689. this._executeWhenReadyTimeoutId = setTimeout(function () {
  25690. _this._checkIsReady();
  25691. }, 150);
  25692. };
  25693. // Animations
  25694. /**
  25695. * Will start the animation sequence of a given target
  25696. * @param target defines the target
  25697. * @param from defines from which frame should animation start
  25698. * @param to defines until which frame should animation run.
  25699. * @param weight defines the weight to apply to the animation (1.0 by default)
  25700. * @param loop defines if the animation loops
  25701. * @param speedRatio defines the speed in which to run the animation (1.0 by default)
  25702. * @param onAnimationEnd defines the function to be executed when the animation ends
  25703. * @param animatable defines an animatable object. If not provided a new one will be created from the given params
  25704. * @returns the animatable object created for this animation
  25705. */
  25706. Scene.prototype.beginWeightedAnimation = function (target, from, to, weight, loop, speedRatio, onAnimationEnd, animatable) {
  25707. if (weight === void 0) { weight = 1.0; }
  25708. if (speedRatio === void 0) { speedRatio = 1.0; }
  25709. var returnedAnimatable = this.beginAnimation(target, from, to, loop, speedRatio, onAnimationEnd, animatable, false);
  25710. returnedAnimatable.weight = weight;
  25711. return returnedAnimatable;
  25712. };
  25713. /**
  25714. * Will start the animation sequence of a given target
  25715. * @param target defines the target
  25716. * @param from defines from which frame should animation start
  25717. * @param to defines until which frame should animation run.
  25718. * @param loop defines if the animation loops
  25719. * @param speedRatio defines the speed in which to run the animation (1.0 by default)
  25720. * @param onAnimationEnd defines the function to be executed when the animation ends
  25721. * @param animatable defines an animatable object. If not provided a new one will be created from the given params
  25722. * @param stopCurrent defines if the current animations must be stopped first (true by default)
  25723. * @returns the animatable object created for this animation
  25724. */
  25725. Scene.prototype.beginAnimation = function (target, from, to, loop, speedRatio, onAnimationEnd, animatable, stopCurrent) {
  25726. if (speedRatio === void 0) { speedRatio = 1.0; }
  25727. if (stopCurrent === void 0) { stopCurrent = true; }
  25728. if (from > to && speedRatio > 0) {
  25729. speedRatio *= -1;
  25730. }
  25731. if (stopCurrent) {
  25732. this.stopAnimation(target);
  25733. }
  25734. if (!animatable) {
  25735. animatable = new BABYLON.Animatable(this, target, from, to, loop, speedRatio, onAnimationEnd);
  25736. }
  25737. // Local animations
  25738. if (target.animations) {
  25739. animatable.appendAnimations(target, target.animations);
  25740. }
  25741. // Children animations
  25742. if (target.getAnimatables) {
  25743. var animatables = target.getAnimatables();
  25744. for (var index = 0; index < animatables.length; index++) {
  25745. this.beginAnimation(animatables[index], from, to, loop, speedRatio, onAnimationEnd, animatable, stopCurrent);
  25746. }
  25747. }
  25748. animatable.reset();
  25749. return animatable;
  25750. };
  25751. /**
  25752. * Begin a new animation on a given node
  25753. * @param target defines the target where the animation will take place
  25754. * @param animations defines the list of animations to start
  25755. * @param from defines the initial value
  25756. * @param to defines the final value
  25757. * @param loop defines if you want animation to loop (off by default)
  25758. * @param speedRatio defines the speed ratio to apply to all animations
  25759. * @param onAnimationEnd defines the callback to call when an animation ends (will be called once per node)
  25760. * @returns the list of created animatables
  25761. */
  25762. Scene.prototype.beginDirectAnimation = function (target, animations, from, to, loop, speedRatio, onAnimationEnd) {
  25763. if (speedRatio === undefined) {
  25764. speedRatio = 1.0;
  25765. }
  25766. var animatable = new BABYLON.Animatable(this, target, from, to, loop, speedRatio, onAnimationEnd, animations);
  25767. return animatable;
  25768. };
  25769. /**
  25770. * Begin a new animation on a given node and its hierarchy
  25771. * @param target defines the root node where the animation will take place
  25772. * @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.
  25773. * @param animations defines the list of animations to start
  25774. * @param from defines the initial value
  25775. * @param to defines the final value
  25776. * @param loop defines if you want animation to loop (off by default)
  25777. * @param speedRatio defines the speed ratio to apply to all animations
  25778. * @param onAnimationEnd defines the callback to call when an animation ends (will be called once per node)
  25779. * @returns the list of animatables created for all nodes
  25780. */
  25781. Scene.prototype.beginDirectHierarchyAnimation = function (target, directDescendantsOnly, animations, from, to, loop, speedRatio, onAnimationEnd) {
  25782. var children = target.getDescendants(directDescendantsOnly);
  25783. var result = [];
  25784. for (var _i = 0, children_1 = children; _i < children_1.length; _i++) {
  25785. var child = children_1[_i];
  25786. result.push(this.beginDirectAnimation(child, animations, from, to, loop, speedRatio, onAnimationEnd));
  25787. }
  25788. return result;
  25789. };
  25790. /**
  25791. * Gets the animatable associated with a specific target
  25792. * @param target defines the target of the animatable
  25793. * @returns the required animatable if found
  25794. */
  25795. Scene.prototype.getAnimatableByTarget = function (target) {
  25796. for (var index = 0; index < this._activeAnimatables.length; index++) {
  25797. if (this._activeAnimatables[index].target === target) {
  25798. return this._activeAnimatables[index];
  25799. }
  25800. }
  25801. return null;
  25802. };
  25803. /**
  25804. * Gets all animatables associated with a given target
  25805. * @param target defines the target to look animatables for
  25806. * @returns an array of Animatables
  25807. */
  25808. Scene.prototype.getAllAnimatablesByTarget = function (target) {
  25809. var result = [];
  25810. for (var index = 0; index < this._activeAnimatables.length; index++) {
  25811. if (this._activeAnimatables[index].target === target) {
  25812. result.push(this._activeAnimatables[index]);
  25813. }
  25814. }
  25815. return result;
  25816. };
  25817. Object.defineProperty(Scene.prototype, "animatables", {
  25818. /**
  25819. * Gets all animatable attached to the scene
  25820. */
  25821. get: function () {
  25822. return this._activeAnimatables;
  25823. },
  25824. enumerable: true,
  25825. configurable: true
  25826. });
  25827. /**
  25828. * Will stop the animation of the given target
  25829. * @param target - the target
  25830. * @param animationName - the name of the animation to stop (all animations will be stopped if empty)
  25831. */
  25832. Scene.prototype.stopAnimation = function (target, animationName) {
  25833. var animatables = this.getAllAnimatablesByTarget(target);
  25834. for (var _i = 0, animatables_1 = animatables; _i < animatables_1.length; _i++) {
  25835. var animatable = animatables_1[_i];
  25836. animatable.stop(animationName);
  25837. }
  25838. };
  25839. /**
  25840. * Stops and removes all animations that have been applied to the scene
  25841. */
  25842. Scene.prototype.stopAllAnimations = function () {
  25843. if (this._activeAnimatables) {
  25844. for (var i = 0; i < this._activeAnimatables.length; i++) {
  25845. this._activeAnimatables[i].stop();
  25846. }
  25847. this._activeAnimatables = [];
  25848. }
  25849. for (var _i = 0, _a = this.animationGroups; _i < _a.length; _i++) {
  25850. var group = _a[_i];
  25851. group.stop();
  25852. }
  25853. };
  25854. Scene.prototype._animate = function () {
  25855. if (!this.animationsEnabled || this._activeAnimatables.length === 0) {
  25856. return;
  25857. }
  25858. // Getting time
  25859. var now = BABYLON.Tools.Now;
  25860. if (!this._animationTimeLast) {
  25861. if (this._pendingData.length > 0) {
  25862. return;
  25863. }
  25864. this._animationTimeLast = now;
  25865. }
  25866. var deltaTime = this.useConstantAnimationDeltaTime ? 16.0 : (now - this._animationTimeLast) * this.animationTimeScale;
  25867. this._animationTime += deltaTime;
  25868. this._animationTimeLast = now;
  25869. for (var index = 0; index < this._activeAnimatables.length; index++) {
  25870. this._activeAnimatables[index]._animate(this._animationTime);
  25871. }
  25872. // Late animation bindings
  25873. this._processLateAnimationBindings();
  25874. };
  25875. /** @hidden */
  25876. Scene.prototype._registerTargetForLateAnimationBinding = function (runtimeAnimation) {
  25877. var target = runtimeAnimation.target;
  25878. this._registeredForLateAnimationBindings.pushNoDuplicate(target);
  25879. if (!target._lateAnimationHolders) {
  25880. target._lateAnimationHolders = {};
  25881. }
  25882. if (!target._lateAnimationHolders[runtimeAnimation.targetPath]) {
  25883. target._lateAnimationHolders[runtimeAnimation.targetPath] = {
  25884. totalWeight: 0,
  25885. animations: []
  25886. };
  25887. }
  25888. target._lateAnimationHolders[runtimeAnimation.targetPath].animations.push(runtimeAnimation);
  25889. target._lateAnimationHolders[runtimeAnimation.targetPath].totalWeight += runtimeAnimation.weight;
  25890. };
  25891. Scene.prototype._processLateAnimationBindingsForMatrices = function (holder, originalValue) {
  25892. var normalizer = 1.0;
  25893. var finalPosition = BABYLON.Tmp.Vector3[0];
  25894. var finalScaling = BABYLON.Tmp.Vector3[1];
  25895. var finalQuaternion = BABYLON.Tmp.Quaternion[0];
  25896. var startIndex = 0;
  25897. var originalAnimation = holder.animations[0];
  25898. var scale = 1;
  25899. if (holder.totalWeight < 1.0) {
  25900. // We need to mix the original value in
  25901. originalValue.decompose(finalScaling, finalQuaternion, finalPosition);
  25902. scale = 1.0 - holder.totalWeight;
  25903. }
  25904. else {
  25905. startIndex = 1;
  25906. // We need to normalize the weights
  25907. normalizer = holder.totalWeight;
  25908. originalAnimation.currentValue.decompose(finalScaling, finalQuaternion, finalPosition);
  25909. scale = originalAnimation.weight / normalizer;
  25910. if (scale == 1) {
  25911. return originalAnimation.currentValue;
  25912. }
  25913. }
  25914. finalScaling.scaleInPlace(scale);
  25915. finalPosition.scaleInPlace(scale);
  25916. finalQuaternion.scaleInPlace(scale);
  25917. for (var animIndex = startIndex; animIndex < holder.animations.length; animIndex++) {
  25918. var runtimeAnimation = holder.animations[animIndex];
  25919. var scale = runtimeAnimation.weight / normalizer;
  25920. var currentPosition = BABYLON.Tmp.Vector3[2];
  25921. var currentScaling = BABYLON.Tmp.Vector3[3];
  25922. var currentQuaternion = BABYLON.Tmp.Quaternion[1];
  25923. runtimeAnimation.currentValue.decompose(currentScaling, currentQuaternion, currentPosition);
  25924. currentScaling.scaleAndAddToRef(scale, finalScaling);
  25925. currentQuaternion.scaleAndAddToRef(scale, finalQuaternion);
  25926. currentPosition.scaleAndAddToRef(scale, finalPosition);
  25927. }
  25928. BABYLON.Matrix.ComposeToRef(finalScaling, finalQuaternion, finalPosition, originalAnimation._workValue);
  25929. return originalAnimation._workValue;
  25930. };
  25931. Scene.prototype._processLateAnimationBindings = function () {
  25932. if (!this._registeredForLateAnimationBindings.length) {
  25933. return;
  25934. }
  25935. for (var index = 0; index < this._registeredForLateAnimationBindings.length; index++) {
  25936. var target = this._registeredForLateAnimationBindings.data[index];
  25937. for (var path in target._lateAnimationHolders) {
  25938. var holder = target._lateAnimationHolders[path];
  25939. var originalAnimation = holder.animations[0];
  25940. var originalValue = originalAnimation.originalValue;
  25941. var finalTarget = originalAnimation.target;
  25942. var matrixDecomposeMode = BABYLON.Animation.AllowMatrixDecomposeForInterpolation && originalValue.m; // ie. data is matrix
  25943. var finalValue = void 0;
  25944. if (matrixDecomposeMode) {
  25945. finalValue = this._processLateAnimationBindingsForMatrices(holder, originalValue);
  25946. }
  25947. else {
  25948. var startIndex = 0;
  25949. var normalizer = 1.0;
  25950. if (holder.totalWeight < 1.0) {
  25951. // We need to mix the original value in
  25952. if (originalValue.scale) {
  25953. finalValue = originalValue.scale(1.0 - holder.totalWeight);
  25954. }
  25955. else {
  25956. finalValue = originalValue * (1.0 - holder.totalWeight);
  25957. }
  25958. }
  25959. else {
  25960. // We need to normalize the weights
  25961. normalizer = holder.totalWeight;
  25962. var scale_1 = originalAnimation.weight / normalizer;
  25963. if (scale_1 !== 1) {
  25964. if (originalAnimation.currentValue.scale) {
  25965. finalValue = originalAnimation.currentValue.scale(scale_1);
  25966. }
  25967. else {
  25968. finalValue = originalAnimation.currentValue * scale_1;
  25969. }
  25970. }
  25971. else {
  25972. finalValue = originalAnimation.currentValue;
  25973. }
  25974. startIndex = 1;
  25975. }
  25976. for (var animIndex = startIndex; animIndex < holder.animations.length; animIndex++) {
  25977. var runtimeAnimation = holder.animations[animIndex];
  25978. var scale = runtimeAnimation.weight / normalizer;
  25979. if (runtimeAnimation.currentValue.scaleAndAddToRef) {
  25980. runtimeAnimation.currentValue.scaleAndAddToRef(scale, finalValue);
  25981. }
  25982. else {
  25983. finalValue += runtimeAnimation.currentValue * scale;
  25984. }
  25985. }
  25986. }
  25987. finalTarget[path] = finalValue;
  25988. }
  25989. target._lateAnimationHolders = {};
  25990. }
  25991. this._registeredForLateAnimationBindings.reset();
  25992. };
  25993. // Matrix
  25994. /** @hidden */
  25995. Scene.prototype._switchToAlternateCameraConfiguration = function (active) {
  25996. this._useAlternateCameraConfiguration = active;
  25997. };
  25998. /**
  25999. * Gets the current view matrix
  26000. * @returns a Matrix
  26001. */
  26002. Scene.prototype.getViewMatrix = function () {
  26003. return this._useAlternateCameraConfiguration ? this._alternateViewMatrix : this._viewMatrix;
  26004. };
  26005. /**
  26006. * Gets the current projection matrix
  26007. * @returns a Matrix
  26008. */
  26009. Scene.prototype.getProjectionMatrix = function () {
  26010. return this._useAlternateCameraConfiguration ? this._alternateProjectionMatrix : this._projectionMatrix;
  26011. };
  26012. /**
  26013. * Gets the current transform matrix
  26014. * @returns a Matrix made of View * Projection
  26015. */
  26016. Scene.prototype.getTransformMatrix = function () {
  26017. return this._useAlternateCameraConfiguration ? this._alternateTransformMatrix : this._transformMatrix;
  26018. };
  26019. /**
  26020. * Sets the current transform matrix
  26021. * @param view defines the View matrix to use
  26022. * @param projection defines the Projection matrix to use
  26023. */
  26024. Scene.prototype.setTransformMatrix = function (view, projection) {
  26025. if (this._viewUpdateFlag === view.updateFlag && this._projectionUpdateFlag === projection.updateFlag) {
  26026. return;
  26027. }
  26028. this._viewUpdateFlag = view.updateFlag;
  26029. this._projectionUpdateFlag = projection.updateFlag;
  26030. this._viewMatrix = view;
  26031. this._projectionMatrix = projection;
  26032. this._viewMatrix.multiplyToRef(this._projectionMatrix, this._transformMatrix);
  26033. // Update frustum
  26034. if (!this._frustumPlanes) {
  26035. this._frustumPlanes = BABYLON.Frustum.GetPlanes(this._transformMatrix);
  26036. }
  26037. else {
  26038. BABYLON.Frustum.GetPlanesToRef(this._transformMatrix, this._frustumPlanes);
  26039. }
  26040. if (this.activeCamera && this.activeCamera._alternateCamera) {
  26041. var otherCamera = this.activeCamera._alternateCamera;
  26042. otherCamera.getViewMatrix().multiplyToRef(otherCamera.getProjectionMatrix(), BABYLON.Tmp.Matrix[0]);
  26043. BABYLON.Frustum.GetRightPlaneToRef(BABYLON.Tmp.Matrix[0], this._frustumPlanes[3]); // Replace right plane by second camera right plane
  26044. }
  26045. if (this._sceneUbo.useUbo) {
  26046. this._sceneUbo.updateMatrix("viewProjection", this._transformMatrix);
  26047. this._sceneUbo.updateMatrix("view", this._viewMatrix);
  26048. this._sceneUbo.update();
  26049. }
  26050. };
  26051. /** @hidden */
  26052. Scene.prototype._setAlternateTransformMatrix = function (view, projection) {
  26053. if (this._alternateViewUpdateFlag === view.updateFlag && this._alternateProjectionUpdateFlag === projection.updateFlag) {
  26054. return;
  26055. }
  26056. this._alternateViewUpdateFlag = view.updateFlag;
  26057. this._alternateProjectionUpdateFlag = projection.updateFlag;
  26058. this._alternateViewMatrix = view;
  26059. this._alternateProjectionMatrix = projection;
  26060. if (!this._alternateTransformMatrix) {
  26061. this._alternateTransformMatrix = BABYLON.Matrix.Zero();
  26062. }
  26063. this._alternateViewMatrix.multiplyToRef(this._alternateProjectionMatrix, this._alternateTransformMatrix);
  26064. if (!this._alternateSceneUbo) {
  26065. this._createAlternateUbo();
  26066. }
  26067. if (this._alternateSceneUbo.useUbo) {
  26068. this._alternateSceneUbo.updateMatrix("viewProjection", this._alternateTransformMatrix);
  26069. this._alternateSceneUbo.updateMatrix("view", this._alternateViewMatrix);
  26070. this._alternateSceneUbo.update();
  26071. }
  26072. };
  26073. /**
  26074. * Gets the uniform buffer used to store scene data
  26075. * @returns a UniformBuffer
  26076. */
  26077. Scene.prototype.getSceneUniformBuffer = function () {
  26078. return this._useAlternateCameraConfiguration ? this._alternateSceneUbo : this._sceneUbo;
  26079. };
  26080. /**
  26081. * Gets an unique (relatively to the current scene) Id
  26082. * @returns an unique number for the scene
  26083. */
  26084. Scene.prototype.getUniqueId = function () {
  26085. var result = Scene._uniqueIdCounter;
  26086. Scene._uniqueIdCounter++;
  26087. return result;
  26088. };
  26089. /**
  26090. * Add a mesh to the list of scene's meshes
  26091. * @param newMesh defines the mesh to add
  26092. */
  26093. Scene.prototype.addMesh = function (newMesh) {
  26094. this.meshes.push(newMesh);
  26095. //notify the collision coordinator
  26096. if (this.collisionCoordinator) {
  26097. this.collisionCoordinator.onMeshAdded(newMesh);
  26098. }
  26099. newMesh._resyncLightSources();
  26100. this.onNewMeshAddedObservable.notifyObservers(newMesh);
  26101. };
  26102. /**
  26103. * Remove a mesh for the list of scene's meshes
  26104. * @param toRemove defines the mesh to remove
  26105. * @returns the index where the mesh was in the mesh list
  26106. */
  26107. Scene.prototype.removeMesh = function (toRemove) {
  26108. var index = this.meshes.indexOf(toRemove);
  26109. if (index !== -1) {
  26110. // Remove from the scene if mesh found
  26111. this.meshes.splice(index, 1);
  26112. }
  26113. this.onMeshRemovedObservable.notifyObservers(toRemove);
  26114. return index;
  26115. };
  26116. /**
  26117. * Add a transform node to the list of scene's transform nodes
  26118. * @param newTransformNode defines the transform node to add
  26119. */
  26120. Scene.prototype.addTransformNode = function (newTransformNode) {
  26121. this.transformNodes.push(newTransformNode);
  26122. this.onNewTransformNodeAddedObservable.notifyObservers(newTransformNode);
  26123. };
  26124. /**
  26125. * Remove a transform node for the list of scene's transform nodes
  26126. * @param toRemove defines the transform node to remove
  26127. * @returns the index where the transform node was in the transform node list
  26128. */
  26129. Scene.prototype.removeTransformNode = function (toRemove) {
  26130. var index = this.transformNodes.indexOf(toRemove);
  26131. if (index !== -1) {
  26132. // Remove from the scene if found
  26133. this.transformNodes.splice(index, 1);
  26134. }
  26135. this.onTransformNodeRemovedObservable.notifyObservers(toRemove);
  26136. return index;
  26137. };
  26138. /**
  26139. * Remove a skeleton for the list of scene's skeletons
  26140. * @param toRemove defines the skeleton to remove
  26141. * @returns the index where the skeleton was in the skeleton list
  26142. */
  26143. Scene.prototype.removeSkeleton = function (toRemove) {
  26144. var index = this.skeletons.indexOf(toRemove);
  26145. if (index !== -1) {
  26146. // Remove from the scene if found
  26147. this.skeletons.splice(index, 1);
  26148. }
  26149. return index;
  26150. };
  26151. /**
  26152. * Remove a morph target for the list of scene's morph targets
  26153. * @param toRemove defines the morph target to remove
  26154. * @returns the index where the morph target was in the morph target list
  26155. */
  26156. Scene.prototype.removeMorphTargetManager = function (toRemove) {
  26157. var index = this.morphTargetManagers.indexOf(toRemove);
  26158. if (index !== -1) {
  26159. // Remove from the scene if found
  26160. this.morphTargetManagers.splice(index, 1);
  26161. }
  26162. return index;
  26163. };
  26164. /**
  26165. * Remove a light for the list of scene's lights
  26166. * @param toRemove defines the light to remove
  26167. * @returns the index where the light was in the light list
  26168. */
  26169. Scene.prototype.removeLight = function (toRemove) {
  26170. var index = this.lights.indexOf(toRemove);
  26171. if (index !== -1) {
  26172. // Remove from meshes
  26173. for (var _i = 0, _a = this.meshes; _i < _a.length; _i++) {
  26174. var mesh = _a[_i];
  26175. mesh._removeLightSource(toRemove);
  26176. }
  26177. // Remove from the scene if mesh found
  26178. this.lights.splice(index, 1);
  26179. this.sortLightsByPriority();
  26180. }
  26181. this.onLightRemovedObservable.notifyObservers(toRemove);
  26182. return index;
  26183. };
  26184. /**
  26185. * Remove a camera for the list of scene's cameras
  26186. * @param toRemove defines the camera to remove
  26187. * @returns the index where the camera was in the camera list
  26188. */
  26189. Scene.prototype.removeCamera = function (toRemove) {
  26190. var index = this.cameras.indexOf(toRemove);
  26191. if (index !== -1) {
  26192. // Remove from the scene if mesh found
  26193. this.cameras.splice(index, 1);
  26194. }
  26195. // Remove from activeCameras
  26196. var index2 = this.activeCameras.indexOf(toRemove);
  26197. if (index2 !== -1) {
  26198. // Remove from the scene if mesh found
  26199. this.activeCameras.splice(index2, 1);
  26200. }
  26201. // Reset the activeCamera
  26202. if (this.activeCamera === toRemove) {
  26203. if (this.cameras.length > 0) {
  26204. this.activeCamera = this.cameras[0];
  26205. }
  26206. else {
  26207. this.activeCamera = null;
  26208. }
  26209. }
  26210. this.onCameraRemovedObservable.notifyObservers(toRemove);
  26211. return index;
  26212. };
  26213. /**
  26214. * Remove a particle system for the list of scene's particle systems
  26215. * @param toRemove defines the particle system to remove
  26216. * @returns the index where the particle system was in the particle system list
  26217. */
  26218. Scene.prototype.removeParticleSystem = function (toRemove) {
  26219. var index = this.particleSystems.indexOf(toRemove);
  26220. if (index !== -1) {
  26221. this.particleSystems.splice(index, 1);
  26222. }
  26223. return index;
  26224. };
  26225. /**
  26226. * Remove a animation for the list of scene's animations
  26227. * @param toRemove defines the animation to remove
  26228. * @returns the index where the animation was in the animation list
  26229. */
  26230. Scene.prototype.removeAnimation = function (toRemove) {
  26231. var index = this.animations.indexOf(toRemove);
  26232. if (index !== -1) {
  26233. this.animations.splice(index, 1);
  26234. }
  26235. return index;
  26236. };
  26237. /**
  26238. * Removes the given animation group from this scene.
  26239. * @param toRemove The animation group to remove
  26240. * @returns The index of the removed animation group
  26241. */
  26242. Scene.prototype.removeAnimationGroup = function (toRemove) {
  26243. var index = this.animationGroups.indexOf(toRemove);
  26244. if (index !== -1) {
  26245. this.animationGroups.splice(index, 1);
  26246. }
  26247. return index;
  26248. };
  26249. /**
  26250. * Removes the given multi-material from this scene.
  26251. * @param toRemove The multi-material to remove
  26252. * @returns The index of the removed multi-material
  26253. */
  26254. Scene.prototype.removeMultiMaterial = function (toRemove) {
  26255. var index = this.multiMaterials.indexOf(toRemove);
  26256. if (index !== -1) {
  26257. this.multiMaterials.splice(index, 1);
  26258. }
  26259. return index;
  26260. };
  26261. /**
  26262. * Removes the given material from this scene.
  26263. * @param toRemove The material to remove
  26264. * @returns The index of the removed material
  26265. */
  26266. Scene.prototype.removeMaterial = function (toRemove) {
  26267. var index = this.materials.indexOf(toRemove);
  26268. if (index !== -1) {
  26269. this.materials.splice(index, 1);
  26270. }
  26271. return index;
  26272. };
  26273. /**
  26274. * Removes the given lens flare system from this scene.
  26275. * @param toRemove The lens flare system to remove
  26276. * @returns The index of the removed lens flare system
  26277. */
  26278. Scene.prototype.removeLensFlareSystem = function (toRemove) {
  26279. var index = this.lensFlareSystems.indexOf(toRemove);
  26280. if (index !== -1) {
  26281. this.lensFlareSystems.splice(index, 1);
  26282. }
  26283. return index;
  26284. };
  26285. /**
  26286. * Removes the given action manager from this scene.
  26287. * @param toRemove The action manager to remove
  26288. * @returns The index of the removed action manager
  26289. */
  26290. Scene.prototype.removeActionManager = function (toRemove) {
  26291. var index = this._actionManagers.indexOf(toRemove);
  26292. if (index !== -1) {
  26293. this._actionManagers.splice(index, 1);
  26294. }
  26295. return index;
  26296. };
  26297. /**
  26298. * Removes the given effect layer from this scene.
  26299. * @param toRemove defines the effect layer to remove
  26300. * @returns the index of the removed effect layer
  26301. */
  26302. Scene.prototype.removeEffectLayer = function (toRemove) {
  26303. var index = this.effectLayers.indexOf(toRemove);
  26304. if (index !== -1) {
  26305. this.effectLayers.splice(index, 1);
  26306. }
  26307. return index;
  26308. };
  26309. /**
  26310. * Removes the given texture from this scene.
  26311. * @param toRemove The texture to remove
  26312. * @returns The index of the removed texture
  26313. */
  26314. Scene.prototype.removeTexture = function (toRemove) {
  26315. var index = this.textures.indexOf(toRemove);
  26316. if (index !== -1) {
  26317. this.textures.splice(index, 1);
  26318. }
  26319. return index;
  26320. };
  26321. /**
  26322. * Adds the given light to this scene
  26323. * @param newLight The light to add
  26324. */
  26325. Scene.prototype.addLight = function (newLight) {
  26326. this.lights.push(newLight);
  26327. this.sortLightsByPriority();
  26328. // Add light to all meshes (To support if the light is removed and then readded)
  26329. for (var _i = 0, _a = this.meshes; _i < _a.length; _i++) {
  26330. var mesh = _a[_i];
  26331. if (mesh._lightSources.indexOf(newLight) === -1) {
  26332. mesh._lightSources.push(newLight);
  26333. mesh._resyncLightSources();
  26334. }
  26335. }
  26336. this.onNewLightAddedObservable.notifyObservers(newLight);
  26337. };
  26338. /**
  26339. * Sorts the list list based on light priorities
  26340. */
  26341. Scene.prototype.sortLightsByPriority = function () {
  26342. if (this.requireLightSorting) {
  26343. this.lights.sort(BABYLON.Light.CompareLightsPriority);
  26344. }
  26345. };
  26346. /**
  26347. * Adds the given camera to this scene
  26348. * @param newCamera The camera to add
  26349. */
  26350. Scene.prototype.addCamera = function (newCamera) {
  26351. this.cameras.push(newCamera);
  26352. this.onNewCameraAddedObservable.notifyObservers(newCamera);
  26353. };
  26354. /**
  26355. * Adds the given skeleton to this scene
  26356. * @param newSkeleton The skeleton to add
  26357. */
  26358. Scene.prototype.addSkeleton = function (newSkeleton) {
  26359. this.skeletons.push(newSkeleton);
  26360. };
  26361. /**
  26362. * Adds the given particle system to this scene
  26363. * @param newParticleSystem The particle system to add
  26364. */
  26365. Scene.prototype.addParticleSystem = function (newParticleSystem) {
  26366. this.particleSystems.push(newParticleSystem);
  26367. };
  26368. /**
  26369. * Adds the given animation to this scene
  26370. * @param newAnimation The animation to add
  26371. */
  26372. Scene.prototype.addAnimation = function (newAnimation) {
  26373. this.animations.push(newAnimation);
  26374. };
  26375. /**
  26376. * Adds the given animation group to this scene.
  26377. * @param newAnimationGroup The animation group to add
  26378. */
  26379. Scene.prototype.addAnimationGroup = function (newAnimationGroup) {
  26380. this.animationGroups.push(newAnimationGroup);
  26381. };
  26382. /**
  26383. * Adds the given multi-material to this scene
  26384. * @param newMultiMaterial The multi-material to add
  26385. */
  26386. Scene.prototype.addMultiMaterial = function (newMultiMaterial) {
  26387. this.multiMaterials.push(newMultiMaterial);
  26388. };
  26389. /**
  26390. * Adds the given material to this scene
  26391. * @param newMaterial The material to add
  26392. */
  26393. Scene.prototype.addMaterial = function (newMaterial) {
  26394. this.materials.push(newMaterial);
  26395. };
  26396. /**
  26397. * Adds the given morph target to this scene
  26398. * @param newMorphTargetManager The morph target to add
  26399. */
  26400. Scene.prototype.addMorphTargetManager = function (newMorphTargetManager) {
  26401. this.morphTargetManagers.push(newMorphTargetManager);
  26402. };
  26403. /**
  26404. * Adds the given geometry to this scene
  26405. * @param newGeometry The geometry to add
  26406. */
  26407. Scene.prototype.addGeometry = function (newGeometry) {
  26408. this._geometries.push(newGeometry);
  26409. };
  26410. /**
  26411. * Adds the given lens flare system to this scene
  26412. * @param newLensFlareSystem The lens flare system to add
  26413. */
  26414. Scene.prototype.addLensFlareSystem = function (newLensFlareSystem) {
  26415. this.lensFlareSystems.push(newLensFlareSystem);
  26416. };
  26417. /**
  26418. * Adds the given effect layer to this scene
  26419. * @param newEffectLayer defines the effect layer to add
  26420. */
  26421. Scene.prototype.addEffectLayer = function (newEffectLayer) {
  26422. this.effectLayers.push(newEffectLayer);
  26423. };
  26424. /**
  26425. * Adds the given action manager to this scene
  26426. * @param newActionManager The action manager to add
  26427. */
  26428. Scene.prototype.addActionManager = function (newActionManager) {
  26429. this._actionManagers.push(newActionManager);
  26430. };
  26431. /**
  26432. * Adds the given texture to this scene.
  26433. * @param newTexture The texture to add
  26434. */
  26435. Scene.prototype.addTexture = function (newTexture) {
  26436. this.textures.push(newTexture);
  26437. };
  26438. /**
  26439. * Switch active camera
  26440. * @param newCamera defines the new active camera
  26441. * @param attachControl defines if attachControl must be called for the new active camera (default: true)
  26442. */
  26443. Scene.prototype.switchActiveCamera = function (newCamera, attachControl) {
  26444. if (attachControl === void 0) { attachControl = true; }
  26445. var canvas = this._engine.getRenderingCanvas();
  26446. if (!canvas) {
  26447. return;
  26448. }
  26449. if (this.activeCamera) {
  26450. this.activeCamera.detachControl(canvas);
  26451. }
  26452. this.activeCamera = newCamera;
  26453. if (attachControl) {
  26454. newCamera.attachControl(canvas);
  26455. }
  26456. };
  26457. /**
  26458. * sets the active camera of the scene using its ID
  26459. * @param id defines the camera's ID
  26460. * @return the new active camera or null if none found.
  26461. */
  26462. Scene.prototype.setActiveCameraByID = function (id) {
  26463. var camera = this.getCameraByID(id);
  26464. if (camera) {
  26465. this.activeCamera = camera;
  26466. return camera;
  26467. }
  26468. return null;
  26469. };
  26470. /**
  26471. * sets the active camera of the scene using its name
  26472. * @param name defines the camera's name
  26473. * @returns the new active camera or null if none found.
  26474. */
  26475. Scene.prototype.setActiveCameraByName = function (name) {
  26476. var camera = this.getCameraByName(name);
  26477. if (camera) {
  26478. this.activeCamera = camera;
  26479. return camera;
  26480. }
  26481. return null;
  26482. };
  26483. /**
  26484. * get an animation group using its name
  26485. * @param name defines the material's name
  26486. * @return the animation group or null if none found.
  26487. */
  26488. Scene.prototype.getAnimationGroupByName = function (name) {
  26489. for (var index = 0; index < this.animationGroups.length; index++) {
  26490. if (this.animationGroups[index].name === name) {
  26491. return this.animationGroups[index];
  26492. }
  26493. }
  26494. return null;
  26495. };
  26496. /**
  26497. * get a material using its id
  26498. * @param id defines the material's ID
  26499. * @return the material or null if none found.
  26500. */
  26501. Scene.prototype.getMaterialByID = function (id) {
  26502. for (var index = 0; index < this.materials.length; index++) {
  26503. if (this.materials[index].id === id) {
  26504. return this.materials[index];
  26505. }
  26506. }
  26507. return null;
  26508. };
  26509. /**
  26510. * Gets a material using its name
  26511. * @param name defines the material's name
  26512. * @return the material or null if none found.
  26513. */
  26514. Scene.prototype.getMaterialByName = function (name) {
  26515. for (var index = 0; index < this.materials.length; index++) {
  26516. if (this.materials[index].name === name) {
  26517. return this.materials[index];
  26518. }
  26519. }
  26520. return null;
  26521. };
  26522. /**
  26523. * Gets a lens flare system using its name
  26524. * @param name defines the name to look for
  26525. * @returns the lens flare system or null if not found
  26526. */
  26527. Scene.prototype.getLensFlareSystemByName = function (name) {
  26528. for (var index = 0; index < this.lensFlareSystems.length; index++) {
  26529. if (this.lensFlareSystems[index].name === name) {
  26530. return this.lensFlareSystems[index];
  26531. }
  26532. }
  26533. return null;
  26534. };
  26535. /**
  26536. * Gets a lens flare system using its id
  26537. * @param id defines the id to look for
  26538. * @returns the lens flare system or null if not found
  26539. */
  26540. Scene.prototype.getLensFlareSystemByID = function (id) {
  26541. for (var index = 0; index < this.lensFlareSystems.length; index++) {
  26542. if (this.lensFlareSystems[index].id === id) {
  26543. return this.lensFlareSystems[index];
  26544. }
  26545. }
  26546. return null;
  26547. };
  26548. /**
  26549. * Gets a camera using its id
  26550. * @param id defines the id to look for
  26551. * @returns the camera or null if not found
  26552. */
  26553. Scene.prototype.getCameraByID = function (id) {
  26554. for (var index = 0; index < this.cameras.length; index++) {
  26555. if (this.cameras[index].id === id) {
  26556. return this.cameras[index];
  26557. }
  26558. }
  26559. return null;
  26560. };
  26561. /**
  26562. * Gets a camera using its unique id
  26563. * @param uniqueId defines the unique id to look for
  26564. * @returns the camera or null if not found
  26565. */
  26566. Scene.prototype.getCameraByUniqueID = function (uniqueId) {
  26567. for (var index = 0; index < this.cameras.length; index++) {
  26568. if (this.cameras[index].uniqueId === uniqueId) {
  26569. return this.cameras[index];
  26570. }
  26571. }
  26572. return null;
  26573. };
  26574. /**
  26575. * Gets a camera using its name
  26576. * @param name defines the camera's name
  26577. * @return the camera or null if none found.
  26578. */
  26579. Scene.prototype.getCameraByName = function (name) {
  26580. for (var index = 0; index < this.cameras.length; index++) {
  26581. if (this.cameras[index].name === name) {
  26582. return this.cameras[index];
  26583. }
  26584. }
  26585. return null;
  26586. };
  26587. /**
  26588. * Gets a bone using its id
  26589. * @param id defines the bone's id
  26590. * @return the bone or null if not found
  26591. */
  26592. Scene.prototype.getBoneByID = function (id) {
  26593. for (var skeletonIndex = 0; skeletonIndex < this.skeletons.length; skeletonIndex++) {
  26594. var skeleton = this.skeletons[skeletonIndex];
  26595. for (var boneIndex = 0; boneIndex < skeleton.bones.length; boneIndex++) {
  26596. if (skeleton.bones[boneIndex].id === id) {
  26597. return skeleton.bones[boneIndex];
  26598. }
  26599. }
  26600. }
  26601. return null;
  26602. };
  26603. /**
  26604. * Gets a bone using its id
  26605. * @param name defines the bone's name
  26606. * @return the bone or null if not found
  26607. */
  26608. Scene.prototype.getBoneByName = function (name) {
  26609. for (var skeletonIndex = 0; skeletonIndex < this.skeletons.length; skeletonIndex++) {
  26610. var skeleton = this.skeletons[skeletonIndex];
  26611. for (var boneIndex = 0; boneIndex < skeleton.bones.length; boneIndex++) {
  26612. if (skeleton.bones[boneIndex].name === name) {
  26613. return skeleton.bones[boneIndex];
  26614. }
  26615. }
  26616. }
  26617. return null;
  26618. };
  26619. /**
  26620. * Gets a light node using its name
  26621. * @param name defines the the light's name
  26622. * @return the light or null if none found.
  26623. */
  26624. Scene.prototype.getLightByName = function (name) {
  26625. for (var index = 0; index < this.lights.length; index++) {
  26626. if (this.lights[index].name === name) {
  26627. return this.lights[index];
  26628. }
  26629. }
  26630. return null;
  26631. };
  26632. /**
  26633. * Gets a light node using its id
  26634. * @param id defines the light's id
  26635. * @return the light or null if none found.
  26636. */
  26637. Scene.prototype.getLightByID = function (id) {
  26638. for (var index = 0; index < this.lights.length; index++) {
  26639. if (this.lights[index].id === id) {
  26640. return this.lights[index];
  26641. }
  26642. }
  26643. return null;
  26644. };
  26645. /**
  26646. * Gets a light node using its scene-generated unique ID
  26647. * @param uniqueId defines the light's unique id
  26648. * @return the light or null if none found.
  26649. */
  26650. Scene.prototype.getLightByUniqueID = function (uniqueId) {
  26651. for (var index = 0; index < this.lights.length; index++) {
  26652. if (this.lights[index].uniqueId === uniqueId) {
  26653. return this.lights[index];
  26654. }
  26655. }
  26656. return null;
  26657. };
  26658. /**
  26659. * Gets a particle system by id
  26660. * @param id defines the particle system id
  26661. * @return the corresponding system or null if none found
  26662. */
  26663. Scene.prototype.getParticleSystemByID = function (id) {
  26664. for (var index = 0; index < this.particleSystems.length; index++) {
  26665. if (this.particleSystems[index].id === id) {
  26666. return this.particleSystems[index];
  26667. }
  26668. }
  26669. return null;
  26670. };
  26671. /**
  26672. * Gets a geometry using its ID
  26673. * @param id defines the geometry's id
  26674. * @return the geometry or null if none found.
  26675. */
  26676. Scene.prototype.getGeometryByID = function (id) {
  26677. for (var index = 0; index < this._geometries.length; index++) {
  26678. if (this._geometries[index].id === id) {
  26679. return this._geometries[index];
  26680. }
  26681. }
  26682. return null;
  26683. };
  26684. /**
  26685. * Add a new geometry to this scene
  26686. * @param geometry defines the geometry to be added to the scene.
  26687. * @param force defines if the geometry must be pushed even if a geometry with this id already exists
  26688. * @return a boolean defining if the geometry was added or not
  26689. */
  26690. Scene.prototype.pushGeometry = function (geometry, force) {
  26691. if (!force && this.getGeometryByID(geometry.id)) {
  26692. return false;
  26693. }
  26694. this._geometries.push(geometry);
  26695. //notify the collision coordinator
  26696. if (this.collisionCoordinator) {
  26697. this.collisionCoordinator.onGeometryAdded(geometry);
  26698. }
  26699. this.onNewGeometryAddedObservable.notifyObservers(geometry);
  26700. return true;
  26701. };
  26702. /**
  26703. * Removes an existing geometry
  26704. * @param geometry defines the geometry to be removed from the scene
  26705. * @return a boolean defining if the geometry was removed or not
  26706. */
  26707. Scene.prototype.removeGeometry = function (geometry) {
  26708. var index = this._geometries.indexOf(geometry);
  26709. if (index > -1) {
  26710. this._geometries.splice(index, 1);
  26711. //notify the collision coordinator
  26712. if (this.collisionCoordinator) {
  26713. this.collisionCoordinator.onGeometryDeleted(geometry);
  26714. }
  26715. this.onGeometryRemovedObservable.notifyObservers(geometry);
  26716. return true;
  26717. }
  26718. return false;
  26719. };
  26720. /**
  26721. * Gets the list of geometries attached to the scene
  26722. * @returns an array of Geometry
  26723. */
  26724. Scene.prototype.getGeometries = function () {
  26725. return this._geometries;
  26726. };
  26727. /**
  26728. * Gets the first added mesh found of a given ID
  26729. * @param id defines the id to search for
  26730. * @return the mesh found or null if not found at all
  26731. */
  26732. Scene.prototype.getMeshByID = function (id) {
  26733. for (var index = 0; index < this.meshes.length; index++) {
  26734. if (this.meshes[index].id === id) {
  26735. return this.meshes[index];
  26736. }
  26737. }
  26738. return null;
  26739. };
  26740. /**
  26741. * Gets a list of meshes using their id
  26742. * @param id defines the id to search for
  26743. * @returns a list of meshes
  26744. */
  26745. Scene.prototype.getMeshesByID = function (id) {
  26746. return this.meshes.filter(function (m) {
  26747. return m.id === id;
  26748. });
  26749. };
  26750. /**
  26751. * Gets the first added transform node found of a given ID
  26752. * @param id defines the id to search for
  26753. * @return the found transform node or null if not found at all.
  26754. */
  26755. Scene.prototype.getTransformNodeByID = function (id) {
  26756. for (var index = 0; index < this.transformNodes.length; index++) {
  26757. if (this.transformNodes[index].id === id) {
  26758. return this.transformNodes[index];
  26759. }
  26760. }
  26761. return null;
  26762. };
  26763. /**
  26764. * Gets a list of transform nodes using their id
  26765. * @param id defines the id to search for
  26766. * @returns a list of transform nodes
  26767. */
  26768. Scene.prototype.getTransformNodesByID = function (id) {
  26769. return this.transformNodes.filter(function (m) {
  26770. return m.id === id;
  26771. });
  26772. };
  26773. /**
  26774. * Gets a mesh with its auto-generated unique id
  26775. * @param uniqueId defines the unique id to search for
  26776. * @return the found mesh or null if not found at all.
  26777. */
  26778. Scene.prototype.getMeshByUniqueID = function (uniqueId) {
  26779. for (var index = 0; index < this.meshes.length; index++) {
  26780. if (this.meshes[index].uniqueId === uniqueId) {
  26781. return this.meshes[index];
  26782. }
  26783. }
  26784. return null;
  26785. };
  26786. /**
  26787. * Gets a the last added mesh using a given id
  26788. * @param id defines the id to search for
  26789. * @return the found mesh or null if not found at all.
  26790. */
  26791. Scene.prototype.getLastMeshByID = function (id) {
  26792. for (var index = this.meshes.length - 1; index >= 0; index--) {
  26793. if (this.meshes[index].id === id) {
  26794. return this.meshes[index];
  26795. }
  26796. }
  26797. return null;
  26798. };
  26799. /**
  26800. * Gets a the last added node (Mesh, Camera, Light) using a given id
  26801. * @param id defines the id to search for
  26802. * @return the found node or null if not found at all
  26803. */
  26804. Scene.prototype.getLastEntryByID = function (id) {
  26805. var index;
  26806. for (index = this.meshes.length - 1; index >= 0; index--) {
  26807. if (this.meshes[index].id === id) {
  26808. return this.meshes[index];
  26809. }
  26810. }
  26811. for (index = this.transformNodes.length - 1; index >= 0; index--) {
  26812. if (this.transformNodes[index].id === id) {
  26813. return this.transformNodes[index];
  26814. }
  26815. }
  26816. for (index = this.cameras.length - 1; index >= 0; index--) {
  26817. if (this.cameras[index].id === id) {
  26818. return this.cameras[index];
  26819. }
  26820. }
  26821. for (index = this.lights.length - 1; index >= 0; index--) {
  26822. if (this.lights[index].id === id) {
  26823. return this.lights[index];
  26824. }
  26825. }
  26826. return null;
  26827. };
  26828. /**
  26829. * Gets a node (Mesh, Camera, Light) using a given id
  26830. * @param id defines the id to search for
  26831. * @return the found node or null if not found at all
  26832. */
  26833. Scene.prototype.getNodeByID = function (id) {
  26834. var mesh = this.getMeshByID(id);
  26835. if (mesh) {
  26836. return mesh;
  26837. }
  26838. var light = this.getLightByID(id);
  26839. if (light) {
  26840. return light;
  26841. }
  26842. var camera = this.getCameraByID(id);
  26843. if (camera) {
  26844. return camera;
  26845. }
  26846. var bone = this.getBoneByID(id);
  26847. return bone;
  26848. };
  26849. /**
  26850. * Gets a node (Mesh, Camera, Light) using a given name
  26851. * @param name defines the name to search for
  26852. * @return the found node or null if not found at all.
  26853. */
  26854. Scene.prototype.getNodeByName = function (name) {
  26855. var mesh = this.getMeshByName(name);
  26856. if (mesh) {
  26857. return mesh;
  26858. }
  26859. var light = this.getLightByName(name);
  26860. if (light) {
  26861. return light;
  26862. }
  26863. var camera = this.getCameraByName(name);
  26864. if (camera) {
  26865. return camera;
  26866. }
  26867. var bone = this.getBoneByName(name);
  26868. return bone;
  26869. };
  26870. /**
  26871. * Gets a mesh using a given name
  26872. * @param name defines the name to search for
  26873. * @return the found mesh or null if not found at all.
  26874. */
  26875. Scene.prototype.getMeshByName = function (name) {
  26876. for (var index = 0; index < this.meshes.length; index++) {
  26877. if (this.meshes[index].name === name) {
  26878. return this.meshes[index];
  26879. }
  26880. }
  26881. return null;
  26882. };
  26883. /**
  26884. * Gets a transform node using a given name
  26885. * @param name defines the name to search for
  26886. * @return the found transform node or null if not found at all.
  26887. */
  26888. Scene.prototype.getTransformNodeByName = function (name) {
  26889. for (var index = 0; index < this.transformNodes.length; index++) {
  26890. if (this.transformNodes[index].name === name) {
  26891. return this.transformNodes[index];
  26892. }
  26893. }
  26894. return null;
  26895. };
  26896. /**
  26897. * Gets a sound using a given name
  26898. * @param name defines the name to search for
  26899. * @return the found sound or null if not found at all.
  26900. */
  26901. Scene.prototype.getSoundByName = function (name) {
  26902. var index;
  26903. if (BABYLON.AudioEngine) {
  26904. for (index = 0; index < this.mainSoundTrack.soundCollection.length; index++) {
  26905. if (this.mainSoundTrack.soundCollection[index].name === name) {
  26906. return this.mainSoundTrack.soundCollection[index];
  26907. }
  26908. }
  26909. for (var sdIndex = 0; sdIndex < this.soundTracks.length; sdIndex++) {
  26910. for (index = 0; index < this.soundTracks[sdIndex].soundCollection.length; index++) {
  26911. if (this.soundTracks[sdIndex].soundCollection[index].name === name) {
  26912. return this.soundTracks[sdIndex].soundCollection[index];
  26913. }
  26914. }
  26915. }
  26916. }
  26917. return null;
  26918. };
  26919. /**
  26920. * Gets a skeleton using a given id (if many are found, this function will pick the last one)
  26921. * @param id defines the id to search for
  26922. * @return the found skeleton or null if not found at all.
  26923. */
  26924. Scene.prototype.getLastSkeletonByID = function (id) {
  26925. for (var index = this.skeletons.length - 1; index >= 0; index--) {
  26926. if (this.skeletons[index].id === id) {
  26927. return this.skeletons[index];
  26928. }
  26929. }
  26930. return null;
  26931. };
  26932. /**
  26933. * Gets a skeleton using a given id (if many are found, this function will pick the first one)
  26934. * @param id defines the id to search for
  26935. * @return the found skeleton or null if not found at all.
  26936. */
  26937. Scene.prototype.getSkeletonById = function (id) {
  26938. for (var index = 0; index < this.skeletons.length; index++) {
  26939. if (this.skeletons[index].id === id) {
  26940. return this.skeletons[index];
  26941. }
  26942. }
  26943. return null;
  26944. };
  26945. /**
  26946. * Gets a skeleton using a given name
  26947. * @param name defines the name to search for
  26948. * @return the found skeleton or null if not found at all.
  26949. */
  26950. Scene.prototype.getSkeletonByName = function (name) {
  26951. for (var index = 0; index < this.skeletons.length; index++) {
  26952. if (this.skeletons[index].name === name) {
  26953. return this.skeletons[index];
  26954. }
  26955. }
  26956. return null;
  26957. };
  26958. /**
  26959. * Gets a morph target manager using a given id (if many are found, this function will pick the last one)
  26960. * @param id defines the id to search for
  26961. * @return the found morph target manager or null if not found at all.
  26962. */
  26963. Scene.prototype.getMorphTargetManagerById = function (id) {
  26964. for (var index = 0; index < this.morphTargetManagers.length; index++) {
  26965. if (this.morphTargetManagers[index].uniqueId === id) {
  26966. return this.morphTargetManagers[index];
  26967. }
  26968. }
  26969. return null;
  26970. };
  26971. /**
  26972. * Gets a boolean indicating if the given mesh is active
  26973. * @param mesh defines the mesh to look for
  26974. * @returns true if the mesh is in the active list
  26975. */
  26976. Scene.prototype.isActiveMesh = function (mesh) {
  26977. return (this._activeMeshes.indexOf(mesh) !== -1);
  26978. };
  26979. /**
  26980. * Return a the first highlight layer of the scene with a given name.
  26981. * @param name The name of the highlight layer to look for.
  26982. * @return The highlight layer if found otherwise null.
  26983. */
  26984. Scene.prototype.getHighlightLayerByName = function (name) {
  26985. for (var index = 0; index < this.effectLayers.length; index++) {
  26986. if (this.effectLayers[index].name === name && this.effectLayers[index].getEffectName() === BABYLON.HighlightLayer.EffectName) {
  26987. return this.effectLayers[index];
  26988. }
  26989. }
  26990. return null;
  26991. };
  26992. /**
  26993. * Return a the first highlight layer of the scene with a given name.
  26994. * @param name The name of the highlight layer to look for.
  26995. * @return The highlight layer if found otherwise null.
  26996. */
  26997. Scene.prototype.getGlowLayerByName = function (name) {
  26998. for (var index = 0; index < this.effectLayers.length; index++) {
  26999. if (this.effectLayers[index].name === name && this.effectLayers[index].getEffectName() === BABYLON.GlowLayer.EffectName) {
  27000. return this.effectLayers[index];
  27001. }
  27002. }
  27003. return null;
  27004. };
  27005. Object.defineProperty(Scene.prototype, "uid", {
  27006. /**
  27007. * Return a unique id as a string which can serve as an identifier for the scene
  27008. */
  27009. get: function () {
  27010. if (!this._uid) {
  27011. this._uid = BABYLON.Tools.RandomId();
  27012. }
  27013. return this._uid;
  27014. },
  27015. enumerable: true,
  27016. configurable: true
  27017. });
  27018. /**
  27019. * Add an externaly attached data from its key.
  27020. * This method call will fail and return false, if such key already exists.
  27021. * If you don't care and just want to get the data no matter what, use the more convenient getOrAddExternalDataWithFactory() method.
  27022. * @param key the unique key that identifies the data
  27023. * @param data the data object to associate to the key for this Engine instance
  27024. * @return true if no such key were already present and the data was added successfully, false otherwise
  27025. */
  27026. Scene.prototype.addExternalData = function (key, data) {
  27027. if (!this._externalData) {
  27028. this._externalData = new BABYLON.StringDictionary();
  27029. }
  27030. return this._externalData.add(key, data);
  27031. };
  27032. /**
  27033. * Get an externaly attached data from its key
  27034. * @param key the unique key that identifies the data
  27035. * @return the associated data, if present (can be null), or undefined if not present
  27036. */
  27037. Scene.prototype.getExternalData = function (key) {
  27038. if (!this._externalData) {
  27039. return null;
  27040. }
  27041. return this._externalData.get(key);
  27042. };
  27043. /**
  27044. * Get an externaly attached data from its key, create it using a factory if it's not already present
  27045. * @param key the unique key that identifies the data
  27046. * @param factory the factory that will be called to create the instance if and only if it doesn't exists
  27047. * @return the associated data, can be null if the factory returned null.
  27048. */
  27049. Scene.prototype.getOrAddExternalDataWithFactory = function (key, factory) {
  27050. if (!this._externalData) {
  27051. this._externalData = new BABYLON.StringDictionary();
  27052. }
  27053. return this._externalData.getOrAddWithFactory(key, factory);
  27054. };
  27055. /**
  27056. * Remove an externaly attached data from the Engine instance
  27057. * @param key the unique key that identifies the data
  27058. * @return true if the data was successfully removed, false if it doesn't exist
  27059. */
  27060. Scene.prototype.removeExternalData = function (key) {
  27061. return this._externalData.remove(key);
  27062. };
  27063. Scene.prototype._evaluateSubMesh = function (subMesh, mesh) {
  27064. if (this.dispatchAllSubMeshesOfActiveMeshes || mesh.alwaysSelectAsActiveMesh || mesh.subMeshes.length === 1 || subMesh.isInFrustum(this._frustumPlanes)) {
  27065. if (mesh.showSubMeshesBoundingBox) {
  27066. var boundingInfo = subMesh.getBoundingInfo();
  27067. if (boundingInfo !== null && boundingInfo !== undefined) {
  27068. this.getBoundingBoxRenderer().renderList.push(boundingInfo.boundingBox);
  27069. }
  27070. }
  27071. var material = subMesh.getMaterial();
  27072. if (material !== null && material !== undefined) {
  27073. // Render targets
  27074. if (material.getRenderTargetTextures !== undefined) {
  27075. if (this._processedMaterials.indexOf(material) === -1) {
  27076. this._processedMaterials.push(material);
  27077. this._renderTargets.concatWithNoDuplicate(material.getRenderTargetTextures());
  27078. }
  27079. }
  27080. // Dispatch
  27081. this._activeIndices.addCount(subMesh.indexCount, false);
  27082. this._renderingManager.dispatch(subMesh, mesh, material);
  27083. }
  27084. }
  27085. };
  27086. /**
  27087. * Clear the processed materials smart array preventing retention point in material dispose.
  27088. */
  27089. Scene.prototype.freeProcessedMaterials = function () {
  27090. this._processedMaterials.dispose();
  27091. };
  27092. /**
  27093. * Clear the active meshes smart array preventing retention point in mesh dispose.
  27094. */
  27095. Scene.prototype.freeActiveMeshes = function () {
  27096. this._activeMeshes.dispose();
  27097. if (this.activeCamera && this.activeCamera._activeMeshes) {
  27098. this.activeCamera._activeMeshes.dispose();
  27099. }
  27100. if (this.activeCameras) {
  27101. for (var i = 0; i < this.activeCameras.length; i++) {
  27102. var activeCamera = this.activeCameras[i];
  27103. if (activeCamera && activeCamera._activeMeshes) {
  27104. activeCamera._activeMeshes.dispose();
  27105. }
  27106. }
  27107. }
  27108. };
  27109. /**
  27110. * Clear the info related to rendering groups preventing retention points during dispose.
  27111. */
  27112. Scene.prototype.freeRenderingGroups = function () {
  27113. if (this._renderingManager) {
  27114. this._renderingManager.freeRenderingGroups();
  27115. }
  27116. if (this.textures) {
  27117. for (var i = 0; i < this.textures.length; i++) {
  27118. var texture = this.textures[i];
  27119. if (texture && texture.renderList) {
  27120. texture.freeRenderingGroups();
  27121. }
  27122. }
  27123. }
  27124. };
  27125. /** @hidden */
  27126. Scene.prototype._isInIntermediateRendering = function () {
  27127. return this._intermediateRendering;
  27128. };
  27129. /**
  27130. * Defines the current active mesh candidate provider
  27131. * @param provider defines the provider to use
  27132. */
  27133. Scene.prototype.setActiveMeshCandidateProvider = function (provider) {
  27134. this._activeMeshCandidateProvider = provider;
  27135. };
  27136. /**
  27137. * Gets the current active mesh candidate provider
  27138. * @returns the current active mesh candidate provider
  27139. */
  27140. Scene.prototype.getActiveMeshCandidateProvider = function () {
  27141. return this._activeMeshCandidateProvider;
  27142. };
  27143. /**
  27144. * Use this function to stop evaluating active meshes. The current list will be keep alive between frames
  27145. * @returns the current scene
  27146. */
  27147. Scene.prototype.freezeActiveMeshes = function () {
  27148. if (!this.activeCamera) {
  27149. return this;
  27150. }
  27151. if (!this._frustumPlanes) {
  27152. this.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix());
  27153. }
  27154. this._evaluateActiveMeshes();
  27155. this._activeMeshesFrozen = true;
  27156. return this;
  27157. };
  27158. /**
  27159. * Use this function to restart evaluating active meshes on every frame
  27160. * @returns the current scene
  27161. */
  27162. Scene.prototype.unfreezeActiveMeshes = function () {
  27163. this._activeMeshesFrozen = false;
  27164. return this;
  27165. };
  27166. Scene.prototype._evaluateActiveMeshes = function () {
  27167. if (this._activeMeshesFrozen && this._activeMeshes.length) {
  27168. return;
  27169. }
  27170. if (!this.activeCamera) {
  27171. return;
  27172. }
  27173. this.onBeforeActiveMeshesEvaluationObservable.notifyObservers(this);
  27174. this.activeCamera._activeMeshes.reset();
  27175. this._activeMeshes.reset();
  27176. this._renderingManager.reset();
  27177. this._processedMaterials.reset();
  27178. this._activeParticleSystems.reset();
  27179. this._activeSkeletons.reset();
  27180. this._softwareSkinnedMeshes.reset();
  27181. if (this._boundingBoxRenderer) {
  27182. this._boundingBoxRenderer.reset();
  27183. }
  27184. // Meshes
  27185. var meshes;
  27186. var len;
  27187. var checkIsEnabled = true;
  27188. // Determine mesh candidates
  27189. if (this._activeMeshCandidateProvider !== undefined) {
  27190. // Use _activeMeshCandidateProvider
  27191. meshes = this._activeMeshCandidateProvider.getMeshes(this);
  27192. checkIsEnabled = this._activeMeshCandidateProvider.checksIsEnabled === false;
  27193. if (meshes !== undefined) {
  27194. len = meshes.length;
  27195. }
  27196. else {
  27197. len = 0;
  27198. }
  27199. }
  27200. else if (this._selectionOctree !== undefined) {
  27201. // Octree
  27202. var selection = this._selectionOctree.select(this._frustumPlanes);
  27203. meshes = selection.data;
  27204. len = selection.length;
  27205. }
  27206. else {
  27207. // Full scene traversal
  27208. len = this.meshes.length;
  27209. meshes = this.meshes;
  27210. }
  27211. // Check each mesh
  27212. for (var meshIndex = 0, mesh, meshLOD; meshIndex < len; meshIndex++) {
  27213. mesh = meshes[meshIndex];
  27214. if (mesh.isBlocked) {
  27215. continue;
  27216. }
  27217. this._totalVertices.addCount(mesh.getTotalVertices(), false);
  27218. if (!mesh.isReady() || (checkIsEnabled && !mesh.isEnabled())) {
  27219. continue;
  27220. }
  27221. mesh.computeWorldMatrix();
  27222. // Intersections
  27223. if (mesh.actionManager && mesh.actionManager.hasSpecificTriggers([BABYLON.ActionManager.OnIntersectionEnterTrigger, BABYLON.ActionManager.OnIntersectionExitTrigger])) {
  27224. this._meshesForIntersections.pushNoDuplicate(mesh);
  27225. }
  27226. // Switch to current LOD
  27227. meshLOD = mesh.getLOD(this.activeCamera);
  27228. if (meshLOD === undefined || meshLOD === null) {
  27229. continue;
  27230. }
  27231. mesh._preActivate();
  27232. if (mesh.alwaysSelectAsActiveMesh || mesh.isVisible && mesh.visibility > 0 && ((mesh.layerMask & this.activeCamera.layerMask) !== 0) && mesh.isInFrustum(this._frustumPlanes)) {
  27233. this._activeMeshes.push(mesh);
  27234. this.activeCamera._activeMeshes.push(mesh);
  27235. mesh._activate(this._renderId);
  27236. if (meshLOD !== mesh) {
  27237. meshLOD._activate(this._renderId);
  27238. }
  27239. this._activeMesh(mesh, meshLOD);
  27240. }
  27241. }
  27242. this.onAfterActiveMeshesEvaluationObservable.notifyObservers(this);
  27243. // Particle systems
  27244. if (this.particlesEnabled) {
  27245. this.onBeforeParticlesRenderingObservable.notifyObservers(this);
  27246. for (var particleIndex = 0; particleIndex < this.particleSystems.length; particleIndex++) {
  27247. var particleSystem = this.particleSystems[particleIndex];
  27248. if (!particleSystem.isStarted() || !particleSystem.emitter) {
  27249. continue;
  27250. }
  27251. var emitter = particleSystem.emitter;
  27252. if (!emitter.position || emitter.isEnabled()) {
  27253. this._activeParticleSystems.push(particleSystem);
  27254. particleSystem.animate();
  27255. this._renderingManager.dispatchParticles(particleSystem);
  27256. }
  27257. }
  27258. this.onAfterParticlesRenderingObservable.notifyObservers(this);
  27259. }
  27260. };
  27261. Scene.prototype._activeMesh = function (sourceMesh, mesh) {
  27262. if (this.skeletonsEnabled && mesh.skeleton !== null && mesh.skeleton !== undefined) {
  27263. if (this._activeSkeletons.pushNoDuplicate(mesh.skeleton)) {
  27264. mesh.skeleton.prepare();
  27265. }
  27266. if (!mesh.computeBonesUsingShaders) {
  27267. this._softwareSkinnedMeshes.pushNoDuplicate(mesh);
  27268. }
  27269. }
  27270. if (sourceMesh.showBoundingBox || this.forceShowBoundingBoxes) {
  27271. var boundingInfo = sourceMesh.getBoundingInfo();
  27272. this.getBoundingBoxRenderer().renderList.push(boundingInfo.boundingBox);
  27273. }
  27274. if (mesh !== undefined && mesh !== null
  27275. && mesh.subMeshes !== undefined && mesh.subMeshes !== null && mesh.subMeshes.length > 0) {
  27276. // Submeshes Octrees
  27277. var len;
  27278. var subMeshes;
  27279. if (mesh.useOctreeForRenderingSelection && mesh._submeshesOctree !== undefined && mesh._submeshesOctree !== null) {
  27280. var intersections = mesh._submeshesOctree.select(this._frustumPlanes);
  27281. len = intersections.length;
  27282. subMeshes = intersections.data;
  27283. }
  27284. else {
  27285. subMeshes = mesh.subMeshes;
  27286. len = subMeshes.length;
  27287. }
  27288. for (var subIndex = 0, subMesh; subIndex < len; subIndex++) {
  27289. subMesh = subMeshes[subIndex];
  27290. this._evaluateSubMesh(subMesh, mesh);
  27291. }
  27292. }
  27293. };
  27294. /**
  27295. * Update the transform matrix to update from the current active camera
  27296. * @param force defines a boolean used to force the update even if cache is up to date
  27297. */
  27298. Scene.prototype.updateTransformMatrix = function (force) {
  27299. if (!this.activeCamera) {
  27300. return;
  27301. }
  27302. this.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix(force));
  27303. };
  27304. /**
  27305. * 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)
  27306. * @param alternateCamera defines the camera to use
  27307. */
  27308. Scene.prototype.updateAlternateTransformMatrix = function (alternateCamera) {
  27309. this._setAlternateTransformMatrix(alternateCamera.getViewMatrix(), alternateCamera.getProjectionMatrix());
  27310. };
  27311. Scene.prototype._renderForCamera = function (camera, rigParent) {
  27312. if (camera && camera._skipRendering) {
  27313. return;
  27314. }
  27315. var engine = this._engine;
  27316. this.activeCamera = camera;
  27317. if (!this.activeCamera)
  27318. throw new Error("Active camera not set");
  27319. BABYLON.Tools.StartPerformanceCounter("Rendering camera " + this.activeCamera.name);
  27320. // Viewport
  27321. engine.setViewport(this.activeCamera.viewport);
  27322. // Camera
  27323. this.resetCachedMaterial();
  27324. this._renderId++;
  27325. this.updateTransformMatrix();
  27326. if (camera._alternateCamera) {
  27327. this.updateAlternateTransformMatrix(camera._alternateCamera);
  27328. this._alternateRendering = true;
  27329. }
  27330. this.onBeforeCameraRenderObservable.notifyObservers(this.activeCamera);
  27331. // Meshes
  27332. this._evaluateActiveMeshes();
  27333. // Software skinning
  27334. for (var softwareSkinnedMeshIndex = 0; softwareSkinnedMeshIndex < this._softwareSkinnedMeshes.length; softwareSkinnedMeshIndex++) {
  27335. var mesh = this._softwareSkinnedMeshes.data[softwareSkinnedMeshIndex];
  27336. mesh.applySkeleton(mesh.skeleton);
  27337. }
  27338. // Render targets
  27339. this.onBeforeRenderTargetsRenderObservable.notifyObservers(this);
  27340. var needsRestoreFrameBuffer = false;
  27341. if (camera.customRenderTargets && camera.customRenderTargets.length > 0) {
  27342. this._renderTargets.concatWithNoDuplicate(camera.customRenderTargets);
  27343. }
  27344. if (rigParent && rigParent.customRenderTargets && rigParent.customRenderTargets.length > 0) {
  27345. this._renderTargets.concatWithNoDuplicate(rigParent.customRenderTargets);
  27346. }
  27347. if (this.renderTargetsEnabled && this._renderTargets.length > 0) {
  27348. this._intermediateRendering = true;
  27349. BABYLON.Tools.StartPerformanceCounter("Render targets", this._renderTargets.length > 0);
  27350. for (var renderIndex = 0; renderIndex < this._renderTargets.length; renderIndex++) {
  27351. var renderTarget = this._renderTargets.data[renderIndex];
  27352. if (renderTarget._shouldRender()) {
  27353. this._renderId++;
  27354. var hasSpecialRenderTargetCamera = renderTarget.activeCamera && renderTarget.activeCamera !== this.activeCamera;
  27355. renderTarget.render(hasSpecialRenderTargetCamera, this.dumpNextRenderTargets);
  27356. }
  27357. }
  27358. BABYLON.Tools.EndPerformanceCounter("Render targets", this._renderTargets.length > 0);
  27359. this._intermediateRendering = false;
  27360. this._renderId++;
  27361. needsRestoreFrameBuffer = true; // Restore back buffer
  27362. }
  27363. // Render EffecttLayer Texture
  27364. var stencilState = this._engine.getStencilBuffer();
  27365. var renderEffects = false;
  27366. var needStencil = false;
  27367. if (this.renderTargetsEnabled && this.effectLayers && this.effectLayers.length > 0) {
  27368. this._intermediateRendering = true;
  27369. for (var i = 0; i < this.effectLayers.length; i++) {
  27370. var effectLayer = this.effectLayers[i];
  27371. if (effectLayer.shouldRender() &&
  27372. (!effectLayer.camera ||
  27373. (effectLayer.camera.cameraRigMode === BABYLON.Camera.RIG_MODE_NONE && camera === effectLayer.camera) ||
  27374. (effectLayer.camera.cameraRigMode !== BABYLON.Camera.RIG_MODE_NONE && effectLayer.camera._rigCameras.indexOf(camera) > -1))) {
  27375. renderEffects = true;
  27376. needStencil = needStencil || effectLayer.needStencil();
  27377. var renderTarget = effectLayer._mainTexture;
  27378. if (renderTarget._shouldRender()) {
  27379. this._renderId++;
  27380. renderTarget.render(false, false);
  27381. needsRestoreFrameBuffer = true;
  27382. }
  27383. }
  27384. }
  27385. this._intermediateRendering = false;
  27386. this._renderId++;
  27387. }
  27388. if (needsRestoreFrameBuffer) {
  27389. engine.restoreDefaultFramebuffer(); // Restore back buffer
  27390. }
  27391. this.onAfterRenderTargetsRenderObservable.notifyObservers(this);
  27392. // Prepare Frame
  27393. this.postProcessManager._prepareFrame();
  27394. // Backgrounds
  27395. var layerIndex;
  27396. var layer;
  27397. if (this.layers.length) {
  27398. engine.setDepthBuffer(false);
  27399. for (layerIndex = 0; layerIndex < this.layers.length; layerIndex++) {
  27400. layer = this.layers[layerIndex];
  27401. if (layer.isBackground && ((layer.layerMask & this.activeCamera.layerMask) !== 0)) {
  27402. layer.render();
  27403. }
  27404. }
  27405. engine.setDepthBuffer(true);
  27406. }
  27407. // Activate effect Layer stencil
  27408. if (needStencil) {
  27409. this._engine.setStencilBuffer(true);
  27410. }
  27411. // Render
  27412. this.onBeforeDrawPhaseObservable.notifyObservers(this);
  27413. this._renderingManager.render(null, null, true, true);
  27414. this.onAfterDrawPhaseObservable.notifyObservers(this);
  27415. // Restore effect Layer stencil
  27416. if (needStencil) {
  27417. this._engine.setStencilBuffer(stencilState);
  27418. }
  27419. // Bounding boxes
  27420. if (this._boundingBoxRenderer) {
  27421. this._boundingBoxRenderer.render();
  27422. }
  27423. // Lens flares
  27424. if (this.lensFlaresEnabled) {
  27425. BABYLON.Tools.StartPerformanceCounter("Lens flares", this.lensFlareSystems.length > 0);
  27426. for (var lensFlareSystemIndex = 0; lensFlareSystemIndex < this.lensFlareSystems.length; lensFlareSystemIndex++) {
  27427. var lensFlareSystem = this.lensFlareSystems[lensFlareSystemIndex];
  27428. if ((camera.layerMask & lensFlareSystem.layerMask) !== 0) {
  27429. lensFlareSystem.render();
  27430. }
  27431. }
  27432. BABYLON.Tools.EndPerformanceCounter("Lens flares", this.lensFlareSystems.length > 0);
  27433. }
  27434. // Effect Layer
  27435. if (renderEffects) {
  27436. engine.setDepthBuffer(false);
  27437. for (var i = 0; i < this.effectLayers.length; i++) {
  27438. if (this.effectLayers[i].shouldRender()) {
  27439. this.effectLayers[i].render();
  27440. }
  27441. }
  27442. engine.setDepthBuffer(true);
  27443. }
  27444. // Foregrounds
  27445. if (this.layers.length) {
  27446. engine.setDepthBuffer(false);
  27447. for (layerIndex = 0; layerIndex < this.layers.length; layerIndex++) {
  27448. layer = this.layers[layerIndex];
  27449. if (!layer.isBackground && ((layer.layerMask & this.activeCamera.layerMask) !== 0)) {
  27450. layer.render();
  27451. }
  27452. }
  27453. engine.setDepthBuffer(true);
  27454. }
  27455. // Finalize frame
  27456. this.postProcessManager._finalizeFrame(camera.isIntermediate);
  27457. // Reset some special arrays
  27458. this._renderTargets.reset();
  27459. this._alternateRendering = false;
  27460. this.onAfterCameraRenderObservable.notifyObservers(this.activeCamera);
  27461. BABYLON.Tools.EndPerformanceCounter("Rendering camera " + this.activeCamera.name);
  27462. };
  27463. Scene.prototype._processSubCameras = function (camera) {
  27464. if (camera.cameraRigMode === BABYLON.Camera.RIG_MODE_NONE) {
  27465. this._renderForCamera(camera);
  27466. return;
  27467. }
  27468. // rig cameras
  27469. for (var index = 0; index < camera._rigCameras.length; index++) {
  27470. this._renderForCamera(camera._rigCameras[index], camera);
  27471. }
  27472. this.activeCamera = camera;
  27473. this.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix());
  27474. };
  27475. Scene.prototype._checkIntersections = function () {
  27476. for (var index = 0; index < this._meshesForIntersections.length; index++) {
  27477. var sourceMesh = this._meshesForIntersections.data[index];
  27478. if (!sourceMesh.actionManager) {
  27479. continue;
  27480. }
  27481. for (var actionIndex = 0; actionIndex < sourceMesh.actionManager.actions.length; actionIndex++) {
  27482. var action = sourceMesh.actionManager.actions[actionIndex];
  27483. if (action.trigger === BABYLON.ActionManager.OnIntersectionEnterTrigger || action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  27484. var parameters = action.getTriggerParameter();
  27485. var otherMesh = parameters instanceof BABYLON.AbstractMesh ? parameters : parameters.mesh;
  27486. var areIntersecting = otherMesh.intersectsMesh(sourceMesh, parameters.usePreciseIntersection);
  27487. var currentIntersectionInProgress = sourceMesh._intersectionsInProgress.indexOf(otherMesh);
  27488. if (areIntersecting && currentIntersectionInProgress === -1) {
  27489. if (action.trigger === BABYLON.ActionManager.OnIntersectionEnterTrigger) {
  27490. action._executeCurrent(BABYLON.ActionEvent.CreateNew(sourceMesh, undefined, otherMesh));
  27491. sourceMesh._intersectionsInProgress.push(otherMesh);
  27492. }
  27493. else if (action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  27494. sourceMesh._intersectionsInProgress.push(otherMesh);
  27495. }
  27496. }
  27497. else if (!areIntersecting && currentIntersectionInProgress > -1) {
  27498. //They intersected, and now they don't.
  27499. //is this trigger an exit trigger? execute an event.
  27500. if (action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  27501. action._executeCurrent(BABYLON.ActionEvent.CreateNew(sourceMesh, undefined, otherMesh));
  27502. }
  27503. //if this is an exit trigger, or no exit trigger exists, remove the id from the intersection in progress array.
  27504. if (!sourceMesh.actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnIntersectionExitTrigger, function (parameter) {
  27505. var parameterMesh = parameter instanceof BABYLON.AbstractMesh ? parameter : parameter.mesh;
  27506. return otherMesh === parameterMesh;
  27507. }) || action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  27508. sourceMesh._intersectionsInProgress.splice(currentIntersectionInProgress, 1);
  27509. }
  27510. }
  27511. }
  27512. }
  27513. }
  27514. };
  27515. /**
  27516. * Render the scene
  27517. */
  27518. Scene.prototype.render = function () {
  27519. if (this.isDisposed) {
  27520. return;
  27521. }
  27522. this._activeParticles.fetchNewFrame();
  27523. this._totalVertices.fetchNewFrame();
  27524. this._activeIndices.fetchNewFrame();
  27525. this._activeBones.fetchNewFrame();
  27526. this._meshesForIntersections.reset();
  27527. this.resetCachedMaterial();
  27528. this.onBeforeAnimationsObservable.notifyObservers(this);
  27529. // Actions
  27530. if (this.actionManager) {
  27531. this.actionManager.processTrigger(BABYLON.ActionManager.OnEveryFrameTrigger);
  27532. }
  27533. //Simplification Queue
  27534. if (this.simplificationQueue && !this.simplificationQueue.running) {
  27535. this.simplificationQueue.executeNext();
  27536. }
  27537. if (this._engine.isDeterministicLockStep()) {
  27538. var deltaTime = Math.max(Scene.MinDeltaTime, Math.min(this._engine.getDeltaTime(), Scene.MaxDeltaTime)) + this._timeAccumulator;
  27539. var defaultFPS = (60.0 / 1000.0);
  27540. var defaultFrameTime = 1000 / 60; // frame time in MS
  27541. if (this._physicsEngine) {
  27542. defaultFrameTime = this._physicsEngine.getTimeStep() * 1000;
  27543. }
  27544. var stepsTaken = 0;
  27545. var maxSubSteps = this._engine.getLockstepMaxSteps();
  27546. var internalSteps = Math.floor(deltaTime / (1000 * defaultFPS));
  27547. internalSteps = Math.min(internalSteps, maxSubSteps);
  27548. do {
  27549. this.onBeforeStepObservable.notifyObservers(this);
  27550. // Animations
  27551. this._animationRatio = defaultFrameTime * defaultFPS;
  27552. this._animate();
  27553. this.onAfterAnimationsObservable.notifyObservers(this);
  27554. // Physics
  27555. if (this._physicsEngine) {
  27556. this.onBeforePhysicsObservable.notifyObservers(this);
  27557. this._physicsEngine._step(defaultFrameTime / 1000);
  27558. this.onAfterPhysicsObservable.notifyObservers(this);
  27559. }
  27560. this.onAfterStepObservable.notifyObservers(this);
  27561. this._currentStepId++;
  27562. stepsTaken++;
  27563. deltaTime -= defaultFrameTime;
  27564. } while (deltaTime > 0 && stepsTaken < internalSteps);
  27565. this._timeAccumulator = deltaTime < 0 ? 0 : deltaTime;
  27566. }
  27567. else {
  27568. // Animations
  27569. var deltaTime = this.useConstantAnimationDeltaTime ? 16 : Math.max(Scene.MinDeltaTime, Math.min(this._engine.getDeltaTime(), Scene.MaxDeltaTime));
  27570. this._animationRatio = deltaTime * (60.0 / 1000.0);
  27571. this._animate();
  27572. this.onAfterAnimationsObservable.notifyObservers(this);
  27573. // Physics
  27574. if (this._physicsEngine) {
  27575. this.onBeforePhysicsObservable.notifyObservers(this);
  27576. this._physicsEngine._step(deltaTime / 1000.0);
  27577. this.onAfterPhysicsObservable.notifyObservers(this);
  27578. }
  27579. }
  27580. // update gamepad manager
  27581. if (this._gamepadManager && this._gamepadManager._isMonitoring) {
  27582. this._gamepadManager._checkGamepadsStatus();
  27583. }
  27584. // Update Cameras
  27585. if (this.activeCameras.length > 0) {
  27586. for (var cameraIndex = 0; cameraIndex < this.activeCameras.length; cameraIndex++) {
  27587. var camera = this.activeCameras[cameraIndex];
  27588. camera.update();
  27589. if (camera.cameraRigMode !== BABYLON.Camera.RIG_MODE_NONE) {
  27590. // rig cameras
  27591. for (var index = 0; index < camera._rigCameras.length; index++) {
  27592. camera._rigCameras[index].update();
  27593. }
  27594. }
  27595. }
  27596. }
  27597. else if (this.activeCamera) {
  27598. this.activeCamera.update();
  27599. if (this.activeCamera.cameraRigMode !== BABYLON.Camera.RIG_MODE_NONE) {
  27600. // rig cameras
  27601. for (var index = 0; index < this.activeCamera._rigCameras.length; index++) {
  27602. this.activeCamera._rigCameras[index].update();
  27603. }
  27604. }
  27605. }
  27606. // Before render
  27607. this.onBeforeRenderObservable.notifyObservers(this);
  27608. // Customs render targets
  27609. this.onBeforeRenderTargetsRenderObservable.notifyObservers(this);
  27610. var engine = this.getEngine();
  27611. var currentActiveCamera = this.activeCamera;
  27612. if (this.renderTargetsEnabled) {
  27613. BABYLON.Tools.StartPerformanceCounter("Custom render targets", this.customRenderTargets.length > 0);
  27614. this._intermediateRendering = true;
  27615. for (var customIndex = 0; customIndex < this.customRenderTargets.length; customIndex++) {
  27616. var renderTarget = this.customRenderTargets[customIndex];
  27617. if (renderTarget._shouldRender()) {
  27618. this._renderId++;
  27619. this.activeCamera = renderTarget.activeCamera || this.activeCamera;
  27620. if (!this.activeCamera)
  27621. throw new Error("Active camera not set");
  27622. // Viewport
  27623. engine.setViewport(this.activeCamera.viewport);
  27624. // Camera
  27625. this.updateTransformMatrix();
  27626. renderTarget.render(currentActiveCamera !== this.activeCamera, this.dumpNextRenderTargets);
  27627. }
  27628. }
  27629. BABYLON.Tools.EndPerformanceCounter("Custom render targets", this.customRenderTargets.length > 0);
  27630. this._intermediateRendering = false;
  27631. this._renderId++;
  27632. }
  27633. // Restore back buffer
  27634. if (this.customRenderTargets.length > 0) {
  27635. engine.restoreDefaultFramebuffer();
  27636. }
  27637. this.onAfterRenderTargetsRenderObservable.notifyObservers(this);
  27638. this.activeCamera = currentActiveCamera;
  27639. // Procedural textures
  27640. if (this.proceduralTexturesEnabled) {
  27641. BABYLON.Tools.StartPerformanceCounter("Procedural textures", this.proceduralTextures.length > 0);
  27642. for (var proceduralIndex = 0; proceduralIndex < this.proceduralTextures.length; proceduralIndex++) {
  27643. var proceduralTexture = this.proceduralTextures[proceduralIndex];
  27644. if (proceduralTexture._shouldRender()) {
  27645. proceduralTexture.render();
  27646. }
  27647. }
  27648. BABYLON.Tools.EndPerformanceCounter("Procedural textures", this.proceduralTextures.length > 0);
  27649. }
  27650. // Clear
  27651. if (this.autoClearDepthAndStencil || this.autoClear) {
  27652. this._engine.clear(this.clearColor, this.autoClear || this.forceWireframe || this.forcePointsCloud, this.autoClearDepthAndStencil, this.autoClearDepthAndStencil);
  27653. }
  27654. // Shadows
  27655. if (this.shadowsEnabled) {
  27656. for (var lightIndex = 0; lightIndex < this.lights.length; lightIndex++) {
  27657. var light = this.lights[lightIndex];
  27658. var shadowGenerator = light.getShadowGenerator();
  27659. if (light.isEnabled() && light.shadowEnabled && shadowGenerator) {
  27660. var shadowMap = (shadowGenerator.getShadowMap());
  27661. if (this.textures.indexOf(shadowMap) !== -1) {
  27662. this._renderTargets.push(shadowMap);
  27663. }
  27664. }
  27665. }
  27666. }
  27667. // Depth renderer
  27668. for (var key in this._depthRenderer) {
  27669. this._renderTargets.push(this._depthRenderer[key].getDepthMap());
  27670. }
  27671. // Geometry renderer
  27672. if (this._geometryBufferRenderer) {
  27673. this._renderTargets.push(this._geometryBufferRenderer.getGBuffer());
  27674. }
  27675. // RenderPipeline
  27676. if (this._postProcessRenderPipelineManager) {
  27677. this._postProcessRenderPipelineManager.update();
  27678. }
  27679. // Multi-cameras?
  27680. if (this.activeCameras.length > 0) {
  27681. for (var cameraIndex = 0; cameraIndex < this.activeCameras.length; cameraIndex++) {
  27682. if (cameraIndex > 0) {
  27683. this._engine.clear(null, false, true, true);
  27684. }
  27685. this._processSubCameras(this.activeCameras[cameraIndex]);
  27686. }
  27687. }
  27688. else {
  27689. if (!this.activeCamera) {
  27690. throw new Error("No camera defined");
  27691. }
  27692. this._processSubCameras(this.activeCamera);
  27693. }
  27694. // Intersection checks
  27695. this._checkIntersections();
  27696. // Update the audio listener attached to the camera
  27697. if (BABYLON.AudioEngine) {
  27698. this._updateAudioParameters();
  27699. }
  27700. // After render
  27701. if (this.afterRender) {
  27702. this.afterRender();
  27703. }
  27704. this.onAfterRenderObservable.notifyObservers(this);
  27705. // Cleaning
  27706. for (var index = 0; index < this._toBeDisposed.length; index++) {
  27707. var data = this._toBeDisposed.data[index];
  27708. if (data) {
  27709. data.dispose();
  27710. }
  27711. this._toBeDisposed[index] = null;
  27712. }
  27713. this._toBeDisposed.reset();
  27714. if (this.dumpNextRenderTargets) {
  27715. this.dumpNextRenderTargets = false;
  27716. }
  27717. this._activeBones.addCount(0, true);
  27718. this._activeIndices.addCount(0, true);
  27719. this._activeParticles.addCount(0, true);
  27720. };
  27721. Scene.prototype._updateAudioParameters = function () {
  27722. if (!this.audioEnabled || !this._mainSoundTrack || (this._mainSoundTrack.soundCollection.length === 0 && this.soundTracks.length === 1)) {
  27723. return;
  27724. }
  27725. var listeningCamera;
  27726. var audioEngine = BABYLON.Engine.audioEngine;
  27727. if (this.activeCameras.length > 0) {
  27728. listeningCamera = this.activeCameras[0];
  27729. }
  27730. else {
  27731. listeningCamera = this.activeCamera;
  27732. }
  27733. if (listeningCamera && audioEngine.canUseWebAudio && audioEngine.audioContext) {
  27734. audioEngine.audioContext.listener.setPosition(listeningCamera.position.x, listeningCamera.position.y, listeningCamera.position.z);
  27735. // for VR cameras
  27736. if (listeningCamera.rigCameras && listeningCamera.rigCameras.length > 0) {
  27737. listeningCamera = listeningCamera.rigCameras[0];
  27738. }
  27739. var mat = BABYLON.Matrix.Invert(listeningCamera.getViewMatrix());
  27740. var cameraDirection = BABYLON.Vector3.TransformNormal(new BABYLON.Vector3(0, 0, -1), mat);
  27741. cameraDirection.normalize();
  27742. // To avoid some errors on GearVR
  27743. if (!isNaN(cameraDirection.x) && !isNaN(cameraDirection.y) && !isNaN(cameraDirection.z)) {
  27744. audioEngine.audioContext.listener.setOrientation(cameraDirection.x, cameraDirection.y, cameraDirection.z, 0, 1, 0);
  27745. }
  27746. var i;
  27747. for (i = 0; i < this.mainSoundTrack.soundCollection.length; i++) {
  27748. var sound = this.mainSoundTrack.soundCollection[i];
  27749. if (sound.useCustomAttenuation) {
  27750. sound.updateDistanceFromListener();
  27751. }
  27752. }
  27753. for (i = 0; i < this.soundTracks.length; i++) {
  27754. for (var j = 0; j < this.soundTracks[i].soundCollection.length; j++) {
  27755. sound = this.soundTracks[i].soundCollection[j];
  27756. if (sound.useCustomAttenuation) {
  27757. sound.updateDistanceFromListener();
  27758. }
  27759. }
  27760. }
  27761. }
  27762. };
  27763. Object.defineProperty(Scene.prototype, "audioEnabled", {
  27764. // Audio
  27765. /**
  27766. * Gets or sets if audio support is enabled
  27767. * @see http://doc.babylonjs.com/how_to/playing_sounds_and_music
  27768. */
  27769. get: function () {
  27770. return this._audioEnabled;
  27771. },
  27772. set: function (value) {
  27773. this._audioEnabled = value;
  27774. if (BABYLON.AudioEngine) {
  27775. if (this._audioEnabled) {
  27776. this._enableAudio();
  27777. }
  27778. else {
  27779. this._disableAudio();
  27780. }
  27781. }
  27782. },
  27783. enumerable: true,
  27784. configurable: true
  27785. });
  27786. Scene.prototype._disableAudio = function () {
  27787. var i;
  27788. for (i = 0; i < this.mainSoundTrack.soundCollection.length; i++) {
  27789. this.mainSoundTrack.soundCollection[i].pause();
  27790. }
  27791. for (i = 0; i < this.soundTracks.length; i++) {
  27792. for (var j = 0; j < this.soundTracks[i].soundCollection.length; j++) {
  27793. this.soundTracks[i].soundCollection[j].pause();
  27794. }
  27795. }
  27796. };
  27797. Scene.prototype._enableAudio = function () {
  27798. var i;
  27799. for (i = 0; i < this.mainSoundTrack.soundCollection.length; i++) {
  27800. if (this.mainSoundTrack.soundCollection[i].isPaused) {
  27801. this.mainSoundTrack.soundCollection[i].play();
  27802. }
  27803. }
  27804. for (i = 0; i < this.soundTracks.length; i++) {
  27805. for (var j = 0; j < this.soundTracks[i].soundCollection.length; j++) {
  27806. if (this.soundTracks[i].soundCollection[j].isPaused) {
  27807. this.soundTracks[i].soundCollection[j].play();
  27808. }
  27809. }
  27810. }
  27811. };
  27812. Object.defineProperty(Scene.prototype, "headphone", {
  27813. /**
  27814. * Gets or sets if audio will be output to headphones
  27815. * @see http://doc.babylonjs.com/how_to/playing_sounds_and_music
  27816. */
  27817. get: function () {
  27818. return this._headphone;
  27819. },
  27820. set: function (value) {
  27821. this._headphone = value;
  27822. if (BABYLON.AudioEngine) {
  27823. if (this._headphone) {
  27824. this._switchAudioModeForHeadphones();
  27825. }
  27826. else {
  27827. this._switchAudioModeForNormalSpeakers();
  27828. }
  27829. }
  27830. },
  27831. enumerable: true,
  27832. configurable: true
  27833. });
  27834. Scene.prototype._switchAudioModeForHeadphones = function () {
  27835. this.mainSoundTrack.switchPanningModelToHRTF();
  27836. for (var i = 0; i < this.soundTracks.length; i++) {
  27837. this.soundTracks[i].switchPanningModelToHRTF();
  27838. }
  27839. };
  27840. Scene.prototype._switchAudioModeForNormalSpeakers = function () {
  27841. this.mainSoundTrack.switchPanningModelToEqualPower();
  27842. for (var i = 0; i < this.soundTracks.length; i++) {
  27843. this.soundTracks[i].switchPanningModelToEqualPower();
  27844. }
  27845. };
  27846. /**
  27847. * Creates a depth renderer a given camera which contains a depth map which can be used for post processing.
  27848. * @param camera The camera to create the depth renderer on (default: scene's active camera)
  27849. * @returns the created depth renderer
  27850. */
  27851. Scene.prototype.enableDepthRenderer = function (camera) {
  27852. camera = camera || this.activeCamera;
  27853. if (!camera) {
  27854. throw "No camera available to enable depth renderer";
  27855. }
  27856. if (!this._depthRenderer[camera.id]) {
  27857. var textureType = 0;
  27858. if (this._engine.getCaps().textureHalfFloatRender) {
  27859. textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  27860. }
  27861. else if (this._engine.getCaps().textureFloatRender) {
  27862. textureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  27863. }
  27864. else {
  27865. throw "Depth renderer does not support int texture type";
  27866. }
  27867. this._depthRenderer[camera.id] = new BABYLON.DepthRenderer(this, textureType, camera);
  27868. }
  27869. return this._depthRenderer[camera.id];
  27870. };
  27871. /**
  27872. * Disables a depth renderer for a given camera
  27873. * @param camera The camera to disable the depth renderer on (default: scene's active camera)
  27874. */
  27875. Scene.prototype.disableDepthRenderer = function (camera) {
  27876. camera = camera || this.activeCamera;
  27877. if (!camera || !this._depthRenderer[camera.id]) {
  27878. return;
  27879. }
  27880. this._depthRenderer[camera.id].dispose();
  27881. delete this._depthRenderer[camera.id];
  27882. };
  27883. /**
  27884. * Enables a GeometryBufferRender and associates it with the scene
  27885. * @param ratio defines the scaling ratio to apply to the renderer (1 by default which means same resolution)
  27886. * @returns the GeometryBufferRenderer
  27887. */
  27888. Scene.prototype.enableGeometryBufferRenderer = function (ratio) {
  27889. if (ratio === void 0) { ratio = 1; }
  27890. if (this._geometryBufferRenderer) {
  27891. return this._geometryBufferRenderer;
  27892. }
  27893. this._geometryBufferRenderer = new BABYLON.GeometryBufferRenderer(this, ratio);
  27894. if (!this._geometryBufferRenderer.isSupported) {
  27895. this._geometryBufferRenderer = null;
  27896. }
  27897. return this._geometryBufferRenderer;
  27898. };
  27899. /**
  27900. * Disables the GeometryBufferRender associated with the scene
  27901. */
  27902. Scene.prototype.disableGeometryBufferRenderer = function () {
  27903. if (!this._geometryBufferRenderer) {
  27904. return;
  27905. }
  27906. this._geometryBufferRenderer.dispose();
  27907. this._geometryBufferRenderer = null;
  27908. };
  27909. /**
  27910. * Freeze all materials
  27911. * A frozen material will not be updatable but should be faster to render
  27912. */
  27913. Scene.prototype.freezeMaterials = function () {
  27914. for (var i = 0; i < this.materials.length; i++) {
  27915. this.materials[i].freeze();
  27916. }
  27917. };
  27918. /**
  27919. * Unfreeze all materials
  27920. * A frozen material will not be updatable but should be faster to render
  27921. */
  27922. Scene.prototype.unfreezeMaterials = function () {
  27923. for (var i = 0; i < this.materials.length; i++) {
  27924. this.materials[i].unfreeze();
  27925. }
  27926. };
  27927. /**
  27928. * Releases all held ressources
  27929. */
  27930. Scene.prototype.dispose = function () {
  27931. this.beforeRender = null;
  27932. this.afterRender = null;
  27933. this.skeletons = [];
  27934. this.morphTargetManagers = [];
  27935. this.importedMeshesFiles = new Array();
  27936. this.stopAllAnimations();
  27937. this.resetCachedMaterial();
  27938. for (var key in this._depthRenderer) {
  27939. this._depthRenderer[key].dispose();
  27940. }
  27941. if (this._gamepadManager) {
  27942. this._gamepadManager.dispose();
  27943. this._gamepadManager = null;
  27944. }
  27945. // Smart arrays
  27946. if (this.activeCamera) {
  27947. this.activeCamera._activeMeshes.dispose();
  27948. this.activeCamera = null;
  27949. }
  27950. this._activeMeshes.dispose();
  27951. this._renderingManager.dispose();
  27952. this._processedMaterials.dispose();
  27953. this._activeParticleSystems.dispose();
  27954. this._activeSkeletons.dispose();
  27955. this._softwareSkinnedMeshes.dispose();
  27956. this._renderTargets.dispose();
  27957. this._registeredForLateAnimationBindings.dispose();
  27958. if (this._boundingBoxRenderer) {
  27959. this._boundingBoxRenderer.dispose();
  27960. }
  27961. this._meshesForIntersections.dispose();
  27962. this._toBeDisposed.dispose();
  27963. // Abort active requests
  27964. for (var _i = 0, _a = this._activeRequests; _i < _a.length; _i++) {
  27965. var request = _a[_i];
  27966. request.abort();
  27967. }
  27968. // Debug layer
  27969. if (this._debugLayer) {
  27970. this._debugLayer.hide();
  27971. }
  27972. // Events
  27973. this.onDisposeObservable.notifyObservers(this);
  27974. this.onDisposeObservable.clear();
  27975. this.onBeforeRenderObservable.clear();
  27976. this.onAfterRenderObservable.clear();
  27977. this.onBeforeRenderTargetsRenderObservable.clear();
  27978. this.onAfterRenderTargetsRenderObservable.clear();
  27979. this.onAfterStepObservable.clear();
  27980. this.onBeforeStepObservable.clear();
  27981. this.onBeforeActiveMeshesEvaluationObservable.clear();
  27982. this.onAfterActiveMeshesEvaluationObservable.clear();
  27983. this.onBeforeParticlesRenderingObservable.clear();
  27984. this.onAfterParticlesRenderingObservable.clear();
  27985. this.onBeforeSpritesRenderingObservable.clear();
  27986. this.onAfterSpritesRenderingObservable.clear();
  27987. this.onBeforeDrawPhaseObservable.clear();
  27988. this.onAfterDrawPhaseObservable.clear();
  27989. this.onBeforePhysicsObservable.clear();
  27990. this.onAfterPhysicsObservable.clear();
  27991. this.onBeforeAnimationsObservable.clear();
  27992. this.onAfterAnimationsObservable.clear();
  27993. this.onDataLoadedObservable.clear();
  27994. this.detachControl();
  27995. // Release sounds & sounds tracks
  27996. if (BABYLON.AudioEngine) {
  27997. this.disposeSounds();
  27998. }
  27999. // VR Helper
  28000. if (this.VRHelper) {
  28001. this.VRHelper.dispose();
  28002. }
  28003. // Detach cameras
  28004. var canvas = this._engine.getRenderingCanvas();
  28005. if (canvas) {
  28006. var index;
  28007. for (index = 0; index < this.cameras.length; index++) {
  28008. this.cameras[index].detachControl(canvas);
  28009. }
  28010. }
  28011. // Release animation groups
  28012. while (this.animationGroups.length) {
  28013. this.animationGroups[0].dispose();
  28014. }
  28015. // Release lights
  28016. while (this.lights.length) {
  28017. this.lights[0].dispose();
  28018. }
  28019. // Release meshes
  28020. while (this.meshes.length) {
  28021. this.meshes[0].dispose(true);
  28022. }
  28023. while (this.transformNodes.length) {
  28024. this.removeTransformNode(this.transformNodes[0]);
  28025. }
  28026. // Release cameras
  28027. while (this.cameras.length) {
  28028. this.cameras[0].dispose();
  28029. }
  28030. // Release materials
  28031. if (this.defaultMaterial) {
  28032. this.defaultMaterial.dispose();
  28033. }
  28034. while (this.multiMaterials.length) {
  28035. this.multiMaterials[0].dispose();
  28036. }
  28037. while (this.materials.length) {
  28038. this.materials[0].dispose();
  28039. }
  28040. // Release particles
  28041. while (this.particleSystems.length) {
  28042. this.particleSystems[0].dispose();
  28043. }
  28044. // Release sprites
  28045. while (this.spriteManagers.length) {
  28046. this.spriteManagers[0].dispose();
  28047. }
  28048. // Release postProcesses
  28049. while (this.postProcesses.length) {
  28050. this.postProcesses[0].dispose();
  28051. }
  28052. // Release layers
  28053. while (this.layers.length) {
  28054. this.layers[0].dispose();
  28055. }
  28056. while (this.effectLayers.length) {
  28057. this.effectLayers[0].dispose();
  28058. }
  28059. // Release textures
  28060. while (this.textures.length) {
  28061. this.textures[0].dispose();
  28062. }
  28063. // Release UBO
  28064. this._sceneUbo.dispose();
  28065. if (this._alternateSceneUbo) {
  28066. this._alternateSceneUbo.dispose();
  28067. }
  28068. // Post-processes
  28069. this.postProcessManager.dispose();
  28070. if (this._postProcessRenderPipelineManager) {
  28071. this._postProcessRenderPipelineManager.dispose();
  28072. }
  28073. // Physics
  28074. if (this._physicsEngine) {
  28075. this.disablePhysicsEngine();
  28076. }
  28077. // Remove from engine
  28078. index = this._engine.scenes.indexOf(this);
  28079. if (index > -1) {
  28080. this._engine.scenes.splice(index, 1);
  28081. }
  28082. this._engine.wipeCaches(true);
  28083. this._isDisposed = true;
  28084. };
  28085. Object.defineProperty(Scene.prototype, "isDisposed", {
  28086. /**
  28087. * Gets if the scene is already disposed
  28088. */
  28089. get: function () {
  28090. return this._isDisposed;
  28091. },
  28092. enumerable: true,
  28093. configurable: true
  28094. });
  28095. /**
  28096. * Releases sounds & soundtracks
  28097. */
  28098. Scene.prototype.disposeSounds = function () {
  28099. if (!this._mainSoundTrack) {
  28100. return;
  28101. }
  28102. this.mainSoundTrack.dispose();
  28103. for (var scIndex = 0; scIndex < this.soundTracks.length; scIndex++) {
  28104. this.soundTracks[scIndex].dispose();
  28105. }
  28106. };
  28107. // Octrees
  28108. /**
  28109. * Get the world extend vectors with an optional filter
  28110. *
  28111. * @param filterPredicate the predicate - which meshes should be included when calculating the world size
  28112. * @returns {{ min: Vector3; max: Vector3 }} min and max vectors
  28113. */
  28114. Scene.prototype.getWorldExtends = function (filterPredicate) {
  28115. var min = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  28116. var max = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  28117. filterPredicate = filterPredicate || (function () { return true; });
  28118. this.meshes.filter(filterPredicate).forEach(function (mesh) {
  28119. mesh.computeWorldMatrix(true);
  28120. if (!mesh.subMeshes || mesh.subMeshes.length === 0 || mesh.infiniteDistance) {
  28121. return;
  28122. }
  28123. var boundingInfo = mesh.getBoundingInfo();
  28124. var minBox = boundingInfo.boundingBox.minimumWorld;
  28125. var maxBox = boundingInfo.boundingBox.maximumWorld;
  28126. BABYLON.Tools.CheckExtends(minBox, min, max);
  28127. BABYLON.Tools.CheckExtends(maxBox, min, max);
  28128. });
  28129. return {
  28130. min: min,
  28131. max: max
  28132. };
  28133. };
  28134. /**
  28135. * Creates or updates the octree used to boost selection (picking)
  28136. * @see http://doc.babylonjs.com/how_to/optimizing_your_scene_with_octrees
  28137. * @param maxCapacity defines the maximum capacity per leaf
  28138. * @param maxDepth defines the maximum depth of the octree
  28139. * @returns an octree of AbstractMesh
  28140. */
  28141. Scene.prototype.createOrUpdateSelectionOctree = function (maxCapacity, maxDepth) {
  28142. if (maxCapacity === void 0) { maxCapacity = 64; }
  28143. if (maxDepth === void 0) { maxDepth = 2; }
  28144. if (!this._selectionOctree) {
  28145. this._selectionOctree = new BABYLON.Octree(BABYLON.Octree.CreationFuncForMeshes, maxCapacity, maxDepth);
  28146. }
  28147. var worldExtends = this.getWorldExtends();
  28148. // Update octree
  28149. this._selectionOctree.update(worldExtends.min, worldExtends.max, this.meshes);
  28150. return this._selectionOctree;
  28151. };
  28152. // Picking
  28153. /**
  28154. * Creates a ray that can be used to pick in the scene
  28155. * @param x defines the x coordinate of the origin (on-screen)
  28156. * @param y defines the y coordinate of the origin (on-screen)
  28157. * @param world defines the world matrix to use if you want to pick in object space (instead of world space)
  28158. * @param camera defines the camera to use for the picking
  28159. * @param cameraViewSpace defines if picking will be done in view space (false by default)
  28160. * @returns a Ray
  28161. */
  28162. Scene.prototype.createPickingRay = function (x, y, world, camera, cameraViewSpace) {
  28163. if (cameraViewSpace === void 0) { cameraViewSpace = false; }
  28164. var result = BABYLON.Ray.Zero();
  28165. this.createPickingRayToRef(x, y, world, result, camera, cameraViewSpace);
  28166. return result;
  28167. };
  28168. /**
  28169. * Creates a ray that can be used to pick in the scene
  28170. * @param x defines the x coordinate of the origin (on-screen)
  28171. * @param y defines the y coordinate of the origin (on-screen)
  28172. * @param world defines the world matrix to use if you want to pick in object space (instead of world space)
  28173. * @param result defines the ray where to store the picking ray
  28174. * @param camera defines the camera to use for the picking
  28175. * @param cameraViewSpace defines if picking will be done in view space (false by default)
  28176. * @returns the current scene
  28177. */
  28178. Scene.prototype.createPickingRayToRef = function (x, y, world, result, camera, cameraViewSpace) {
  28179. if (cameraViewSpace === void 0) { cameraViewSpace = false; }
  28180. var engine = this._engine;
  28181. if (!camera) {
  28182. if (!this.activeCamera)
  28183. throw new Error("Active camera not set");
  28184. camera = this.activeCamera;
  28185. }
  28186. var cameraViewport = camera.viewport;
  28187. var viewport = cameraViewport.toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
  28188. // Moving coordinates to local viewport world
  28189. x = x / this._engine.getHardwareScalingLevel() - viewport.x;
  28190. y = y / this._engine.getHardwareScalingLevel() - (this._engine.getRenderHeight() - viewport.y - viewport.height);
  28191. result.update(x, y, viewport.width, viewport.height, world ? world : BABYLON.Matrix.Identity(), cameraViewSpace ? BABYLON.Matrix.Identity() : camera.getViewMatrix(), camera.getProjectionMatrix());
  28192. return this;
  28193. };
  28194. /**
  28195. * Creates a ray that can be used to pick in the scene
  28196. * @param x defines the x coordinate of the origin (on-screen)
  28197. * @param y defines the y coordinate of the origin (on-screen)
  28198. * @param camera defines the camera to use for the picking
  28199. * @returns a Ray
  28200. */
  28201. Scene.prototype.createPickingRayInCameraSpace = function (x, y, camera) {
  28202. var result = BABYLON.Ray.Zero();
  28203. this.createPickingRayInCameraSpaceToRef(x, y, result, camera);
  28204. return result;
  28205. };
  28206. /**
  28207. * Creates a ray that can be used to pick in the scene
  28208. * @param x defines the x coordinate of the origin (on-screen)
  28209. * @param y defines the y coordinate of the origin (on-screen)
  28210. * @param result defines the ray where to store the picking ray
  28211. * @param camera defines the camera to use for the picking
  28212. * @returns the current scene
  28213. */
  28214. Scene.prototype.createPickingRayInCameraSpaceToRef = function (x, y, result, camera) {
  28215. if (!BABYLON.PickingInfo) {
  28216. return this;
  28217. }
  28218. var engine = this._engine;
  28219. if (!camera) {
  28220. if (!this.activeCamera)
  28221. throw new Error("Active camera not set");
  28222. camera = this.activeCamera;
  28223. }
  28224. var cameraViewport = camera.viewport;
  28225. var viewport = cameraViewport.toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
  28226. var identity = BABYLON.Matrix.Identity();
  28227. // Moving coordinates to local viewport world
  28228. x = x / this._engine.getHardwareScalingLevel() - viewport.x;
  28229. y = y / this._engine.getHardwareScalingLevel() - (this._engine.getRenderHeight() - viewport.y - viewport.height);
  28230. result.update(x, y, viewport.width, viewport.height, identity, identity, camera.getProjectionMatrix());
  28231. return this;
  28232. };
  28233. Scene.prototype._internalPick = function (rayFunction, predicate, fastCheck) {
  28234. if (!BABYLON.PickingInfo) {
  28235. return null;
  28236. }
  28237. var pickingInfo = null;
  28238. for (var meshIndex = 0; meshIndex < this.meshes.length; meshIndex++) {
  28239. var mesh = this.meshes[meshIndex];
  28240. if (predicate) {
  28241. if (!predicate(mesh)) {
  28242. continue;
  28243. }
  28244. }
  28245. else if (!mesh.isEnabled() || !mesh.isVisible || !mesh.isPickable) {
  28246. continue;
  28247. }
  28248. var world = mesh.getWorldMatrix();
  28249. var ray = rayFunction(world);
  28250. var result = mesh.intersects(ray, fastCheck);
  28251. if (!result || !result.hit)
  28252. continue;
  28253. if (!fastCheck && pickingInfo != null && result.distance >= pickingInfo.distance)
  28254. continue;
  28255. pickingInfo = result;
  28256. if (fastCheck) {
  28257. break;
  28258. }
  28259. }
  28260. return pickingInfo || new BABYLON.PickingInfo();
  28261. };
  28262. Scene.prototype._internalMultiPick = function (rayFunction, predicate) {
  28263. if (!BABYLON.PickingInfo) {
  28264. return null;
  28265. }
  28266. var pickingInfos = new Array();
  28267. for (var meshIndex = 0; meshIndex < this.meshes.length; meshIndex++) {
  28268. var mesh = this.meshes[meshIndex];
  28269. if (predicate) {
  28270. if (!predicate(mesh)) {
  28271. continue;
  28272. }
  28273. }
  28274. else if (!mesh.isEnabled() || !mesh.isVisible || !mesh.isPickable) {
  28275. continue;
  28276. }
  28277. var world = mesh.getWorldMatrix();
  28278. var ray = rayFunction(world);
  28279. var result = mesh.intersects(ray, false);
  28280. if (!result || !result.hit)
  28281. continue;
  28282. pickingInfos.push(result);
  28283. }
  28284. return pickingInfos;
  28285. };
  28286. Scene.prototype._internalPickSprites = function (ray, predicate, fastCheck, camera) {
  28287. if (!BABYLON.PickingInfo) {
  28288. return null;
  28289. }
  28290. var pickingInfo = null;
  28291. if (!camera) {
  28292. if (!this.activeCamera) {
  28293. return null;
  28294. }
  28295. camera = this.activeCamera;
  28296. }
  28297. if (this.spriteManagers.length > 0) {
  28298. for (var spriteIndex = 0; spriteIndex < this.spriteManagers.length; spriteIndex++) {
  28299. var spriteManager = this.spriteManagers[spriteIndex];
  28300. if (!spriteManager.isPickable) {
  28301. continue;
  28302. }
  28303. var result = spriteManager.intersects(ray, camera, predicate, fastCheck);
  28304. if (!result || !result.hit)
  28305. continue;
  28306. if (!fastCheck && pickingInfo != null && result.distance >= pickingInfo.distance)
  28307. continue;
  28308. pickingInfo = result;
  28309. if (fastCheck) {
  28310. break;
  28311. }
  28312. }
  28313. }
  28314. return pickingInfo || new BABYLON.PickingInfo();
  28315. };
  28316. /** Launch a ray to try to pick a mesh in the scene
  28317. * @param x position on screen
  28318. * @param y position on screen
  28319. * @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
  28320. * @param fastCheck Launch a fast check only using the bounding boxes. Can be set to null.
  28321. * @param camera to use for computing the picking ray. Can be set to null. In this case, the scene.activeCamera will be used
  28322. * @returns a PickingInfo
  28323. */
  28324. Scene.prototype.pick = function (x, y, predicate, fastCheck, camera) {
  28325. var _this = this;
  28326. if (!BABYLON.PickingInfo) {
  28327. return null;
  28328. }
  28329. return this._internalPick(function (world) {
  28330. _this.createPickingRayToRef(x, y, world, _this._tempPickingRay, camera || null);
  28331. return _this._tempPickingRay;
  28332. }, predicate, fastCheck);
  28333. };
  28334. /** Launch a ray to try to pick a sprite in the scene
  28335. * @param x position on screen
  28336. * @param y position on screen
  28337. * @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
  28338. * @param fastCheck Launch a fast check only using the bounding boxes. Can be set to null.
  28339. * @param camera camera to use for computing the picking ray. Can be set to null. In this case, the scene.activeCamera will be used
  28340. * @returns a PickingInfo
  28341. */
  28342. Scene.prototype.pickSprite = function (x, y, predicate, fastCheck, camera) {
  28343. this.createPickingRayInCameraSpaceToRef(x, y, this._tempPickingRay, camera);
  28344. return this._internalPickSprites(this._tempPickingRay, predicate, fastCheck, camera);
  28345. };
  28346. /** Use the given ray to pick a mesh in the scene
  28347. * @param ray The ray to use to pick meshes
  28348. * @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
  28349. * @param fastCheck Launch a fast check only using the bounding boxes. Can be set to null
  28350. * @returns a PickingInfo
  28351. */
  28352. Scene.prototype.pickWithRay = function (ray, predicate, fastCheck) {
  28353. var _this = this;
  28354. return this._internalPick(function (world) {
  28355. if (!_this._pickWithRayInverseMatrix) {
  28356. _this._pickWithRayInverseMatrix = BABYLON.Matrix.Identity();
  28357. }
  28358. world.invertToRef(_this._pickWithRayInverseMatrix);
  28359. if (!_this._cachedRayForTransform) {
  28360. _this._cachedRayForTransform = BABYLON.Ray.Zero();
  28361. }
  28362. BABYLON.Ray.TransformToRef(ray, _this._pickWithRayInverseMatrix, _this._cachedRayForTransform);
  28363. return _this._cachedRayForTransform;
  28364. }, predicate, fastCheck);
  28365. };
  28366. /**
  28367. * Launch a ray to try to pick a mesh in the scene
  28368. * @param x X position on screen
  28369. * @param y Y position on screen
  28370. * @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
  28371. * @param camera camera to use for computing the picking ray. Can be set to null. In this case, the scene.activeCamera will be used
  28372. * @returns an array of PickingInfo
  28373. */
  28374. Scene.prototype.multiPick = function (x, y, predicate, camera) {
  28375. var _this = this;
  28376. return this._internalMultiPick(function (world) { return _this.createPickingRay(x, y, world, camera || null); }, predicate);
  28377. };
  28378. /**
  28379. * Launch a ray to try to pick a mesh in the scene
  28380. * @param ray Ray to use
  28381. * @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
  28382. * @returns an array of PickingInfo
  28383. */
  28384. Scene.prototype.multiPickWithRay = function (ray, predicate) {
  28385. var _this = this;
  28386. return this._internalMultiPick(function (world) {
  28387. if (!_this._pickWithRayInverseMatrix) {
  28388. _this._pickWithRayInverseMatrix = BABYLON.Matrix.Identity();
  28389. }
  28390. world.invertToRef(_this._pickWithRayInverseMatrix);
  28391. if (!_this._cachedRayForTransform) {
  28392. _this._cachedRayForTransform = BABYLON.Ray.Zero();
  28393. }
  28394. BABYLON.Ray.TransformToRef(ray, _this._pickWithRayInverseMatrix, _this._cachedRayForTransform);
  28395. return _this._cachedRayForTransform;
  28396. }, predicate);
  28397. };
  28398. /**
  28399. * Force the value of meshUnderPointer
  28400. * @param mesh defines the mesh to use
  28401. */
  28402. Scene.prototype.setPointerOverMesh = function (mesh) {
  28403. if (this._pointerOverMesh === mesh) {
  28404. return;
  28405. }
  28406. if (this._pointerOverMesh && this._pointerOverMesh.actionManager) {
  28407. this._pointerOverMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOutTrigger, BABYLON.ActionEvent.CreateNew(this._pointerOverMesh));
  28408. }
  28409. this._pointerOverMesh = mesh;
  28410. if (this._pointerOverMesh && this._pointerOverMesh.actionManager) {
  28411. this._pointerOverMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOverTrigger, BABYLON.ActionEvent.CreateNew(this._pointerOverMesh));
  28412. }
  28413. };
  28414. /**
  28415. * Gets the mesh under the pointer
  28416. * @returns a Mesh or null if no mesh is under the pointer
  28417. */
  28418. Scene.prototype.getPointerOverMesh = function () {
  28419. return this._pointerOverMesh;
  28420. };
  28421. /**
  28422. * Force the sprite under the pointer
  28423. * @param sprite defines the sprite to use
  28424. */
  28425. Scene.prototype.setPointerOverSprite = function (sprite) {
  28426. if (this._pointerOverSprite === sprite) {
  28427. return;
  28428. }
  28429. if (this._pointerOverSprite && this._pointerOverSprite.actionManager) {
  28430. this._pointerOverSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOutTrigger, BABYLON.ActionEvent.CreateNewFromSprite(this._pointerOverSprite, this));
  28431. }
  28432. this._pointerOverSprite = sprite;
  28433. if (this._pointerOverSprite && this._pointerOverSprite.actionManager) {
  28434. this._pointerOverSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOverTrigger, BABYLON.ActionEvent.CreateNewFromSprite(this._pointerOverSprite, this));
  28435. }
  28436. };
  28437. /**
  28438. * Gets the sprite under the pointer
  28439. * @returns a Sprite or null if no sprite is under the pointer
  28440. */
  28441. Scene.prototype.getPointerOverSprite = function () {
  28442. return this._pointerOverSprite;
  28443. };
  28444. // Physics
  28445. /**
  28446. * Gets the current physics engine
  28447. * @returns a PhysicsEngine or null if none attached
  28448. */
  28449. Scene.prototype.getPhysicsEngine = function () {
  28450. return this._physicsEngine;
  28451. };
  28452. /**
  28453. * Enables physics to the current scene
  28454. * @param gravity defines the scene's gravity for the physics engine
  28455. * @param plugin defines the physics engine to be used. defaults to OimoJS.
  28456. * @return a boolean indicating if the physics engine was initialized
  28457. */
  28458. Scene.prototype.enablePhysics = function (gravity, plugin) {
  28459. if (gravity === void 0) { gravity = null; }
  28460. if (this._physicsEngine) {
  28461. return true;
  28462. }
  28463. try {
  28464. this._physicsEngine = new BABYLON.PhysicsEngine(gravity, plugin);
  28465. return true;
  28466. }
  28467. catch (e) {
  28468. BABYLON.Tools.Error(e.message);
  28469. return false;
  28470. }
  28471. };
  28472. /**
  28473. * Disables and disposes the physics engine associated with the scene
  28474. */
  28475. Scene.prototype.disablePhysicsEngine = function () {
  28476. if (!this._physicsEngine) {
  28477. return;
  28478. }
  28479. this._physicsEngine.dispose();
  28480. this._physicsEngine = null;
  28481. };
  28482. /**
  28483. * Gets a boolean indicating if there is an active physics engine
  28484. * @returns a boolean indicating if there is an active physics engine
  28485. */
  28486. Scene.prototype.isPhysicsEnabled = function () {
  28487. return this._physicsEngine !== undefined;
  28488. };
  28489. /**
  28490. * Deletes a physics compound impostor
  28491. * @param compound defines the compound to delete
  28492. */
  28493. Scene.prototype.deleteCompoundImpostor = function (compound) {
  28494. var mesh = compound.parts[0].mesh;
  28495. if (mesh.physicsImpostor) {
  28496. mesh.physicsImpostor.dispose( /*true*/);
  28497. mesh.physicsImpostor = null;
  28498. }
  28499. };
  28500. // Misc.
  28501. /** @hidden */
  28502. Scene.prototype._rebuildGeometries = function () {
  28503. for (var _i = 0, _a = this._geometries; _i < _a.length; _i++) {
  28504. var geometry = _a[_i];
  28505. geometry._rebuild();
  28506. }
  28507. for (var _b = 0, _c = this.meshes; _b < _c.length; _b++) {
  28508. var mesh = _c[_b];
  28509. mesh._rebuild();
  28510. }
  28511. if (this.postProcessManager) {
  28512. this.postProcessManager._rebuild();
  28513. }
  28514. for (var _d = 0, _e = this.layers; _d < _e.length; _d++) {
  28515. var layer = _e[_d];
  28516. layer._rebuild();
  28517. }
  28518. for (var _f = 0, _g = this.effectLayers; _f < _g.length; _f++) {
  28519. var effectLayer = _g[_f];
  28520. effectLayer._rebuild();
  28521. }
  28522. if (this._boundingBoxRenderer) {
  28523. this._boundingBoxRenderer._rebuild();
  28524. }
  28525. for (var _h = 0, _j = this.particleSystems; _h < _j.length; _h++) {
  28526. var system = _j[_h];
  28527. system.rebuild();
  28528. }
  28529. if (this._postProcessRenderPipelineManager) {
  28530. this._postProcessRenderPipelineManager._rebuild();
  28531. }
  28532. };
  28533. /** @hidden */
  28534. Scene.prototype._rebuildTextures = function () {
  28535. for (var _i = 0, _a = this.textures; _i < _a.length; _i++) {
  28536. var texture = _a[_i];
  28537. texture._rebuild();
  28538. }
  28539. this.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  28540. };
  28541. /**
  28542. * Creates a default light for the scene.
  28543. * @param replace Whether to replace the existing lights in the scene.
  28544. */
  28545. Scene.prototype.createDefaultLight = function (replace) {
  28546. if (replace === void 0) { replace = false; }
  28547. // Dispose existing light in replace mode.
  28548. if (replace) {
  28549. if (this.lights) {
  28550. for (var i = 0; i < this.lights.length; i++) {
  28551. this.lights[i].dispose();
  28552. }
  28553. }
  28554. }
  28555. // Light
  28556. if (this.lights.length === 0) {
  28557. new BABYLON.HemisphericLight("default light", BABYLON.Vector3.Up(), this);
  28558. }
  28559. };
  28560. /**
  28561. * Creates a default camera for the scene.
  28562. * @param createArcRotateCamera Whether to create an arc rotate or a free camera.
  28563. * @param replace Whether to replace the existing active camera in the scene.
  28564. * @param attachCameraControls Whether to attach camera controls to the canvas.
  28565. */
  28566. Scene.prototype.createDefaultCamera = function (createArcRotateCamera, replace, attachCameraControls) {
  28567. if (createArcRotateCamera === void 0) { createArcRotateCamera = false; }
  28568. if (replace === void 0) { replace = false; }
  28569. if (attachCameraControls === void 0) { attachCameraControls = false; }
  28570. // Dispose existing camera in replace mode.
  28571. if (replace) {
  28572. if (this.activeCamera) {
  28573. this.activeCamera.dispose();
  28574. this.activeCamera = null;
  28575. }
  28576. }
  28577. // Camera
  28578. if (!this.activeCamera) {
  28579. var worldExtends = this.getWorldExtends();
  28580. var worldSize = worldExtends.max.subtract(worldExtends.min);
  28581. var worldCenter = worldExtends.min.add(worldSize.scale(0.5));
  28582. var camera;
  28583. var radius = worldSize.length() * 1.5;
  28584. // empty scene scenario!
  28585. if (!isFinite(radius)) {
  28586. radius = 1;
  28587. worldCenter.copyFromFloats(0, 0, 0);
  28588. }
  28589. if (createArcRotateCamera) {
  28590. var arcRotateCamera = new BABYLON.ArcRotateCamera("default camera", -(Math.PI / 2), Math.PI / 2, radius, worldCenter, this);
  28591. arcRotateCamera.lowerRadiusLimit = radius * 0.01;
  28592. arcRotateCamera.wheelPrecision = 100 / radius;
  28593. camera = arcRotateCamera;
  28594. }
  28595. else {
  28596. var freeCamera = new BABYLON.FreeCamera("default camera", new BABYLON.Vector3(worldCenter.x, worldCenter.y, -radius), this);
  28597. freeCamera.setTarget(worldCenter);
  28598. camera = freeCamera;
  28599. }
  28600. camera.minZ = radius * 0.01;
  28601. camera.maxZ = radius * 1000;
  28602. camera.speed = radius * 0.2;
  28603. this.activeCamera = camera;
  28604. var canvas = this.getEngine().getRenderingCanvas();
  28605. if (attachCameraControls && canvas) {
  28606. camera.attachControl(canvas);
  28607. }
  28608. }
  28609. };
  28610. /**
  28611. * Creates a default camera and a default light
  28612. * @param createArcRotateCamera defines that the camera will be an ArcRotateCamera
  28613. * @param replace defines if the camera and/or light will replace the existing ones
  28614. * @param attachCameraControls defines if attachControl will be called on the new camera
  28615. */
  28616. Scene.prototype.createDefaultCameraOrLight = function (createArcRotateCamera, replace, attachCameraControls) {
  28617. if (createArcRotateCamera === void 0) { createArcRotateCamera = false; }
  28618. if (replace === void 0) { replace = false; }
  28619. if (attachCameraControls === void 0) { attachCameraControls = false; }
  28620. this.createDefaultLight(replace);
  28621. this.createDefaultCamera(createArcRotateCamera, replace, attachCameraControls);
  28622. };
  28623. /**
  28624. * Creates a new sky box
  28625. * @see http://doc.babylonjs.com/babylon101/environment#skybox
  28626. * @param environmentTexture defines the texture to use as environment texture
  28627. * @param pbr defines if PBRMaterial must be used instead of StandardMaterial
  28628. * @param scale defines the overall scale of the skybox
  28629. * @param blur defines if blurring must be applied to the environment texture (works only with pbr === true)
  28630. * @param setGlobalEnvTexture defines a boolean indicating that scene.environmentTexture must match the current skybox texture (true by default)
  28631. * @returns a new mesh holding the sky box
  28632. */
  28633. Scene.prototype.createDefaultSkybox = function (environmentTexture, pbr, scale, blur, setGlobalEnvTexture) {
  28634. if (pbr === void 0) { pbr = false; }
  28635. if (scale === void 0) { scale = 1000; }
  28636. if (blur === void 0) { blur = 0; }
  28637. if (setGlobalEnvTexture === void 0) { setGlobalEnvTexture = true; }
  28638. if (!environmentTexture) {
  28639. BABYLON.Tools.Warn("Can not create default skybox without environment texture.");
  28640. return null;
  28641. }
  28642. if (setGlobalEnvTexture) {
  28643. if (environmentTexture) {
  28644. this.environmentTexture = environmentTexture;
  28645. }
  28646. }
  28647. // Skybox
  28648. var hdrSkybox = BABYLON.Mesh.CreateBox("hdrSkyBox", scale, this);
  28649. if (pbr) {
  28650. var hdrSkyboxMaterial = new BABYLON.PBRMaterial("skyBox", this);
  28651. hdrSkyboxMaterial.backFaceCulling = false;
  28652. hdrSkyboxMaterial.reflectionTexture = environmentTexture.clone();
  28653. if (hdrSkyboxMaterial.reflectionTexture) {
  28654. hdrSkyboxMaterial.reflectionTexture.coordinatesMode = BABYLON.Texture.SKYBOX_MODE;
  28655. }
  28656. hdrSkyboxMaterial.microSurface = 1.0 - blur;
  28657. hdrSkyboxMaterial.disableLighting = true;
  28658. hdrSkyboxMaterial.twoSidedLighting = true;
  28659. hdrSkybox.infiniteDistance = true;
  28660. hdrSkybox.material = hdrSkyboxMaterial;
  28661. }
  28662. else {
  28663. var skyboxMaterial = new BABYLON.StandardMaterial("skyBox", this);
  28664. skyboxMaterial.backFaceCulling = false;
  28665. skyboxMaterial.reflectionTexture = environmentTexture.clone();
  28666. if (skyboxMaterial.reflectionTexture) {
  28667. skyboxMaterial.reflectionTexture.coordinatesMode = BABYLON.Texture.SKYBOX_MODE;
  28668. }
  28669. skyboxMaterial.disableLighting = true;
  28670. hdrSkybox.infiniteDistance = true;
  28671. hdrSkybox.material = skyboxMaterial;
  28672. }
  28673. return hdrSkybox;
  28674. };
  28675. /**
  28676. * Creates a new environment
  28677. * @see http://doc.babylonjs.com/babylon101/environment#skybox
  28678. * @param options defines the options you can use to configure the environment
  28679. * @returns the new EnvironmentHelper
  28680. */
  28681. Scene.prototype.createDefaultEnvironment = function (options) {
  28682. if (BABYLON.EnvironmentHelper) {
  28683. return new BABYLON.EnvironmentHelper(options, this);
  28684. }
  28685. return null;
  28686. };
  28687. /**
  28688. * Creates a new VREXperienceHelper
  28689. * @see http://doc.babylonjs.com/how_to/webvr_helper
  28690. * @param webVROptions defines the options used to create the new VREXperienceHelper
  28691. * @returns a new VREXperienceHelper
  28692. */
  28693. Scene.prototype.createDefaultVRExperience = function (webVROptions) {
  28694. if (webVROptions === void 0) { webVROptions = {}; }
  28695. return new BABYLON.VRExperienceHelper(this, webVROptions);
  28696. };
  28697. // Tags
  28698. Scene.prototype._getByTags = function (list, tagsQuery, forEach) {
  28699. if (tagsQuery === undefined) {
  28700. // returns the complete list (could be done with BABYLON.Tags.MatchesQuery but no need to have a for-loop here)
  28701. return list;
  28702. }
  28703. var listByTags = [];
  28704. forEach = forEach || (function (item) { return; });
  28705. for (var i in list) {
  28706. var item = list[i];
  28707. if (BABYLON.Tags && BABYLON.Tags.MatchesQuery(item, tagsQuery)) {
  28708. listByTags.push(item);
  28709. forEach(item);
  28710. }
  28711. }
  28712. return listByTags;
  28713. };
  28714. /**
  28715. * Get a list of meshes by tags
  28716. * @param tagsQuery defines the tags query to use
  28717. * @param forEach defines a predicate used to filter results
  28718. * @returns an array of Mesh
  28719. */
  28720. Scene.prototype.getMeshesByTags = function (tagsQuery, forEach) {
  28721. return this._getByTags(this.meshes, tagsQuery, forEach);
  28722. };
  28723. /**
  28724. * Get a list of cameras by tags
  28725. * @param tagsQuery defines the tags query to use
  28726. * @param forEach defines a predicate used to filter results
  28727. * @returns an array of Camera
  28728. */
  28729. Scene.prototype.getCamerasByTags = function (tagsQuery, forEach) {
  28730. return this._getByTags(this.cameras, tagsQuery, forEach);
  28731. };
  28732. /**
  28733. * Get a list of lights by tags
  28734. * @param tagsQuery defines the tags query to use
  28735. * @param forEach defines a predicate used to filter results
  28736. * @returns an array of Light
  28737. */
  28738. Scene.prototype.getLightsByTags = function (tagsQuery, forEach) {
  28739. return this._getByTags(this.lights, tagsQuery, forEach);
  28740. };
  28741. /**
  28742. * Get a list of materials by tags
  28743. * @param tagsQuery defines the tags query to use
  28744. * @param forEach defines a predicate used to filter results
  28745. * @returns an array of Material
  28746. */
  28747. Scene.prototype.getMaterialByTags = function (tagsQuery, forEach) {
  28748. return this._getByTags(this.materials, tagsQuery, forEach).concat(this._getByTags(this.multiMaterials, tagsQuery, forEach));
  28749. };
  28750. /**
  28751. * Overrides the default sort function applied in the renderging group to prepare the meshes.
  28752. * This allowed control for front to back rendering or reversly depending of the special needs.
  28753. *
  28754. * @param renderingGroupId The rendering group id corresponding to its index
  28755. * @param opaqueSortCompareFn The opaque queue comparison function use to sort.
  28756. * @param alphaTestSortCompareFn The alpha test queue comparison function use to sort.
  28757. * @param transparentSortCompareFn The transparent queue comparison function use to sort.
  28758. */
  28759. Scene.prototype.setRenderingOrder = function (renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn) {
  28760. if (opaqueSortCompareFn === void 0) { opaqueSortCompareFn = null; }
  28761. if (alphaTestSortCompareFn === void 0) { alphaTestSortCompareFn = null; }
  28762. if (transparentSortCompareFn === void 0) { transparentSortCompareFn = null; }
  28763. this._renderingManager.setRenderingOrder(renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn);
  28764. };
  28765. /**
  28766. * Specifies whether or not the stencil and depth buffer are cleared between two rendering groups.
  28767. *
  28768. * @param renderingGroupId The rendering group id corresponding to its index
  28769. * @param autoClearDepthStencil Automatically clears depth and stencil between groups if true.
  28770. * @param depth Automatically clears depth between groups if true and autoClear is true.
  28771. * @param stencil Automatically clears stencil between groups if true and autoClear is true.
  28772. */
  28773. Scene.prototype.setRenderingAutoClearDepthStencil = function (renderingGroupId, autoClearDepthStencil, depth, stencil) {
  28774. if (depth === void 0) { depth = true; }
  28775. if (stencil === void 0) { stencil = true; }
  28776. this._renderingManager.setRenderingAutoClearDepthStencil(renderingGroupId, autoClearDepthStencil, depth, stencil);
  28777. };
  28778. /**
  28779. * Will flag all materials as dirty to trigger new shader compilation
  28780. * @param flag defines the flag used to specify which material part must be marked as dirty
  28781. * @param predicate If not null, it will be used to specifiy if a material has to be marked as dirty
  28782. */
  28783. Scene.prototype.markAllMaterialsAsDirty = function (flag, predicate) {
  28784. for (var _i = 0, _a = this.materials; _i < _a.length; _i++) {
  28785. var material = _a[_i];
  28786. if (predicate && !predicate(material)) {
  28787. continue;
  28788. }
  28789. material.markAsDirty(flag);
  28790. }
  28791. };
  28792. /** @hidden */
  28793. Scene.prototype._loadFile = function (url, onSuccess, onProgress, useDatabase, useArrayBuffer, onError) {
  28794. var _this = this;
  28795. var request = BABYLON.Tools.LoadFile(url, onSuccess, onProgress, useDatabase ? this.database : undefined, useArrayBuffer, onError);
  28796. this._activeRequests.push(request);
  28797. request.onCompleteObservable.add(function (request) {
  28798. _this._activeRequests.splice(_this._activeRequests.indexOf(request), 1);
  28799. });
  28800. return request;
  28801. };
  28802. /** @hidden */
  28803. Scene.prototype._loadFileAsync = function (url, useDatabase, useArrayBuffer) {
  28804. var _this = this;
  28805. return new Promise(function (resolve, reject) {
  28806. _this._loadFile(url, function (data) {
  28807. resolve(data);
  28808. }, undefined, useDatabase, useArrayBuffer, function (request, exception) {
  28809. reject(exception);
  28810. });
  28811. });
  28812. };
  28813. // Statics
  28814. Scene._FOGMODE_NONE = 0;
  28815. Scene._FOGMODE_EXP = 1;
  28816. Scene._FOGMODE_EXP2 = 2;
  28817. Scene._FOGMODE_LINEAR = 3;
  28818. Scene._uniqueIdCounter = 0;
  28819. /**
  28820. * Gets or sets the minimum deltatime when deterministic lock step is enabled
  28821. * @see http://doc.babylonjs.com/babylon101/animations#deterministic-lockstep
  28822. */
  28823. Scene.MinDeltaTime = 1.0;
  28824. /**
  28825. * Gets or sets the maximum deltatime when deterministic lock step is enabled
  28826. * @see http://doc.babylonjs.com/babylon101/animations#deterministic-lockstep
  28827. */
  28828. Scene.MaxDeltaTime = 1000.0;
  28829. /** The distance in pixel that you have to move to prevent some events */
  28830. Scene.DragMovementThreshold = 10; // in pixels
  28831. /** Time in milliseconds to wait to raise long press events if button is still pressed */
  28832. Scene.LongPressDelay = 500; // in milliseconds
  28833. /** Time in milliseconds with two consecutive clicks will be considered as a double click */
  28834. Scene.DoubleClickDelay = 300; // in milliseconds
  28835. /** If you need to check double click without raising a single click at first click, enable this flag */
  28836. Scene.ExclusiveDoubleClickMode = false;
  28837. return Scene;
  28838. }());
  28839. BABYLON.Scene = Scene;
  28840. })(BABYLON || (BABYLON = {}));
  28841. //# sourceMappingURL=babylon.scene.js.map
  28842. var BABYLON;
  28843. (function (BABYLON) {
  28844. /**
  28845. * Set of assets to keep when moving a scene into an asset container.
  28846. */
  28847. var KeepAssets = /** @class */ (function () {
  28848. function KeepAssets() {
  28849. /**
  28850. * Cameras to keep.
  28851. */
  28852. this.cameras = new Array();
  28853. /**
  28854. * Lights to keep.
  28855. */
  28856. this.lights = new Array();
  28857. /**
  28858. * Meshes to keep.
  28859. */
  28860. this.meshes = new Array();
  28861. /**
  28862. * Skeletons to keep.
  28863. */
  28864. this.skeletons = new Array();
  28865. /**
  28866. * ParticleSystems to keep.
  28867. */
  28868. this.particleSystems = new Array();
  28869. /**
  28870. * Animations to keep.
  28871. */
  28872. this.animations = new Array();
  28873. /**
  28874. * AnimationGroups to keep.
  28875. */
  28876. this.animationGroups = new Array();
  28877. /**
  28878. * MultiMaterials to keep.
  28879. */
  28880. this.multiMaterials = new Array();
  28881. /**
  28882. * Materials to keep.
  28883. */
  28884. this.materials = new Array();
  28885. /**
  28886. * MorphTargetManagers to keep.
  28887. */
  28888. this.morphTargetManagers = new Array();
  28889. /**
  28890. * Geometries to keep.
  28891. */
  28892. this.geometries = new Array();
  28893. /**
  28894. * TransformNodes to keep.
  28895. */
  28896. this.transformNodes = new Array();
  28897. /**
  28898. * LensFlareSystems to keep.
  28899. */
  28900. this.lensFlareSystems = new Array();
  28901. /**
  28902. * ShadowGenerators to keep.
  28903. */
  28904. this.shadowGenerators = new Array();
  28905. /**
  28906. * ActionManagers to keep.
  28907. */
  28908. this.actionManagers = new Array();
  28909. /**
  28910. * Sounds to keep.
  28911. */
  28912. this.sounds = new Array();
  28913. /**
  28914. * Textures to keep.
  28915. */
  28916. this.textures = new Array();
  28917. /**
  28918. * Effect layers to keep.
  28919. */
  28920. this.effectLayers = new Array();
  28921. }
  28922. return KeepAssets;
  28923. }());
  28924. BABYLON.KeepAssets = KeepAssets;
  28925. /**
  28926. * Container with a set of assets that can be added or removed from a scene.
  28927. */
  28928. var AssetContainer = /** @class */ (function () {
  28929. /**
  28930. * Instantiates an AssetContainer.
  28931. * @param scene The scene the AssetContainer belongs to.
  28932. */
  28933. function AssetContainer(scene) {
  28934. // Objects
  28935. /**
  28936. * Cameras populated in the container.
  28937. */
  28938. this.cameras = new Array();
  28939. /**
  28940. * Lights populated in the container.
  28941. */
  28942. this.lights = new Array();
  28943. /**
  28944. * Meshes populated in the container.
  28945. */
  28946. this.meshes = new Array();
  28947. /**
  28948. * Skeletons populated in the container.
  28949. */
  28950. this.skeletons = new Array();
  28951. /**
  28952. * ParticleSystems populated in the container.
  28953. */
  28954. this.particleSystems = new Array();
  28955. /**
  28956. * Animations populated in the container.
  28957. */
  28958. this.animations = new Array();
  28959. /**
  28960. * AnimationGroups populated in the container.
  28961. */
  28962. this.animationGroups = new Array();
  28963. /**
  28964. * MultiMaterials populated in the container.
  28965. */
  28966. this.multiMaterials = new Array();
  28967. /**
  28968. * Materials populated in the container.
  28969. */
  28970. this.materials = new Array();
  28971. /**
  28972. * MorphTargetManagers populated in the container.
  28973. */
  28974. this.morphTargetManagers = new Array();
  28975. /**
  28976. * Geometries populated in the container.
  28977. */
  28978. this.geometries = new Array();
  28979. /**
  28980. * TransformNodes populated in the container.
  28981. */
  28982. this.transformNodes = new Array();
  28983. /**
  28984. * LensFlareSystems populated in the container.
  28985. */
  28986. this.lensFlareSystems = new Array();
  28987. /**
  28988. * ShadowGenerators populated in the container.
  28989. */
  28990. this.shadowGenerators = new Array();
  28991. /**
  28992. * ActionManagers populated in the container.
  28993. */
  28994. this.actionManagers = new Array();
  28995. /**
  28996. * Sounds populated in the container.
  28997. */
  28998. this.sounds = new Array();
  28999. /**
  29000. * Textures populated in the container.
  29001. */
  29002. this.textures = new Array();
  29003. /**
  29004. * Effect layers populated in the container.
  29005. */
  29006. this.effectLayers = new Array();
  29007. this.scene = scene;
  29008. }
  29009. /**
  29010. * Adds all the assets from the container to the scene.
  29011. */
  29012. AssetContainer.prototype.addAllToScene = function () {
  29013. var _this = this;
  29014. this.cameras.forEach(function (o) {
  29015. _this.scene.addCamera(o);
  29016. });
  29017. this.lights.forEach(function (o) {
  29018. _this.scene.addLight(o);
  29019. });
  29020. this.meshes.forEach(function (o) {
  29021. _this.scene.addMesh(o);
  29022. });
  29023. this.skeletons.forEach(function (o) {
  29024. _this.scene.addSkeleton(o);
  29025. });
  29026. this.particleSystems.forEach(function (o) {
  29027. _this.scene.addParticleSystem(o);
  29028. });
  29029. this.animations.forEach(function (o) {
  29030. _this.scene.addAnimation(o);
  29031. });
  29032. this.animationGroups.forEach(function (o) {
  29033. _this.scene.addAnimationGroup(o);
  29034. });
  29035. this.multiMaterials.forEach(function (o) {
  29036. _this.scene.addMultiMaterial(o);
  29037. });
  29038. this.materials.forEach(function (o) {
  29039. _this.scene.addMaterial(o);
  29040. });
  29041. this.morphTargetManagers.forEach(function (o) {
  29042. _this.scene.addMorphTargetManager(o);
  29043. });
  29044. this.geometries.forEach(function (o) {
  29045. _this.scene.addGeometry(o);
  29046. });
  29047. this.transformNodes.forEach(function (o) {
  29048. _this.scene.addTransformNode(o);
  29049. });
  29050. this.lensFlareSystems.forEach(function (o) {
  29051. _this.scene.addLensFlareSystem(o);
  29052. });
  29053. this.actionManagers.forEach(function (o) {
  29054. _this.scene.addActionManager(o);
  29055. });
  29056. this.sounds.forEach(function (o) {
  29057. o.play();
  29058. o.autoplay = true;
  29059. _this.scene.mainSoundTrack.AddSound(o);
  29060. });
  29061. this.textures.forEach(function (o) {
  29062. _this.scene.addTexture(o);
  29063. });
  29064. this.effectLayers.forEach(function (o) {
  29065. _this.scene.addEffectLayer(o);
  29066. });
  29067. };
  29068. /**
  29069. * Removes all the assets in the container from the scene
  29070. */
  29071. AssetContainer.prototype.removeAllFromScene = function () {
  29072. var _this = this;
  29073. this.cameras.forEach(function (o) {
  29074. _this.scene.removeCamera(o);
  29075. });
  29076. this.lights.forEach(function (o) {
  29077. _this.scene.removeLight(o);
  29078. });
  29079. this.meshes.forEach(function (o) {
  29080. _this.scene.removeMesh(o);
  29081. });
  29082. this.skeletons.forEach(function (o) {
  29083. _this.scene.removeSkeleton(o);
  29084. });
  29085. this.particleSystems.forEach(function (o) {
  29086. _this.scene.removeParticleSystem(o);
  29087. });
  29088. this.animations.forEach(function (o) {
  29089. _this.scene.removeAnimation(o);
  29090. });
  29091. this.animationGroups.forEach(function (o) {
  29092. _this.scene.removeAnimationGroup(o);
  29093. });
  29094. this.multiMaterials.forEach(function (o) {
  29095. _this.scene.removeMultiMaterial(o);
  29096. });
  29097. this.materials.forEach(function (o) {
  29098. _this.scene.removeMaterial(o);
  29099. });
  29100. this.morphTargetManagers.forEach(function (o) {
  29101. _this.scene.removeMorphTargetManager(o);
  29102. });
  29103. this.geometries.forEach(function (o) {
  29104. _this.scene.removeGeometry(o);
  29105. });
  29106. this.transformNodes.forEach(function (o) {
  29107. _this.scene.removeTransformNode(o);
  29108. });
  29109. this.lensFlareSystems.forEach(function (o) {
  29110. _this.scene.removeLensFlareSystem(o);
  29111. });
  29112. this.actionManagers.forEach(function (o) {
  29113. _this.scene.removeActionManager(o);
  29114. });
  29115. this.sounds.forEach(function (o) {
  29116. o.stop();
  29117. o.autoplay = false;
  29118. _this.scene.mainSoundTrack.RemoveSound(o);
  29119. });
  29120. this.textures.forEach(function (o) {
  29121. _this.scene.removeTexture(o);
  29122. });
  29123. this.effectLayers.forEach(function (o) {
  29124. _this.scene.removeEffectLayer(o);
  29125. });
  29126. };
  29127. AssetContainer.prototype._moveAssets = function (sourceAssets, targetAssets, keepAssets) {
  29128. for (var _i = 0, sourceAssets_1 = sourceAssets; _i < sourceAssets_1.length; _i++) {
  29129. var asset = sourceAssets_1[_i];
  29130. var move = true;
  29131. for (var _a = 0, keepAssets_1 = keepAssets; _a < keepAssets_1.length; _a++) {
  29132. var keepAsset = keepAssets_1[_a];
  29133. if (asset === keepAsset) {
  29134. move = false;
  29135. break;
  29136. }
  29137. }
  29138. if (move) {
  29139. targetAssets.push(asset);
  29140. }
  29141. }
  29142. };
  29143. /**
  29144. * Removes all the assets contained in the scene and adds them to the container.
  29145. * @param keepAssets Set of assets to keep in the scene. (default: empty)
  29146. */
  29147. AssetContainer.prototype.moveAllFromScene = function (keepAssets) {
  29148. if (keepAssets === undefined) {
  29149. keepAssets = new KeepAssets();
  29150. }
  29151. this._moveAssets(this.scene.cameras, this.cameras, keepAssets.cameras);
  29152. this._moveAssets(this.scene.meshes, this.meshes, keepAssets.meshes);
  29153. this._moveAssets(this.scene.getGeometries(), this.geometries, keepAssets.geometries);
  29154. this._moveAssets(this.scene.materials, this.materials, keepAssets.materials);
  29155. this._moveAssets(this.scene._actionManagers, this.actionManagers, keepAssets.actionManagers);
  29156. this._moveAssets(this.scene.animations, this.animations, keepAssets.animations);
  29157. this._moveAssets(this.scene.animationGroups, this.animationGroups, keepAssets.animationGroups);
  29158. this._moveAssets(this.scene.lensFlareSystems, this.lensFlareSystems, keepAssets.lensFlareSystems);
  29159. this._moveAssets(this.scene.lights, this.lights, keepAssets.lights);
  29160. this._moveAssets(this.scene.morphTargetManagers, this.morphTargetManagers, keepAssets.morphTargetManagers);
  29161. this._moveAssets(this.scene.multiMaterials, this.multiMaterials, keepAssets.multiMaterials);
  29162. this._moveAssets(this.scene.skeletons, this.skeletons, keepAssets.skeletons);
  29163. this._moveAssets(this.scene.particleSystems, this.particleSystems, keepAssets.particleSystems);
  29164. this._moveAssets(this.scene.mainSoundTrack.soundCollection, this.sounds, keepAssets.sounds);
  29165. this._moveAssets(this.scene.transformNodes, this.transformNodes, keepAssets.transformNodes);
  29166. this._moveAssets(this.scene.textures, this.textures, keepAssets.textures);
  29167. this._moveAssets(this.scene.effectLayers, this.effectLayers, keepAssets.effectLayers);
  29168. this.removeAllFromScene();
  29169. };
  29170. return AssetContainer;
  29171. }());
  29172. BABYLON.AssetContainer = AssetContainer;
  29173. })(BABYLON || (BABYLON = {}));
  29174. //# sourceMappingURL=babylon.assetContainer.js.map
  29175. var BABYLON;
  29176. (function (BABYLON) {
  29177. var Buffer = /** @class */ (function () {
  29178. /**
  29179. * Constructor
  29180. * @param engine the engine
  29181. * @param data the data to use for this buffer
  29182. * @param updatable whether the data is updatable
  29183. * @param stride the stride (optional)
  29184. * @param postponeInternalCreation whether to postpone creating the internal WebGL buffer (optional)
  29185. * @param instanced whether the buffer is instanced (optional)
  29186. * @param useBytes set to true if the stride in in bytes (optional)
  29187. */
  29188. function Buffer(engine, data, updatable, stride, postponeInternalCreation, instanced, useBytes) {
  29189. if (stride === void 0) { stride = 0; }
  29190. if (postponeInternalCreation === void 0) { postponeInternalCreation = false; }
  29191. if (instanced === void 0) { instanced = false; }
  29192. if (useBytes === void 0) { useBytes = false; }
  29193. if (engine instanceof BABYLON.Mesh) { // old versions of BABYLON.VertexBuffer accepted 'mesh' instead of 'engine'
  29194. this._engine = engine.getScene().getEngine();
  29195. }
  29196. else {
  29197. this._engine = engine;
  29198. }
  29199. this._updatable = updatable;
  29200. this._instanced = instanced;
  29201. this._data = data;
  29202. this.byteStride = useBytes ? stride : stride * Float32Array.BYTES_PER_ELEMENT;
  29203. if (!postponeInternalCreation) { // by default
  29204. this.create();
  29205. }
  29206. }
  29207. /**
  29208. * Create a new {BABYLON.VertexBuffer} based on the current buffer
  29209. * @param kind defines the vertex buffer kind (position, normal, etc.)
  29210. * @param offset defines offset in the buffer (0 by default)
  29211. * @param size defines the size in floats of attributes (position is 3 for instance)
  29212. * @param stride defines the stride size in floats in the buffer (the offset to apply to reach next value when data is interleaved)
  29213. * @param instanced defines if the vertex buffer contains indexed data
  29214. * @param useBytes defines if the offset and stride are in bytes
  29215. * @returns the new vertex buffer
  29216. */
  29217. Buffer.prototype.createVertexBuffer = function (kind, offset, size, stride, instanced, useBytes) {
  29218. if (useBytes === void 0) { useBytes = false; }
  29219. var byteOffset = useBytes ? offset : offset * Float32Array.BYTES_PER_ELEMENT;
  29220. var byteStride = stride ? (useBytes ? stride : stride * Float32Array.BYTES_PER_ELEMENT) : this.byteStride;
  29221. // a lot of these parameters are ignored as they are overriden by the buffer
  29222. return new BABYLON.VertexBuffer(this._engine, this, kind, this._updatable, true, byteStride, instanced === undefined ? this._instanced : instanced, byteOffset, size, undefined, undefined, true);
  29223. };
  29224. // Properties
  29225. Buffer.prototype.isUpdatable = function () {
  29226. return this._updatable;
  29227. };
  29228. Buffer.prototype.getData = function () {
  29229. return this._data;
  29230. };
  29231. Buffer.prototype.getBuffer = function () {
  29232. return this._buffer;
  29233. };
  29234. /**
  29235. * Gets the stride in float32 units (i.e. byte stride / 4).
  29236. * May not be an integer if the byte stride is not divisible by 4.
  29237. * DEPRECATED. Use byteStride instead.
  29238. * @returns the stride in float32 units
  29239. */
  29240. Buffer.prototype.getStrideSize = function () {
  29241. return this.byteStride / Float32Array.BYTES_PER_ELEMENT;
  29242. };
  29243. // Methods
  29244. Buffer.prototype.create = function (data) {
  29245. if (data === void 0) { data = null; }
  29246. if (!data && this._buffer) {
  29247. return; // nothing to do
  29248. }
  29249. data = data || this._data;
  29250. if (!data) {
  29251. return;
  29252. }
  29253. if (!this._buffer) { // create buffer
  29254. if (this._updatable) {
  29255. this._buffer = this._engine.createDynamicVertexBuffer(data);
  29256. this._data = data;
  29257. }
  29258. else {
  29259. this._buffer = this._engine.createVertexBuffer(data);
  29260. }
  29261. }
  29262. else if (this._updatable) { // update buffer
  29263. this._engine.updateDynamicVertexBuffer(this._buffer, data);
  29264. this._data = data;
  29265. }
  29266. };
  29267. Buffer.prototype._rebuild = function () {
  29268. this._buffer = null;
  29269. this.create(this._data);
  29270. };
  29271. Buffer.prototype.update = function (data) {
  29272. this.create(data);
  29273. };
  29274. /**
  29275. * Updates the data directly.
  29276. * @param data the new data
  29277. * @param offset the new offset
  29278. * @param vertexCount the vertex count (optional)
  29279. * @param useBytes set to true if the offset is in bytes
  29280. */
  29281. Buffer.prototype.updateDirectly = function (data, offset, vertexCount, useBytes) {
  29282. if (useBytes === void 0) { useBytes = false; }
  29283. if (!this._buffer) {
  29284. return;
  29285. }
  29286. if (this._updatable) { // update buffer
  29287. this._engine.updateDynamicVertexBuffer(this._buffer, data, useBytes ? offset : offset * Float32Array.BYTES_PER_ELEMENT, (vertexCount ? vertexCount * this.byteStride : undefined));
  29288. this._data = null;
  29289. }
  29290. };
  29291. Buffer.prototype.dispose = function () {
  29292. if (!this._buffer) {
  29293. return;
  29294. }
  29295. if (this._engine._releaseBuffer(this._buffer)) {
  29296. this._buffer = null;
  29297. }
  29298. };
  29299. return Buffer;
  29300. }());
  29301. BABYLON.Buffer = Buffer;
  29302. })(BABYLON || (BABYLON = {}));
  29303. //# sourceMappingURL=babylon.buffer.js.map
  29304. var BABYLON;
  29305. (function (BABYLON) {
  29306. var VertexBuffer = /** @class */ (function () {
  29307. /**
  29308. * Constructor
  29309. * @param engine the engine
  29310. * @param data the data to use for this vertex buffer
  29311. * @param kind the vertex buffer kind
  29312. * @param updatable whether the data is updatable
  29313. * @param postponeInternalCreation whether to postpone creating the internal WebGL buffer (optional)
  29314. * @param stride the stride (optional)
  29315. * @param instanced whether the buffer is instanced (optional)
  29316. * @param offset the offset of the data (optional)
  29317. * @param size the number of components (optional)
  29318. * @param type the type of the component (optional)
  29319. * @param normalized whether the data contains normalized data (optional)
  29320. * @param useBytes set to true if stride and offset are in bytes (optional)
  29321. */
  29322. function VertexBuffer(engine, data, kind, updatable, postponeInternalCreation, stride, instanced, offset, size, type, normalized, useBytes) {
  29323. if (normalized === void 0) { normalized = false; }
  29324. if (useBytes === void 0) { useBytes = false; }
  29325. if (data instanceof BABYLON.Buffer) {
  29326. this._buffer = data;
  29327. this._ownsBuffer = false;
  29328. }
  29329. else {
  29330. this._buffer = new BABYLON.Buffer(engine, data, updatable, stride, postponeInternalCreation, instanced, useBytes);
  29331. this._ownsBuffer = true;
  29332. }
  29333. this._kind = kind;
  29334. if (type == undefined) {
  29335. var data_1 = this.getData();
  29336. this.type = VertexBuffer.FLOAT;
  29337. if (data_1 instanceof Int8Array)
  29338. this.type = VertexBuffer.BYTE;
  29339. else if (data_1 instanceof Uint8Array)
  29340. this.type = VertexBuffer.UNSIGNED_BYTE;
  29341. else if (data_1 instanceof Int16Array)
  29342. this.type = VertexBuffer.SHORT;
  29343. else if (data_1 instanceof Uint16Array)
  29344. this.type = VertexBuffer.UNSIGNED_SHORT;
  29345. else if (data_1 instanceof Int32Array)
  29346. this.type = VertexBuffer.INT;
  29347. else if (data_1 instanceof Uint32Array)
  29348. this.type = VertexBuffer.UNSIGNED_INT;
  29349. }
  29350. else {
  29351. this.type = type;
  29352. }
  29353. var typeByteLength = VertexBuffer.GetTypeByteLength(this.type);
  29354. if (useBytes) {
  29355. this._size = size || (stride ? (stride / typeByteLength) : VertexBuffer.DeduceStride(kind));
  29356. this.byteStride = stride || this._buffer.byteStride || (this._size * typeByteLength);
  29357. this.byteOffset = offset || 0;
  29358. }
  29359. else {
  29360. this._size = size || stride || VertexBuffer.DeduceStride(kind);
  29361. this.byteStride = stride ? (stride * typeByteLength) : (this._buffer.byteStride || (this._size * typeByteLength));
  29362. this.byteOffset = (offset || 0) * typeByteLength;
  29363. }
  29364. this.normalized = normalized;
  29365. this._instanced = instanced !== undefined ? instanced : false;
  29366. this._instanceDivisor = instanced ? 1 : 0;
  29367. }
  29368. Object.defineProperty(VertexBuffer.prototype, "instanceDivisor", {
  29369. /**
  29370. * Gets or sets the instance divisor when in instanced mode
  29371. */
  29372. get: function () {
  29373. return this._instanceDivisor;
  29374. },
  29375. set: function (value) {
  29376. this._instanceDivisor = value;
  29377. if (value == 0) {
  29378. this._instanced = false;
  29379. }
  29380. else {
  29381. this._instanced = true;
  29382. }
  29383. },
  29384. enumerable: true,
  29385. configurable: true
  29386. });
  29387. VertexBuffer.prototype._rebuild = function () {
  29388. if (!this._buffer) {
  29389. return;
  29390. }
  29391. this._buffer._rebuild();
  29392. };
  29393. /**
  29394. * Returns the kind of the VertexBuffer (string).
  29395. */
  29396. VertexBuffer.prototype.getKind = function () {
  29397. return this._kind;
  29398. };
  29399. // Properties
  29400. /**
  29401. * Boolean : is the VertexBuffer updatable ?
  29402. */
  29403. VertexBuffer.prototype.isUpdatable = function () {
  29404. return this._buffer.isUpdatable();
  29405. };
  29406. /**
  29407. * Returns an array of numbers or a typed array containing the VertexBuffer data.
  29408. */
  29409. VertexBuffer.prototype.getData = function () {
  29410. return this._buffer.getData();
  29411. };
  29412. /**
  29413. * Returns the WebGLBuffer associated to the VertexBuffer.
  29414. */
  29415. VertexBuffer.prototype.getBuffer = function () {
  29416. return this._buffer.getBuffer();
  29417. };
  29418. /**
  29419. * Returns the stride as a multiple of the type byte length.
  29420. * DEPRECATED. Use byteStride instead.
  29421. */
  29422. VertexBuffer.prototype.getStrideSize = function () {
  29423. return this.byteStride / VertexBuffer.GetTypeByteLength(this.type);
  29424. };
  29425. /**
  29426. * Returns the offset as a multiple of the type byte length.
  29427. * DEPRECATED. Use byteOffset instead.
  29428. */
  29429. VertexBuffer.prototype.getOffset = function () {
  29430. return this.byteOffset / VertexBuffer.GetTypeByteLength(this.type);
  29431. };
  29432. /**
  29433. * Returns the number of components per vertex attribute (integer).
  29434. */
  29435. VertexBuffer.prototype.getSize = function () {
  29436. return this._size;
  29437. };
  29438. /**
  29439. * Boolean : is the WebGLBuffer of the VertexBuffer instanced now ?
  29440. */
  29441. VertexBuffer.prototype.getIsInstanced = function () {
  29442. return this._instanced;
  29443. };
  29444. /**
  29445. * Returns the instancing divisor, zero for non-instanced (integer).
  29446. */
  29447. VertexBuffer.prototype.getInstanceDivisor = function () {
  29448. return this._instanceDivisor;
  29449. };
  29450. // Methods
  29451. /**
  29452. * Creates the underlying WebGLBuffer from the passed numeric array or Float32Array.
  29453. * Returns the created WebGLBuffer.
  29454. */
  29455. VertexBuffer.prototype.create = function (data) {
  29456. return this._buffer.create(data);
  29457. };
  29458. /**
  29459. * Updates the underlying WebGLBuffer according to the passed numeric array or Float32Array.
  29460. * This function will create a new buffer if the current one is not updatable
  29461. * Returns the updated WebGLBuffer.
  29462. */
  29463. VertexBuffer.prototype.update = function (data) {
  29464. return this._buffer.update(data);
  29465. };
  29466. /**
  29467. * Updates directly the underlying WebGLBuffer according to the passed numeric array or Float32Array.
  29468. * Returns the directly updated WebGLBuffer.
  29469. * @param data the new data
  29470. * @param offset the new offset
  29471. * @param useBytes set to true if the offset is in bytes
  29472. */
  29473. VertexBuffer.prototype.updateDirectly = function (data, offset, useBytes) {
  29474. if (useBytes === void 0) { useBytes = false; }
  29475. this._buffer.updateDirectly(data, offset, undefined, useBytes);
  29476. };
  29477. /**
  29478. * Disposes the VertexBuffer and the underlying WebGLBuffer.
  29479. */
  29480. VertexBuffer.prototype.dispose = function () {
  29481. if (this._ownsBuffer) {
  29482. this._buffer.dispose();
  29483. }
  29484. };
  29485. /**
  29486. * Enumerates each value of this vertex buffer as numbers.
  29487. * @param count the number of values to enumerate
  29488. * @param callback the callback function called for each value
  29489. */
  29490. VertexBuffer.prototype.forEach = function (count, callback) {
  29491. VertexBuffer.ForEach(this._buffer.getData(), this.byteOffset, this.byteStride, this._size, this.type, count, this.normalized, callback);
  29492. };
  29493. Object.defineProperty(VertexBuffer, "PositionKind", {
  29494. get: function () {
  29495. return VertexBuffer._PositionKind;
  29496. },
  29497. enumerable: true,
  29498. configurable: true
  29499. });
  29500. Object.defineProperty(VertexBuffer, "NormalKind", {
  29501. get: function () {
  29502. return VertexBuffer._NormalKind;
  29503. },
  29504. enumerable: true,
  29505. configurable: true
  29506. });
  29507. Object.defineProperty(VertexBuffer, "TangentKind", {
  29508. get: function () {
  29509. return VertexBuffer._TangentKind;
  29510. },
  29511. enumerable: true,
  29512. configurable: true
  29513. });
  29514. Object.defineProperty(VertexBuffer, "UVKind", {
  29515. get: function () {
  29516. return VertexBuffer._UVKind;
  29517. },
  29518. enumerable: true,
  29519. configurable: true
  29520. });
  29521. Object.defineProperty(VertexBuffer, "UV2Kind", {
  29522. get: function () {
  29523. return VertexBuffer._UV2Kind;
  29524. },
  29525. enumerable: true,
  29526. configurable: true
  29527. });
  29528. Object.defineProperty(VertexBuffer, "UV3Kind", {
  29529. get: function () {
  29530. return VertexBuffer._UV3Kind;
  29531. },
  29532. enumerable: true,
  29533. configurable: true
  29534. });
  29535. Object.defineProperty(VertexBuffer, "UV4Kind", {
  29536. get: function () {
  29537. return VertexBuffer._UV4Kind;
  29538. },
  29539. enumerable: true,
  29540. configurable: true
  29541. });
  29542. Object.defineProperty(VertexBuffer, "UV5Kind", {
  29543. get: function () {
  29544. return VertexBuffer._UV5Kind;
  29545. },
  29546. enumerable: true,
  29547. configurable: true
  29548. });
  29549. Object.defineProperty(VertexBuffer, "UV6Kind", {
  29550. get: function () {
  29551. return VertexBuffer._UV6Kind;
  29552. },
  29553. enumerable: true,
  29554. configurable: true
  29555. });
  29556. Object.defineProperty(VertexBuffer, "ColorKind", {
  29557. get: function () {
  29558. return VertexBuffer._ColorKind;
  29559. },
  29560. enumerable: true,
  29561. configurable: true
  29562. });
  29563. Object.defineProperty(VertexBuffer, "MatricesIndicesKind", {
  29564. get: function () {
  29565. return VertexBuffer._MatricesIndicesKind;
  29566. },
  29567. enumerable: true,
  29568. configurable: true
  29569. });
  29570. Object.defineProperty(VertexBuffer, "MatricesWeightsKind", {
  29571. get: function () {
  29572. return VertexBuffer._MatricesWeightsKind;
  29573. },
  29574. enumerable: true,
  29575. configurable: true
  29576. });
  29577. Object.defineProperty(VertexBuffer, "MatricesIndicesExtraKind", {
  29578. get: function () {
  29579. return VertexBuffer._MatricesIndicesExtraKind;
  29580. },
  29581. enumerable: true,
  29582. configurable: true
  29583. });
  29584. Object.defineProperty(VertexBuffer, "MatricesWeightsExtraKind", {
  29585. get: function () {
  29586. return VertexBuffer._MatricesWeightsExtraKind;
  29587. },
  29588. enumerable: true,
  29589. configurable: true
  29590. });
  29591. /**
  29592. * Deduces the stride given a kind.
  29593. * @param kind The kind string to deduce
  29594. * @returns The deduced stride
  29595. */
  29596. VertexBuffer.DeduceStride = function (kind) {
  29597. switch (kind) {
  29598. case VertexBuffer.UVKind:
  29599. case VertexBuffer.UV2Kind:
  29600. case VertexBuffer.UV3Kind:
  29601. case VertexBuffer.UV4Kind:
  29602. case VertexBuffer.UV5Kind:
  29603. case VertexBuffer.UV6Kind:
  29604. return 2;
  29605. case VertexBuffer.NormalKind:
  29606. case VertexBuffer.PositionKind:
  29607. return 3;
  29608. case VertexBuffer.ColorKind:
  29609. case VertexBuffer.MatricesIndicesKind:
  29610. case VertexBuffer.MatricesIndicesExtraKind:
  29611. case VertexBuffer.MatricesWeightsKind:
  29612. case VertexBuffer.MatricesWeightsExtraKind:
  29613. case VertexBuffer.TangentKind:
  29614. return 4;
  29615. default:
  29616. throw new Error("Invalid kind '" + kind + "'");
  29617. }
  29618. };
  29619. /**
  29620. * Gets the byte length of the given type.
  29621. * @param type the type
  29622. * @returns the number of bytes
  29623. */
  29624. VertexBuffer.GetTypeByteLength = function (type) {
  29625. switch (type) {
  29626. case VertexBuffer.BYTE:
  29627. case VertexBuffer.UNSIGNED_BYTE:
  29628. return 1;
  29629. case VertexBuffer.SHORT:
  29630. case VertexBuffer.UNSIGNED_SHORT:
  29631. return 2;
  29632. case VertexBuffer.INT:
  29633. case VertexBuffer.FLOAT:
  29634. return 4;
  29635. default:
  29636. throw new Error("Invalid type '" + type + "'");
  29637. }
  29638. };
  29639. /**
  29640. * Enumerates each value of the given parameters as numbers.
  29641. * @param data the data to enumerate
  29642. * @param byteOffset the byte offset of the data
  29643. * @param byteStride the byte stride of the data
  29644. * @param componentCount the number of components per element
  29645. * @param componentType the type of the component
  29646. * @param count the total number of components
  29647. * @param normalized whether the data is normalized
  29648. * @param callback the callback function called for each value
  29649. */
  29650. VertexBuffer.ForEach = function (data, byteOffset, byteStride, componentCount, componentType, count, normalized, callback) {
  29651. if (data instanceof Array) {
  29652. var offset = byteOffset / 4;
  29653. var stride = byteStride / 4;
  29654. for (var index = 0; index < count; index += componentCount) {
  29655. for (var componentIndex = 0; componentIndex < componentCount; componentIndex++) {
  29656. callback(data[offset + componentIndex], index + componentIndex);
  29657. }
  29658. offset += stride;
  29659. }
  29660. }
  29661. else {
  29662. var dataView = data instanceof ArrayBuffer ? new DataView(data) : new DataView(data.buffer, data.byteOffset, data.byteLength);
  29663. var componentByteLength = VertexBuffer.GetTypeByteLength(componentType);
  29664. for (var index = 0; index < count; index += componentCount) {
  29665. var componentByteOffset = byteOffset;
  29666. for (var componentIndex = 0; componentIndex < componentCount; componentIndex++) {
  29667. var value = VertexBuffer._GetFloatValue(dataView, componentType, componentByteOffset, normalized);
  29668. callback(value, index + componentIndex);
  29669. componentByteOffset += componentByteLength;
  29670. }
  29671. byteOffset += byteStride;
  29672. }
  29673. }
  29674. };
  29675. VertexBuffer._GetFloatValue = function (dataView, type, byteOffset, normalized) {
  29676. switch (type) {
  29677. case VertexBuffer.BYTE: {
  29678. var value = dataView.getInt8(byteOffset);
  29679. if (normalized) {
  29680. value = (value + 0.5) / 127.5;
  29681. }
  29682. return value;
  29683. }
  29684. case VertexBuffer.UNSIGNED_BYTE: {
  29685. var value = dataView.getUint8(byteOffset);
  29686. if (normalized) {
  29687. value = value / 255;
  29688. }
  29689. return value;
  29690. }
  29691. case VertexBuffer.SHORT: {
  29692. var value = dataView.getInt16(byteOffset, true);
  29693. if (normalized) {
  29694. value = (value + 0.5) / 16383.5;
  29695. }
  29696. return value;
  29697. }
  29698. case VertexBuffer.UNSIGNED_SHORT: {
  29699. var value = dataView.getUint16(byteOffset, true);
  29700. if (normalized) {
  29701. value = value / 65535;
  29702. }
  29703. return value;
  29704. }
  29705. case VertexBuffer.FLOAT: {
  29706. return dataView.getFloat32(byteOffset, true);
  29707. }
  29708. default: {
  29709. throw new Error("Invalid component type " + type);
  29710. }
  29711. }
  29712. };
  29713. /**
  29714. * The byte type.
  29715. */
  29716. VertexBuffer.BYTE = 5120;
  29717. /**
  29718. * The unsigned byte type.
  29719. */
  29720. VertexBuffer.UNSIGNED_BYTE = 5121;
  29721. /**
  29722. * The short type.
  29723. */
  29724. VertexBuffer.SHORT = 5122;
  29725. /**
  29726. * The unsigned short type.
  29727. */
  29728. VertexBuffer.UNSIGNED_SHORT = 5123;
  29729. /**
  29730. * The integer type.
  29731. */
  29732. VertexBuffer.INT = 5124;
  29733. /**
  29734. * The unsigned integer type.
  29735. */
  29736. VertexBuffer.UNSIGNED_INT = 5125;
  29737. /**
  29738. * The float type.
  29739. */
  29740. VertexBuffer.FLOAT = 5126;
  29741. // Enums
  29742. VertexBuffer._PositionKind = "position";
  29743. VertexBuffer._NormalKind = "normal";
  29744. VertexBuffer._TangentKind = "tangent";
  29745. VertexBuffer._UVKind = "uv";
  29746. VertexBuffer._UV2Kind = "uv2";
  29747. VertexBuffer._UV3Kind = "uv3";
  29748. VertexBuffer._UV4Kind = "uv4";
  29749. VertexBuffer._UV5Kind = "uv5";
  29750. VertexBuffer._UV6Kind = "uv6";
  29751. VertexBuffer._ColorKind = "color";
  29752. VertexBuffer._MatricesIndicesKind = "matricesIndices";
  29753. VertexBuffer._MatricesWeightsKind = "matricesWeights";
  29754. VertexBuffer._MatricesIndicesExtraKind = "matricesIndicesExtra";
  29755. VertexBuffer._MatricesWeightsExtraKind = "matricesWeightsExtra";
  29756. return VertexBuffer;
  29757. }());
  29758. BABYLON.VertexBuffer = VertexBuffer;
  29759. })(BABYLON || (BABYLON = {}));
  29760. //# sourceMappingURL=babylon.vertexBuffer.js.map
  29761. var BABYLON;
  29762. (function (BABYLON) {
  29763. /**
  29764. * Internal class used by the engine to get list of {BABYLON.InternalTexture} already bound to the GL context
  29765. */
  29766. var DummyInternalTextureTracker = /** @class */ (function () {
  29767. function DummyInternalTextureTracker() {
  29768. /**
  29769. * Gets or set the previous tracker in the list
  29770. */
  29771. this.previous = null;
  29772. /**
  29773. * Gets or set the next tracker in the list
  29774. */
  29775. this.next = null;
  29776. }
  29777. return DummyInternalTextureTracker;
  29778. }());
  29779. BABYLON.DummyInternalTextureTracker = DummyInternalTextureTracker;
  29780. })(BABYLON || (BABYLON = {}));
  29781. //# sourceMappingURL=babylon.internalTextureTracker.js.map
  29782. var BABYLON;
  29783. (function (BABYLON) {
  29784. /**
  29785. * Class used to store data associated with WebGL texture data for the engine
  29786. * This class should not be used directly
  29787. */
  29788. var InternalTexture = /** @class */ (function () {
  29789. /**
  29790. * Creates a new InternalTexture
  29791. * @param engine defines the engine to use
  29792. * @param dataSource defines the type of data that will be used
  29793. */
  29794. function InternalTexture(engine, dataSource) {
  29795. /**
  29796. * Observable called when the texture is loaded
  29797. */
  29798. this.onLoadedObservable = new BABYLON.Observable();
  29799. /**
  29800. * Gets or set the previous tracker in the list
  29801. */
  29802. this.previous = null;
  29803. /**
  29804. * Gets or set the next tracker in the list
  29805. */
  29806. this.next = null;
  29807. // Private
  29808. /** @hidden */
  29809. this._initialSlot = -1;
  29810. /** @hidden */
  29811. this._designatedSlot = -1;
  29812. /** @hidden */
  29813. this._dataSource = InternalTexture.DATASOURCE_UNKNOWN;
  29814. /** @hidden */
  29815. this._comparisonFunction = 0;
  29816. /** @hidden */
  29817. this._references = 1;
  29818. this._engine = engine;
  29819. this._dataSource = dataSource;
  29820. this._webGLTexture = engine._createTexture();
  29821. }
  29822. Object.defineProperty(InternalTexture.prototype, "dataSource", {
  29823. /**
  29824. * Gets the data source type of the texture (can be one of the BABYLON.InternalTexture.DATASOURCE_XXXX)
  29825. */
  29826. get: function () {
  29827. return this._dataSource;
  29828. },
  29829. enumerable: true,
  29830. configurable: true
  29831. });
  29832. /**
  29833. * Increments the number of references (ie. the number of {BABYLON.Texture} that point to it)
  29834. */
  29835. InternalTexture.prototype.incrementReferences = function () {
  29836. this._references++;
  29837. };
  29838. /**
  29839. * Change the size of the texture (not the size of the content)
  29840. * @param width defines the new width
  29841. * @param height defines the new height
  29842. * @param depth defines the new depth (1 by default)
  29843. */
  29844. InternalTexture.prototype.updateSize = function (width, height, depth) {
  29845. if (depth === void 0) { depth = 1; }
  29846. this.width = width;
  29847. this.height = height;
  29848. this.depth = depth;
  29849. this.baseWidth = width;
  29850. this.baseHeight = height;
  29851. this.baseDepth = depth;
  29852. this._size = width * height * depth;
  29853. };
  29854. /** @hidden */
  29855. InternalTexture.prototype._rebuild = function () {
  29856. var _this = this;
  29857. var proxy;
  29858. this.isReady = false;
  29859. this._cachedCoordinatesMode = null;
  29860. this._cachedWrapU = null;
  29861. this._cachedWrapV = null;
  29862. this._cachedAnisotropicFilteringLevel = null;
  29863. switch (this._dataSource) {
  29864. case InternalTexture.DATASOURCE_TEMP:
  29865. return;
  29866. case InternalTexture.DATASOURCE_URL:
  29867. proxy = this._engine.createTexture(this.url, !this.generateMipMaps, this.invertY, null, this.samplingMode, function () {
  29868. _this.isReady = true;
  29869. }, null, this._buffer, undefined, this.format);
  29870. proxy._swapAndDie(this);
  29871. return;
  29872. case InternalTexture.DATASOURCE_RAW:
  29873. proxy = this._engine.createRawTexture(this._bufferView, this.baseWidth, this.baseHeight, this.format, this.generateMipMaps, this.invertY, this.samplingMode, this._compression);
  29874. proxy._swapAndDie(this);
  29875. this.isReady = true;
  29876. return;
  29877. case InternalTexture.DATASOURCE_RAW3D:
  29878. proxy = this._engine.createRawTexture3D(this._bufferView, this.baseWidth, this.baseHeight, this.baseDepth, this.format, this.generateMipMaps, this.invertY, this.samplingMode, this._compression);
  29879. proxy._swapAndDie(this);
  29880. this.isReady = true;
  29881. return;
  29882. case InternalTexture.DATASOURCE_DYNAMIC:
  29883. proxy = this._engine.createDynamicTexture(this.baseWidth, this.baseHeight, this.generateMipMaps, this.samplingMode);
  29884. proxy._swapAndDie(this);
  29885. // The engine will make sure to update content so no need to flag it as isReady = true
  29886. return;
  29887. case InternalTexture.DATASOURCE_RENDERTARGET:
  29888. var options = new BABYLON.RenderTargetCreationOptions();
  29889. options.generateDepthBuffer = this._generateDepthBuffer;
  29890. options.generateMipMaps = this.generateMipMaps;
  29891. options.generateStencilBuffer = this._generateStencilBuffer;
  29892. options.samplingMode = this.samplingMode;
  29893. options.type = this.type;
  29894. if (this.isCube) {
  29895. proxy = this._engine.createRenderTargetCubeTexture(this.width, options);
  29896. }
  29897. else {
  29898. var size = {
  29899. width: this.width,
  29900. height: this.height
  29901. };
  29902. proxy = this._engine.createRenderTargetTexture(size, options);
  29903. }
  29904. proxy._swapAndDie(this);
  29905. this.isReady = true;
  29906. return;
  29907. case InternalTexture.DATASOURCE_DEPTHTEXTURE:
  29908. var depthTextureOptions = {
  29909. bilinearFiltering: this.samplingMode !== BABYLON.Texture.BILINEAR_SAMPLINGMODE,
  29910. comparisonFunction: this._comparisonFunction,
  29911. generateStencil: this._generateStencilBuffer,
  29912. isCube: this.isCube
  29913. };
  29914. proxy = this._engine.createDepthStencilTexture({ width: this.width, height: this.height }, depthTextureOptions);
  29915. proxy._swapAndDie(this);
  29916. this.isReady = true;
  29917. return;
  29918. case InternalTexture.DATASOURCE_CUBE:
  29919. proxy = this._engine.createCubeTexture(this.url, null, this._files, !this.generateMipMaps, function () {
  29920. _this.isReady = true;
  29921. }, null, this.format, this._extension);
  29922. proxy._swapAndDie(this);
  29923. return;
  29924. case InternalTexture.DATASOURCE_CUBERAW:
  29925. proxy = this._engine.createRawCubeTexture(this._bufferViewArray, this.width, this.format, this.type, this.generateMipMaps, this.invertY, this.samplingMode, this._compression);
  29926. proxy._swapAndDie(this);
  29927. this.isReady = true;
  29928. return;
  29929. case InternalTexture.DATASOURCE_CUBEPREFILTERED:
  29930. proxy = this._engine.createPrefilteredCubeTexture(this.url, null, this._lodGenerationScale, this._lodGenerationOffset, function (proxy) {
  29931. if (proxy) {
  29932. proxy._swapAndDie(_this);
  29933. }
  29934. _this.isReady = true;
  29935. }, null, this.format, this._extension);
  29936. return;
  29937. }
  29938. };
  29939. InternalTexture.prototype._swapAndDie = function (target) {
  29940. target._webGLTexture = this._webGLTexture;
  29941. if (this._framebuffer) {
  29942. target._framebuffer = this._framebuffer;
  29943. }
  29944. if (this._depthStencilBuffer) {
  29945. target._depthStencilBuffer = this._depthStencilBuffer;
  29946. }
  29947. if (this._lodTextureHigh) {
  29948. if (target._lodTextureHigh) {
  29949. target._lodTextureHigh.dispose();
  29950. }
  29951. target._lodTextureHigh = this._lodTextureHigh;
  29952. }
  29953. if (this._lodTextureMid) {
  29954. if (target._lodTextureMid) {
  29955. target._lodTextureMid.dispose();
  29956. }
  29957. target._lodTextureMid = this._lodTextureMid;
  29958. }
  29959. if (this._lodTextureLow) {
  29960. if (target._lodTextureLow) {
  29961. target._lodTextureLow.dispose();
  29962. }
  29963. target._lodTextureLow = this._lodTextureLow;
  29964. }
  29965. var cache = this._engine.getLoadedTexturesCache();
  29966. var index = cache.indexOf(this);
  29967. if (index !== -1) {
  29968. cache.splice(index, 1);
  29969. }
  29970. };
  29971. /**
  29972. * Dispose the current allocated resources
  29973. */
  29974. InternalTexture.prototype.dispose = function () {
  29975. if (!this._webGLTexture) {
  29976. return;
  29977. }
  29978. this._references--;
  29979. if (this._references === 0) {
  29980. this._engine._releaseTexture(this);
  29981. this._webGLTexture = null;
  29982. this.previous = null;
  29983. this.next = null;
  29984. }
  29985. };
  29986. /**
  29987. * The source of the texture data is unknown
  29988. */
  29989. InternalTexture.DATASOURCE_UNKNOWN = 0;
  29990. /**
  29991. * Texture data comes from an URL
  29992. */
  29993. InternalTexture.DATASOURCE_URL = 1;
  29994. /**
  29995. * Texture data is only used for temporary storage
  29996. */
  29997. InternalTexture.DATASOURCE_TEMP = 2;
  29998. /**
  29999. * Texture data comes from raw data (ArrayBuffer)
  30000. */
  30001. InternalTexture.DATASOURCE_RAW = 3;
  30002. /**
  30003. * Texture content is dynamic (video or dynamic texture)
  30004. */
  30005. InternalTexture.DATASOURCE_DYNAMIC = 4;
  30006. /**
  30007. * Texture content is generated by rendering to it
  30008. */
  30009. InternalTexture.DATASOURCE_RENDERTARGET = 5;
  30010. /**
  30011. * Texture content is part of a multi render target process
  30012. */
  30013. InternalTexture.DATASOURCE_MULTIRENDERTARGET = 6;
  30014. /**
  30015. * Texture data comes from a cube data file
  30016. */
  30017. InternalTexture.DATASOURCE_CUBE = 7;
  30018. /**
  30019. * Texture data comes from a raw cube data
  30020. */
  30021. InternalTexture.DATASOURCE_CUBERAW = 8;
  30022. /**
  30023. * Texture data come from a prefiltered cube data file
  30024. */
  30025. InternalTexture.DATASOURCE_CUBEPREFILTERED = 9;
  30026. /**
  30027. * Texture content is raw 3D data
  30028. */
  30029. InternalTexture.DATASOURCE_RAW3D = 10;
  30030. /**
  30031. * Texture content is a depth texture
  30032. */
  30033. InternalTexture.DATASOURCE_DEPTHTEXTURE = 11;
  30034. return InternalTexture;
  30035. }());
  30036. BABYLON.InternalTexture = InternalTexture;
  30037. })(BABYLON || (BABYLON = {}));
  30038. //# sourceMappingURL=babylon.internalTexture.js.map
  30039. var BABYLON;
  30040. (function (BABYLON) {
  30041. var BaseTexture = /** @class */ (function () {
  30042. function BaseTexture(scene) {
  30043. this._hasAlpha = false;
  30044. this.getAlphaFromRGB = false;
  30045. this.level = 1;
  30046. this.coordinatesIndex = 0;
  30047. this._coordinatesMode = BABYLON.Texture.EXPLICIT_MODE;
  30048. /**
  30049. * | Value | Type | Description |
  30050. * | ----- | ------------------ | ----------- |
  30051. * | 0 | CLAMP_ADDRESSMODE | |
  30052. * | 1 | WRAP_ADDRESSMODE | |
  30053. * | 2 | MIRROR_ADDRESSMODE | |
  30054. */
  30055. this.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  30056. /**
  30057. * | Value | Type | Description |
  30058. * | ----- | ------------------ | ----------- |
  30059. * | 0 | CLAMP_ADDRESSMODE | |
  30060. * | 1 | WRAP_ADDRESSMODE | |
  30061. * | 2 | MIRROR_ADDRESSMODE | |
  30062. */
  30063. this.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  30064. /**
  30065. * | Value | Type | Description |
  30066. * | ----- | ------------------ | ----------- |
  30067. * | 0 | CLAMP_ADDRESSMODE | |
  30068. * | 1 | WRAP_ADDRESSMODE | |
  30069. * | 2 | MIRROR_ADDRESSMODE | |
  30070. */
  30071. this.wrapR = BABYLON.Texture.WRAP_ADDRESSMODE;
  30072. this.anisotropicFilteringLevel = BaseTexture.DEFAULT_ANISOTROPIC_FILTERING_LEVEL;
  30073. this.isCube = false;
  30074. this.is3D = false;
  30075. this.gammaSpace = true;
  30076. this.invertZ = false;
  30077. this.lodLevelInAlpha = false;
  30078. this.lodGenerationOffset = 0.0;
  30079. this.lodGenerationScale = 0.8;
  30080. this.isRenderTarget = false;
  30081. this.animations = new Array();
  30082. /**
  30083. * An event triggered when the texture is disposed.
  30084. */
  30085. this.onDisposeObservable = new BABYLON.Observable();
  30086. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  30087. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  30088. if (this._scene) {
  30089. this._scene.textures.push(this);
  30090. }
  30091. this._uid = null;
  30092. }
  30093. Object.defineProperty(BaseTexture.prototype, "hasAlpha", {
  30094. get: function () {
  30095. return this._hasAlpha;
  30096. },
  30097. set: function (value) {
  30098. if (this._hasAlpha === value) {
  30099. return;
  30100. }
  30101. this._hasAlpha = value;
  30102. if (this._scene) {
  30103. this._scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag | BABYLON.Material.MiscDirtyFlag);
  30104. }
  30105. },
  30106. enumerable: true,
  30107. configurable: true
  30108. });
  30109. Object.defineProperty(BaseTexture.prototype, "coordinatesMode", {
  30110. get: function () {
  30111. return this._coordinatesMode;
  30112. },
  30113. /**
  30114. * How a texture is mapped.
  30115. *
  30116. * | Value | Type | Description |
  30117. * | ----- | ----------------------------------- | ----------- |
  30118. * | 0 | EXPLICIT_MODE | |
  30119. * | 1 | SPHERICAL_MODE | |
  30120. * | 2 | PLANAR_MODE | |
  30121. * | 3 | CUBIC_MODE | |
  30122. * | 4 | PROJECTION_MODE | |
  30123. * | 5 | SKYBOX_MODE | |
  30124. * | 6 | INVCUBIC_MODE | |
  30125. * | 7 | EQUIRECTANGULAR_MODE | |
  30126. * | 8 | FIXED_EQUIRECTANGULAR_MODE | |
  30127. * | 9 | FIXED_EQUIRECTANGULAR_MIRRORED_MODE | |
  30128. */
  30129. set: function (value) {
  30130. if (this._coordinatesMode === value) {
  30131. return;
  30132. }
  30133. this._coordinatesMode = value;
  30134. if (this._scene) {
  30135. this._scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  30136. }
  30137. },
  30138. enumerable: true,
  30139. configurable: true
  30140. });
  30141. Object.defineProperty(BaseTexture.prototype, "uid", {
  30142. get: function () {
  30143. if (!this._uid) {
  30144. this._uid = BABYLON.Tools.RandomId();
  30145. }
  30146. return this._uid;
  30147. },
  30148. enumerable: true,
  30149. configurable: true
  30150. });
  30151. BaseTexture.prototype.toString = function () {
  30152. return this.name;
  30153. };
  30154. BaseTexture.prototype.getClassName = function () {
  30155. return "BaseTexture";
  30156. };
  30157. Object.defineProperty(BaseTexture.prototype, "onDispose", {
  30158. set: function (callback) {
  30159. if (this._onDisposeObserver) {
  30160. this.onDisposeObservable.remove(this._onDisposeObserver);
  30161. }
  30162. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  30163. },
  30164. enumerable: true,
  30165. configurable: true
  30166. });
  30167. Object.defineProperty(BaseTexture.prototype, "isBlocking", {
  30168. get: function () {
  30169. return true;
  30170. },
  30171. enumerable: true,
  30172. configurable: true
  30173. });
  30174. BaseTexture.prototype.getScene = function () {
  30175. return this._scene;
  30176. };
  30177. BaseTexture.prototype.getTextureMatrix = function () {
  30178. return BABYLON.Matrix.IdentityReadOnly;
  30179. };
  30180. BaseTexture.prototype.getReflectionTextureMatrix = function () {
  30181. return BABYLON.Matrix.IdentityReadOnly;
  30182. };
  30183. BaseTexture.prototype.getInternalTexture = function () {
  30184. return this._texture;
  30185. };
  30186. BaseTexture.prototype.isReadyOrNotBlocking = function () {
  30187. return !this.isBlocking || this.isReady();
  30188. };
  30189. BaseTexture.prototype.isReady = function () {
  30190. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  30191. this.delayLoad();
  30192. return false;
  30193. }
  30194. if (this._texture) {
  30195. return this._texture.isReady;
  30196. }
  30197. return false;
  30198. };
  30199. BaseTexture.prototype.getSize = function () {
  30200. if (this._texture && this._texture.width) {
  30201. return new BABYLON.Size(this._texture.width, this._texture.height);
  30202. }
  30203. if (this._texture && this._texture._size) {
  30204. return new BABYLON.Size(this._texture._size, this._texture._size);
  30205. }
  30206. return BABYLON.Size.Zero();
  30207. };
  30208. BaseTexture.prototype.getBaseSize = function () {
  30209. if (!this.isReady() || !this._texture)
  30210. return BABYLON.Size.Zero();
  30211. if (this._texture._size) {
  30212. return new BABYLON.Size(this._texture._size, this._texture._size);
  30213. }
  30214. return new BABYLON.Size(this._texture.baseWidth, this._texture.baseHeight);
  30215. };
  30216. BaseTexture.prototype.scale = function (ratio) {
  30217. };
  30218. Object.defineProperty(BaseTexture.prototype, "canRescale", {
  30219. get: function () {
  30220. return false;
  30221. },
  30222. enumerable: true,
  30223. configurable: true
  30224. });
  30225. BaseTexture.prototype._getFromCache = function (url, noMipmap, sampling) {
  30226. if (!this._scene) {
  30227. return null;
  30228. }
  30229. var texturesCache = this._scene.getEngine().getLoadedTexturesCache();
  30230. for (var index = 0; index < texturesCache.length; index++) {
  30231. var texturesCacheEntry = texturesCache[index];
  30232. if (texturesCacheEntry.url === url && texturesCacheEntry.generateMipMaps === !noMipmap) {
  30233. if (!sampling || sampling === texturesCacheEntry.samplingMode) {
  30234. texturesCacheEntry.incrementReferences();
  30235. return texturesCacheEntry;
  30236. }
  30237. }
  30238. }
  30239. return null;
  30240. };
  30241. BaseTexture.prototype._rebuild = function () {
  30242. };
  30243. BaseTexture.prototype.delayLoad = function () {
  30244. };
  30245. BaseTexture.prototype.clone = function () {
  30246. return null;
  30247. };
  30248. Object.defineProperty(BaseTexture.prototype, "textureType", {
  30249. get: function () {
  30250. if (!this._texture) {
  30251. return BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  30252. }
  30253. return (this._texture.type !== undefined) ? this._texture.type : BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  30254. },
  30255. enumerable: true,
  30256. configurable: true
  30257. });
  30258. Object.defineProperty(BaseTexture.prototype, "textureFormat", {
  30259. get: function () {
  30260. if (!this._texture) {
  30261. return BABYLON.Engine.TEXTUREFORMAT_RGBA;
  30262. }
  30263. return (this._texture.format !== undefined) ? this._texture.format : BABYLON.Engine.TEXTUREFORMAT_RGBA;
  30264. },
  30265. enumerable: true,
  30266. configurable: true
  30267. });
  30268. BaseTexture.prototype.readPixels = function (faceIndex) {
  30269. if (faceIndex === void 0) { faceIndex = 0; }
  30270. if (!this._texture) {
  30271. return null;
  30272. }
  30273. var size = this.getSize();
  30274. var scene = this.getScene();
  30275. if (!scene) {
  30276. return null;
  30277. }
  30278. var engine = scene.getEngine();
  30279. if (this._texture.isCube) {
  30280. return engine._readTexturePixels(this._texture, size.width, size.height, faceIndex);
  30281. }
  30282. return engine._readTexturePixels(this._texture, size.width, size.height, -1);
  30283. };
  30284. BaseTexture.prototype.releaseInternalTexture = function () {
  30285. if (this._texture) {
  30286. this._texture.dispose();
  30287. this._texture = null;
  30288. }
  30289. };
  30290. Object.defineProperty(BaseTexture.prototype, "sphericalPolynomial", {
  30291. get: function () {
  30292. if (!this._texture || !BABYLON.CubeMapToSphericalPolynomialTools || !this.isReady()) {
  30293. return null;
  30294. }
  30295. if (!this._texture._sphericalPolynomial) {
  30296. this._texture._sphericalPolynomial =
  30297. BABYLON.CubeMapToSphericalPolynomialTools.ConvertCubeMapTextureToSphericalPolynomial(this);
  30298. }
  30299. return this._texture._sphericalPolynomial;
  30300. },
  30301. set: function (value) {
  30302. if (this._texture) {
  30303. this._texture._sphericalPolynomial = value;
  30304. }
  30305. },
  30306. enumerable: true,
  30307. configurable: true
  30308. });
  30309. Object.defineProperty(BaseTexture.prototype, "_lodTextureHigh", {
  30310. get: function () {
  30311. if (this._texture) {
  30312. return this._texture._lodTextureHigh;
  30313. }
  30314. return null;
  30315. },
  30316. enumerable: true,
  30317. configurable: true
  30318. });
  30319. Object.defineProperty(BaseTexture.prototype, "_lodTextureMid", {
  30320. get: function () {
  30321. if (this._texture) {
  30322. return this._texture._lodTextureMid;
  30323. }
  30324. return null;
  30325. },
  30326. enumerable: true,
  30327. configurable: true
  30328. });
  30329. Object.defineProperty(BaseTexture.prototype, "_lodTextureLow", {
  30330. get: function () {
  30331. if (this._texture) {
  30332. return this._texture._lodTextureLow;
  30333. }
  30334. return null;
  30335. },
  30336. enumerable: true,
  30337. configurable: true
  30338. });
  30339. BaseTexture.prototype.dispose = function () {
  30340. if (!this._scene) {
  30341. return;
  30342. }
  30343. // Animations
  30344. this._scene.stopAnimation(this);
  30345. // Remove from scene
  30346. this._scene._removePendingData(this);
  30347. var index = this._scene.textures.indexOf(this);
  30348. if (index >= 0) {
  30349. this._scene.textures.splice(index, 1);
  30350. }
  30351. if (this._texture === undefined) {
  30352. return;
  30353. }
  30354. // Release
  30355. this.releaseInternalTexture();
  30356. // Callback
  30357. this.onDisposeObservable.notifyObservers(this);
  30358. this.onDisposeObservable.clear();
  30359. };
  30360. BaseTexture.prototype.serialize = function () {
  30361. if (!this.name) {
  30362. return null;
  30363. }
  30364. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  30365. // Animations
  30366. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  30367. return serializationObject;
  30368. };
  30369. BaseTexture.WhenAllReady = function (textures, callback) {
  30370. var numRemaining = textures.length;
  30371. if (numRemaining === 0) {
  30372. callback();
  30373. return;
  30374. }
  30375. var _loop_1 = function () {
  30376. texture = textures[i];
  30377. if (texture.isReady()) {
  30378. if (--numRemaining === 0) {
  30379. callback();
  30380. }
  30381. }
  30382. else {
  30383. onLoadObservable = texture.onLoadObservable;
  30384. var onLoadCallback_1 = function () {
  30385. onLoadObservable.removeCallback(onLoadCallback_1);
  30386. if (--numRemaining === 0) {
  30387. callback();
  30388. }
  30389. };
  30390. onLoadObservable.add(onLoadCallback_1);
  30391. }
  30392. };
  30393. var texture, onLoadObservable;
  30394. for (var i = 0; i < textures.length; i++) {
  30395. _loop_1();
  30396. }
  30397. };
  30398. BaseTexture.DEFAULT_ANISOTROPIC_FILTERING_LEVEL = 4;
  30399. __decorate([
  30400. BABYLON.serialize()
  30401. ], BaseTexture.prototype, "name", void 0);
  30402. __decorate([
  30403. BABYLON.serialize("hasAlpha")
  30404. ], BaseTexture.prototype, "_hasAlpha", void 0);
  30405. __decorate([
  30406. BABYLON.serialize()
  30407. ], BaseTexture.prototype, "getAlphaFromRGB", void 0);
  30408. __decorate([
  30409. BABYLON.serialize()
  30410. ], BaseTexture.prototype, "level", void 0);
  30411. __decorate([
  30412. BABYLON.serialize()
  30413. ], BaseTexture.prototype, "coordinatesIndex", void 0);
  30414. __decorate([
  30415. BABYLON.serialize("coordinatesMode")
  30416. ], BaseTexture.prototype, "_coordinatesMode", void 0);
  30417. __decorate([
  30418. BABYLON.serialize()
  30419. ], BaseTexture.prototype, "wrapU", void 0);
  30420. __decorate([
  30421. BABYLON.serialize()
  30422. ], BaseTexture.prototype, "wrapV", void 0);
  30423. __decorate([
  30424. BABYLON.serialize()
  30425. ], BaseTexture.prototype, "wrapR", void 0);
  30426. __decorate([
  30427. BABYLON.serialize()
  30428. ], BaseTexture.prototype, "anisotropicFilteringLevel", void 0);
  30429. __decorate([
  30430. BABYLON.serialize()
  30431. ], BaseTexture.prototype, "isCube", void 0);
  30432. __decorate([
  30433. BABYLON.serialize()
  30434. ], BaseTexture.prototype, "is3D", void 0);
  30435. __decorate([
  30436. BABYLON.serialize()
  30437. ], BaseTexture.prototype, "gammaSpace", void 0);
  30438. __decorate([
  30439. BABYLON.serialize()
  30440. ], BaseTexture.prototype, "invertZ", void 0);
  30441. __decorate([
  30442. BABYLON.serialize()
  30443. ], BaseTexture.prototype, "lodLevelInAlpha", void 0);
  30444. __decorate([
  30445. BABYLON.serialize()
  30446. ], BaseTexture.prototype, "lodGenerationOffset", void 0);
  30447. __decorate([
  30448. BABYLON.serialize()
  30449. ], BaseTexture.prototype, "lodGenerationScale", void 0);
  30450. __decorate([
  30451. BABYLON.serialize()
  30452. ], BaseTexture.prototype, "isRenderTarget", void 0);
  30453. return BaseTexture;
  30454. }());
  30455. BABYLON.BaseTexture = BaseTexture;
  30456. })(BABYLON || (BABYLON = {}));
  30457. //# sourceMappingURL=babylon.baseTexture.js.map
  30458. var BABYLON;
  30459. (function (BABYLON) {
  30460. var Texture = /** @class */ (function (_super) {
  30461. __extends(Texture, _super);
  30462. function Texture(url, scene, noMipmap, invertY, samplingMode, onLoad, onError, buffer, deleteBuffer, format) {
  30463. if (noMipmap === void 0) { noMipmap = false; }
  30464. if (invertY === void 0) { invertY = true; }
  30465. if (samplingMode === void 0) { samplingMode = Texture.TRILINEAR_SAMPLINGMODE; }
  30466. if (onLoad === void 0) { onLoad = null; }
  30467. if (onError === void 0) { onError = null; }
  30468. if (buffer === void 0) { buffer = null; }
  30469. if (deleteBuffer === void 0) { deleteBuffer = false; }
  30470. var _this = _super.call(this, scene) || this;
  30471. _this.uOffset = 0;
  30472. _this.vOffset = 0;
  30473. _this.uScale = 1.0;
  30474. _this.vScale = 1.0;
  30475. _this.uAng = 0;
  30476. _this.vAng = 0;
  30477. _this.wAng = 0;
  30478. _this._isBlocking = true;
  30479. _this.name = url || "";
  30480. _this.url = url;
  30481. _this._noMipmap = noMipmap;
  30482. _this._invertY = invertY;
  30483. _this._samplingMode = samplingMode;
  30484. _this._buffer = buffer;
  30485. _this._deleteBuffer = deleteBuffer;
  30486. if (format) {
  30487. _this._format = format;
  30488. }
  30489. scene = _this.getScene();
  30490. if (!scene) {
  30491. return _this;
  30492. }
  30493. scene.getEngine().onBeforeTextureInitObservable.notifyObservers(_this);
  30494. var load = function () {
  30495. if (_this._onLoadObservable && _this._onLoadObservable.hasObservers()) {
  30496. _this.onLoadObservable.notifyObservers(_this);
  30497. }
  30498. if (onLoad) {
  30499. onLoad();
  30500. }
  30501. if (!_this.isBlocking && scene) {
  30502. scene.resetCachedMaterial();
  30503. }
  30504. };
  30505. if (!_this.url) {
  30506. _this._delayedOnLoad = load;
  30507. _this._delayedOnError = onError;
  30508. return _this;
  30509. }
  30510. _this._texture = _this._getFromCache(_this.url, noMipmap, samplingMode);
  30511. if (!_this._texture) {
  30512. if (!scene.useDelayedTextureLoading) {
  30513. _this._texture = scene.getEngine().createTexture(_this.url, noMipmap, invertY, scene, _this._samplingMode, load, onError, _this._buffer, undefined, _this._format);
  30514. if (deleteBuffer) {
  30515. delete _this._buffer;
  30516. }
  30517. }
  30518. else {
  30519. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  30520. _this._delayedOnLoad = load;
  30521. _this._delayedOnError = onError;
  30522. }
  30523. }
  30524. else {
  30525. if (_this._texture.isReady) {
  30526. BABYLON.Tools.SetImmediate(function () { return load(); });
  30527. }
  30528. else {
  30529. _this._texture.onLoadedObservable.add(load);
  30530. }
  30531. }
  30532. return _this;
  30533. }
  30534. Object.defineProperty(Texture.prototype, "noMipmap", {
  30535. get: function () {
  30536. return this._noMipmap;
  30537. },
  30538. enumerable: true,
  30539. configurable: true
  30540. });
  30541. Object.defineProperty(Texture.prototype, "isBlocking", {
  30542. get: function () {
  30543. return this._isBlocking;
  30544. },
  30545. set: function (value) {
  30546. this._isBlocking = value;
  30547. },
  30548. enumerable: true,
  30549. configurable: true
  30550. });
  30551. Object.defineProperty(Texture.prototype, "samplingMode", {
  30552. get: function () {
  30553. return this._samplingMode;
  30554. },
  30555. enumerable: true,
  30556. configurable: true
  30557. });
  30558. Texture.prototype.updateURL = function (url) {
  30559. this.url = url;
  30560. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  30561. this.delayLoad();
  30562. };
  30563. Texture.prototype.delayLoad = function () {
  30564. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  30565. return;
  30566. }
  30567. var scene = this.getScene();
  30568. if (!scene) {
  30569. return;
  30570. }
  30571. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  30572. this._texture = this._getFromCache(this.url, this._noMipmap, this._samplingMode);
  30573. if (!this._texture) {
  30574. this._texture = scene.getEngine().createTexture(this.url, this._noMipmap, this._invertY, scene, this._samplingMode, this._delayedOnLoad, this._delayedOnError, this._buffer, null, this._format);
  30575. if (this._deleteBuffer) {
  30576. delete this._buffer;
  30577. }
  30578. }
  30579. else {
  30580. if (this._delayedOnLoad) {
  30581. if (this._texture.isReady) {
  30582. BABYLON.Tools.SetImmediate(this._delayedOnLoad);
  30583. }
  30584. else {
  30585. this._texture.onLoadedObservable.add(this._delayedOnLoad);
  30586. }
  30587. }
  30588. }
  30589. this._delayedOnLoad = null;
  30590. this._delayedOnError = null;
  30591. };
  30592. Texture.prototype.updateSamplingMode = function (samplingMode) {
  30593. if (!this._texture) {
  30594. return;
  30595. }
  30596. var scene = this.getScene();
  30597. if (!scene) {
  30598. return;
  30599. }
  30600. this._samplingMode = samplingMode;
  30601. scene.getEngine().updateTextureSamplingMode(samplingMode, this._texture);
  30602. };
  30603. Texture.prototype._prepareRowForTextureGeneration = function (x, y, z, t) {
  30604. x *= this.uScale;
  30605. y *= this.vScale;
  30606. x -= 0.5 * this.uScale;
  30607. y -= 0.5 * this.vScale;
  30608. z -= 0.5;
  30609. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, y, z, this._rowGenerationMatrix, t);
  30610. t.x += 0.5 * this.uScale + this.uOffset;
  30611. t.y += 0.5 * this.vScale + this.vOffset;
  30612. t.z += 0.5;
  30613. };
  30614. Texture.prototype.getTextureMatrix = function () {
  30615. var _this = this;
  30616. if (this.uOffset === this._cachedUOffset &&
  30617. this.vOffset === this._cachedVOffset &&
  30618. this.uScale === this._cachedUScale &&
  30619. this.vScale === this._cachedVScale &&
  30620. this.uAng === this._cachedUAng &&
  30621. this.vAng === this._cachedVAng &&
  30622. this.wAng === this._cachedWAng) {
  30623. return this._cachedTextureMatrix;
  30624. }
  30625. this._cachedUOffset = this.uOffset;
  30626. this._cachedVOffset = this.vOffset;
  30627. this._cachedUScale = this.uScale;
  30628. this._cachedVScale = this.vScale;
  30629. this._cachedUAng = this.uAng;
  30630. this._cachedVAng = this.vAng;
  30631. this._cachedWAng = this.wAng;
  30632. if (!this._cachedTextureMatrix) {
  30633. this._cachedTextureMatrix = BABYLON.Matrix.Zero();
  30634. this._rowGenerationMatrix = new BABYLON.Matrix();
  30635. this._t0 = BABYLON.Vector3.Zero();
  30636. this._t1 = BABYLON.Vector3.Zero();
  30637. this._t2 = BABYLON.Vector3.Zero();
  30638. }
  30639. BABYLON.Matrix.RotationYawPitchRollToRef(this.vAng, this.uAng, this.wAng, this._rowGenerationMatrix);
  30640. this._prepareRowForTextureGeneration(0, 0, 0, this._t0);
  30641. this._prepareRowForTextureGeneration(1.0, 0, 0, this._t1);
  30642. this._prepareRowForTextureGeneration(0, 1.0, 0, this._t2);
  30643. this._t1.subtractInPlace(this._t0);
  30644. this._t2.subtractInPlace(this._t0);
  30645. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  30646. this._cachedTextureMatrix.m[0] = this._t1.x;
  30647. this._cachedTextureMatrix.m[1] = this._t1.y;
  30648. this._cachedTextureMatrix.m[2] = this._t1.z;
  30649. this._cachedTextureMatrix.m[4] = this._t2.x;
  30650. this._cachedTextureMatrix.m[5] = this._t2.y;
  30651. this._cachedTextureMatrix.m[6] = this._t2.z;
  30652. this._cachedTextureMatrix.m[8] = this._t0.x;
  30653. this._cachedTextureMatrix.m[9] = this._t0.y;
  30654. this._cachedTextureMatrix.m[10] = this._t0.z;
  30655. var scene = this.getScene();
  30656. if (!scene) {
  30657. return this._cachedTextureMatrix;
  30658. }
  30659. scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag, function (mat) {
  30660. return mat.hasTexture(_this);
  30661. });
  30662. return this._cachedTextureMatrix;
  30663. };
  30664. Texture.prototype.getReflectionTextureMatrix = function () {
  30665. var _this = this;
  30666. var scene = this.getScene();
  30667. if (!scene) {
  30668. return this._cachedTextureMatrix;
  30669. }
  30670. if (this.uOffset === this._cachedUOffset &&
  30671. this.vOffset === this._cachedVOffset &&
  30672. this.uScale === this._cachedUScale &&
  30673. this.vScale === this._cachedVScale &&
  30674. this.coordinatesMode === this._cachedCoordinatesMode) {
  30675. if (this.coordinatesMode === Texture.PROJECTION_MODE) {
  30676. if (this._cachedProjectionMatrixId === scene.getProjectionMatrix().updateFlag) {
  30677. return this._cachedTextureMatrix;
  30678. }
  30679. }
  30680. else {
  30681. return this._cachedTextureMatrix;
  30682. }
  30683. }
  30684. if (!this._cachedTextureMatrix) {
  30685. this._cachedTextureMatrix = BABYLON.Matrix.Zero();
  30686. }
  30687. if (!this._projectionModeMatrix) {
  30688. this._projectionModeMatrix = BABYLON.Matrix.Zero();
  30689. }
  30690. this._cachedUOffset = this.uOffset;
  30691. this._cachedVOffset = this.vOffset;
  30692. this._cachedUScale = this.uScale;
  30693. this._cachedVScale = this.vScale;
  30694. this._cachedCoordinatesMode = this.coordinatesMode;
  30695. switch (this.coordinatesMode) {
  30696. case Texture.PLANAR_MODE:
  30697. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  30698. this._cachedTextureMatrix[0] = this.uScale;
  30699. this._cachedTextureMatrix[5] = this.vScale;
  30700. this._cachedTextureMatrix[12] = this.uOffset;
  30701. this._cachedTextureMatrix[13] = this.vOffset;
  30702. break;
  30703. case Texture.PROJECTION_MODE:
  30704. BABYLON.Matrix.IdentityToRef(this._projectionModeMatrix);
  30705. this._projectionModeMatrix.m[0] = 0.5;
  30706. this._projectionModeMatrix.m[5] = -0.5;
  30707. this._projectionModeMatrix.m[10] = 0.0;
  30708. this._projectionModeMatrix.m[12] = 0.5;
  30709. this._projectionModeMatrix.m[13] = 0.5;
  30710. this._projectionModeMatrix.m[14] = 1.0;
  30711. this._projectionModeMatrix.m[15] = 1.0;
  30712. var projectionMatrix = scene.getProjectionMatrix();
  30713. this._cachedProjectionMatrixId = projectionMatrix.updateFlag;
  30714. projectionMatrix.multiplyToRef(this._projectionModeMatrix, this._cachedTextureMatrix);
  30715. break;
  30716. default:
  30717. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  30718. break;
  30719. }
  30720. scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag, function (mat) {
  30721. return (mat.getActiveTextures().indexOf(_this) !== -1);
  30722. });
  30723. return this._cachedTextureMatrix;
  30724. };
  30725. Texture.prototype.clone = function () {
  30726. var _this = this;
  30727. return BABYLON.SerializationHelper.Clone(function () {
  30728. return new Texture(_this._texture ? _this._texture.url : null, _this.getScene(), _this._noMipmap, _this._invertY, _this._samplingMode);
  30729. }, this);
  30730. };
  30731. Object.defineProperty(Texture.prototype, "onLoadObservable", {
  30732. get: function () {
  30733. if (!this._onLoadObservable) {
  30734. this._onLoadObservable = new BABYLON.Observable();
  30735. }
  30736. return this._onLoadObservable;
  30737. },
  30738. enumerable: true,
  30739. configurable: true
  30740. });
  30741. Texture.prototype.serialize = function () {
  30742. var serializationObject = _super.prototype.serialize.call(this);
  30743. if (typeof this._buffer === "string" && this._buffer.substr(0, 5) === "data:") {
  30744. serializationObject.base64String = this._buffer;
  30745. serializationObject.name = serializationObject.name.replace("data:", "");
  30746. }
  30747. serializationObject.invertY = this._invertY;
  30748. serializationObject.samplingMode = this.samplingMode;
  30749. return serializationObject;
  30750. };
  30751. Texture.prototype.getClassName = function () {
  30752. return "Texture";
  30753. };
  30754. Texture.prototype.dispose = function () {
  30755. _super.prototype.dispose.call(this);
  30756. if (this.onLoadObservable) {
  30757. this.onLoadObservable.clear();
  30758. this._onLoadObservable = null;
  30759. }
  30760. this._delayedOnLoad = null;
  30761. this._delayedOnError = null;
  30762. };
  30763. // Statics
  30764. Texture.CreateFromBase64String = function (data, name, scene, noMipmap, invertY, samplingMode, onLoad, onError, format) {
  30765. if (samplingMode === void 0) { samplingMode = Texture.TRILINEAR_SAMPLINGMODE; }
  30766. if (onLoad === void 0) { onLoad = null; }
  30767. if (onError === void 0) { onError = null; }
  30768. if (format === void 0) { format = BABYLON.Engine.TEXTUREFORMAT_RGBA; }
  30769. return new Texture("data:" + name, scene, noMipmap, invertY, samplingMode, onLoad, onError, data, false, format);
  30770. };
  30771. Texture.Parse = function (parsedTexture, scene, rootUrl) {
  30772. if (parsedTexture.customType) {
  30773. var customTexture = BABYLON.Tools.Instantiate(parsedTexture.customType);
  30774. // Update Sampling Mode
  30775. var parsedCustomTexture = customTexture.Parse(parsedTexture, scene, rootUrl);
  30776. if (parsedTexture.samplingMode && parsedCustomTexture.updateSamplingMode && parsedCustomTexture._samplingMode) {
  30777. if (parsedCustomTexture._samplingMode !== parsedTexture.samplingMode) {
  30778. parsedCustomTexture.updateSamplingMode(parsedTexture.samplingMode);
  30779. }
  30780. }
  30781. return parsedCustomTexture;
  30782. }
  30783. if (parsedTexture.isCube) {
  30784. return BABYLON.CubeTexture.Parse(parsedTexture, scene, rootUrl);
  30785. }
  30786. if (!parsedTexture.name && !parsedTexture.isRenderTarget) {
  30787. return null;
  30788. }
  30789. var texture = BABYLON.SerializationHelper.Parse(function () {
  30790. var generateMipMaps = true;
  30791. if (parsedTexture.noMipmap) {
  30792. generateMipMaps = false;
  30793. }
  30794. if (parsedTexture.mirrorPlane) {
  30795. var mirrorTexture = new BABYLON.MirrorTexture(parsedTexture.name, parsedTexture.renderTargetSize, scene, generateMipMaps);
  30796. mirrorTexture._waitingRenderList = parsedTexture.renderList;
  30797. mirrorTexture.mirrorPlane = BABYLON.Plane.FromArray(parsedTexture.mirrorPlane);
  30798. return mirrorTexture;
  30799. }
  30800. else if (parsedTexture.isRenderTarget) {
  30801. var renderTargetTexture = new BABYLON.RenderTargetTexture(parsedTexture.name, parsedTexture.renderTargetSize, scene, generateMipMaps);
  30802. renderTargetTexture._waitingRenderList = parsedTexture.renderList;
  30803. return renderTargetTexture;
  30804. }
  30805. else {
  30806. var texture;
  30807. if (parsedTexture.base64String) {
  30808. texture = Texture.CreateFromBase64String(parsedTexture.base64String, parsedTexture.name, scene, !generateMipMaps);
  30809. }
  30810. else {
  30811. var url = rootUrl + parsedTexture.name;
  30812. if (Texture.UseSerializedUrlIfAny && parsedTexture.url) {
  30813. url = parsedTexture.url;
  30814. }
  30815. texture = new Texture(url, scene, !generateMipMaps, parsedTexture.invertY);
  30816. }
  30817. return texture;
  30818. }
  30819. }, parsedTexture, scene);
  30820. // Update Sampling Mode
  30821. if (parsedTexture.samplingMode) {
  30822. var sampling = parsedTexture.samplingMode;
  30823. if (texture._samplingMode !== sampling) {
  30824. texture.updateSamplingMode(sampling);
  30825. }
  30826. }
  30827. // Animations
  30828. if (parsedTexture.animations) {
  30829. for (var animationIndex = 0; animationIndex < parsedTexture.animations.length; animationIndex++) {
  30830. var parsedAnimation = parsedTexture.animations[animationIndex];
  30831. texture.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  30832. }
  30833. }
  30834. return texture;
  30835. };
  30836. Texture.LoadFromDataString = function (name, buffer, scene, deleteBuffer, noMipmap, invertY, samplingMode, onLoad, onError, format) {
  30837. if (deleteBuffer === void 0) { deleteBuffer = false; }
  30838. if (noMipmap === void 0) { noMipmap = false; }
  30839. if (invertY === void 0) { invertY = true; }
  30840. if (samplingMode === void 0) { samplingMode = Texture.TRILINEAR_SAMPLINGMODE; }
  30841. if (onLoad === void 0) { onLoad = null; }
  30842. if (onError === void 0) { onError = null; }
  30843. if (format === void 0) { format = BABYLON.Engine.TEXTUREFORMAT_RGBA; }
  30844. if (name.substr(0, 5) !== "data:") {
  30845. name = "data:" + name;
  30846. }
  30847. return new Texture(name, scene, noMipmap, invertY, samplingMode, onLoad, onError, buffer, deleteBuffer, format);
  30848. };
  30849. // Constants
  30850. Texture.NEAREST_SAMPLINGMODE = 1;
  30851. Texture.NEAREST_NEAREST_MIPLINEAR = 1; // nearest is mag = nearest and min = nearest and mip = linear
  30852. Texture.BILINEAR_SAMPLINGMODE = 2;
  30853. Texture.LINEAR_LINEAR_MIPNEAREST = 2; // Bilinear is mag = linear and min = linear and mip = nearest
  30854. Texture.TRILINEAR_SAMPLINGMODE = 3;
  30855. Texture.LINEAR_LINEAR_MIPLINEAR = 3; // Trilinear is mag = linear and min = linear and mip = linear
  30856. Texture.NEAREST_NEAREST_MIPNEAREST = 4;
  30857. Texture.NEAREST_LINEAR_MIPNEAREST = 5;
  30858. Texture.NEAREST_LINEAR_MIPLINEAR = 6;
  30859. Texture.NEAREST_LINEAR = 7;
  30860. Texture.NEAREST_NEAREST = 8;
  30861. Texture.LINEAR_NEAREST_MIPNEAREST = 9;
  30862. Texture.LINEAR_NEAREST_MIPLINEAR = 10;
  30863. Texture.LINEAR_LINEAR = 11;
  30864. Texture.LINEAR_NEAREST = 12;
  30865. Texture.EXPLICIT_MODE = 0;
  30866. Texture.SPHERICAL_MODE = 1;
  30867. Texture.PLANAR_MODE = 2;
  30868. Texture.CUBIC_MODE = 3;
  30869. Texture.PROJECTION_MODE = 4;
  30870. Texture.SKYBOX_MODE = 5;
  30871. Texture.INVCUBIC_MODE = 6;
  30872. Texture.EQUIRECTANGULAR_MODE = 7;
  30873. Texture.FIXED_EQUIRECTANGULAR_MODE = 8;
  30874. Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE = 9;
  30875. Texture.CLAMP_ADDRESSMODE = 0;
  30876. Texture.WRAP_ADDRESSMODE = 1;
  30877. Texture.MIRROR_ADDRESSMODE = 2;
  30878. /**
  30879. * 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
  30880. */
  30881. Texture.UseSerializedUrlIfAny = false;
  30882. __decorate([
  30883. BABYLON.serialize()
  30884. ], Texture.prototype, "url", void 0);
  30885. __decorate([
  30886. BABYLON.serialize()
  30887. ], Texture.prototype, "uOffset", void 0);
  30888. __decorate([
  30889. BABYLON.serialize()
  30890. ], Texture.prototype, "vOffset", void 0);
  30891. __decorate([
  30892. BABYLON.serialize()
  30893. ], Texture.prototype, "uScale", void 0);
  30894. __decorate([
  30895. BABYLON.serialize()
  30896. ], Texture.prototype, "vScale", void 0);
  30897. __decorate([
  30898. BABYLON.serialize()
  30899. ], Texture.prototype, "uAng", void 0);
  30900. __decorate([
  30901. BABYLON.serialize()
  30902. ], Texture.prototype, "vAng", void 0);
  30903. __decorate([
  30904. BABYLON.serialize()
  30905. ], Texture.prototype, "wAng", void 0);
  30906. __decorate([
  30907. BABYLON.serialize()
  30908. ], Texture.prototype, "isBlocking", null);
  30909. return Texture;
  30910. }(BABYLON.BaseTexture));
  30911. BABYLON.Texture = Texture;
  30912. })(BABYLON || (BABYLON = {}));
  30913. //# sourceMappingURL=babylon.texture.js.map
  30914. var BABYLON;
  30915. (function (BABYLON) {
  30916. /**
  30917. * @hidden
  30918. **/
  30919. var _InstancesBatch = /** @class */ (function () {
  30920. function _InstancesBatch() {
  30921. this.mustReturn = false;
  30922. this.visibleInstances = new Array();
  30923. this.renderSelf = new Array();
  30924. }
  30925. return _InstancesBatch;
  30926. }());
  30927. BABYLON._InstancesBatch = _InstancesBatch;
  30928. var Mesh = /** @class */ (function (_super) {
  30929. __extends(Mesh, _super);
  30930. /**
  30931. * @constructor
  30932. * @param {string} name The value used by scene.getMeshByName() to do a lookup.
  30933. * @param {Scene} scene The scene to add this mesh to.
  30934. * @param {Node} parent The parent of this mesh, if it has one
  30935. * @param {Mesh} source An optional Mesh from which geometry is shared, cloned.
  30936. * @param {boolean} doNotCloneChildren When cloning, skip cloning child meshes of source, default False.
  30937. * When false, achieved by calling a clone(), also passing False.
  30938. * This will make creation of children, recursive.
  30939. * @param {boolean} clonePhysicsImpostor When cloning, include cloning mesh physics impostor, default True.
  30940. */
  30941. function Mesh(name, scene, parent, source, doNotCloneChildren, clonePhysicsImpostor) {
  30942. if (scene === void 0) { scene = null; }
  30943. if (parent === void 0) { parent = null; }
  30944. if (source === void 0) { source = null; }
  30945. if (clonePhysicsImpostor === void 0) { clonePhysicsImpostor = true; }
  30946. var _this = _super.call(this, name, scene) || this;
  30947. // Events
  30948. /**
  30949. * An event triggered before rendering the mesh
  30950. */
  30951. _this.onBeforeRenderObservable = new BABYLON.Observable();
  30952. /**
  30953. * An event triggered after rendering the mesh
  30954. */
  30955. _this.onAfterRenderObservable = new BABYLON.Observable();
  30956. /**
  30957. * An event triggered before drawing the mesh
  30958. */
  30959. _this.onBeforeDrawObservable = new BABYLON.Observable();
  30960. // Members
  30961. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  30962. _this.instances = new Array();
  30963. _this._LODLevels = new Array();
  30964. _this._visibleInstances = {};
  30965. _this._renderIdForInstances = new Array();
  30966. _this._batchCache = new _InstancesBatch();
  30967. _this._instancesBufferSize = 32 * 16 * 4; // let's start with a maximum of 32 instances
  30968. // Use by builder only to know what orientation were the mesh build in.
  30969. _this._originalBuilderSideOrientation = Mesh._DEFAULTSIDE;
  30970. _this.overrideMaterialSideOrientation = null;
  30971. _this._areNormalsFrozen = false; // Will be used by ribbons mainly
  30972. // Will be used to save a source mesh reference, If any
  30973. _this._source = null;
  30974. scene = _this.getScene();
  30975. if (source) {
  30976. // Source mesh
  30977. _this._source = source;
  30978. // Geometry
  30979. if (source._geometry) {
  30980. source._geometry.applyToMesh(_this);
  30981. }
  30982. // Deep copy
  30983. BABYLON.Tools.DeepCopy(source, _this, ["name", "material", "skeleton", "instances", "parent", "uniqueId",
  30984. "source", "metadata", "hasLODLevels", "geometry", "isBlocked", "areNormalsFrozen"], ["_poseMatrix", "_source"]);
  30985. // Metadata
  30986. if (source.metadata && source.metadata.clone) {
  30987. _this.metadata = source.metadata.clone();
  30988. }
  30989. else {
  30990. _this.metadata = source.metadata;
  30991. }
  30992. // Tags
  30993. if (BABYLON.Tags && BABYLON.Tags.HasTags(source)) {
  30994. BABYLON.Tags.AddTagsTo(_this, BABYLON.Tags.GetTags(source, true));
  30995. }
  30996. // Parent
  30997. _this.parent = source.parent;
  30998. // Pivot
  30999. _this.setPivotMatrix(source.getPivotMatrix());
  31000. _this.id = name + "." + source.id;
  31001. // Material
  31002. _this.material = source.material;
  31003. var index;
  31004. if (!doNotCloneChildren) {
  31005. // Children
  31006. var directDescendants = source.getDescendants(true);
  31007. for (var index_1 = 0; index_1 < directDescendants.length; index_1++) {
  31008. var child = directDescendants[index_1];
  31009. if (child.clone) {
  31010. child.clone(name + "." + child.name, _this);
  31011. }
  31012. }
  31013. }
  31014. // Physics clone
  31015. var physicsEngine = _this.getScene().getPhysicsEngine();
  31016. if (clonePhysicsImpostor && physicsEngine) {
  31017. var impostor = physicsEngine.getImpostorForPhysicsObject(source);
  31018. if (impostor) {
  31019. _this.physicsImpostor = impostor.clone(_this);
  31020. }
  31021. }
  31022. // Particles
  31023. for (index = 0; index < scene.particleSystems.length; index++) {
  31024. var system = scene.particleSystems[index];
  31025. if (system.emitter === source) {
  31026. system.clone(system.name, _this);
  31027. }
  31028. }
  31029. _this.computeWorldMatrix(true);
  31030. }
  31031. // Parent
  31032. if (parent !== null) {
  31033. _this.parent = parent;
  31034. }
  31035. return _this;
  31036. }
  31037. Object.defineProperty(Mesh, "FRONTSIDE", {
  31038. /**
  31039. * Mesh side orientation : usually the external or front surface
  31040. */
  31041. get: function () {
  31042. return Mesh._FRONTSIDE;
  31043. },
  31044. enumerable: true,
  31045. configurable: true
  31046. });
  31047. Object.defineProperty(Mesh, "BACKSIDE", {
  31048. /**
  31049. * Mesh side orientation : usually the internal or back surface
  31050. */
  31051. get: function () {
  31052. return Mesh._BACKSIDE;
  31053. },
  31054. enumerable: true,
  31055. configurable: true
  31056. });
  31057. Object.defineProperty(Mesh, "DOUBLESIDE", {
  31058. /**
  31059. * Mesh side orientation : both internal and external or front and back surfaces
  31060. */
  31061. get: function () {
  31062. return Mesh._DOUBLESIDE;
  31063. },
  31064. enumerable: true,
  31065. configurable: true
  31066. });
  31067. Object.defineProperty(Mesh, "DEFAULTSIDE", {
  31068. /**
  31069. * Mesh side orientation : by default, `FRONTSIDE`
  31070. */
  31071. get: function () {
  31072. return Mesh._DEFAULTSIDE;
  31073. },
  31074. enumerable: true,
  31075. configurable: true
  31076. });
  31077. Object.defineProperty(Mesh, "NO_CAP", {
  31078. /**
  31079. * Mesh cap setting : no cap
  31080. */
  31081. get: function () {
  31082. return Mesh._NO_CAP;
  31083. },
  31084. enumerable: true,
  31085. configurable: true
  31086. });
  31087. Object.defineProperty(Mesh, "CAP_START", {
  31088. /**
  31089. * Mesh cap setting : one cap at the beginning of the mesh
  31090. */
  31091. get: function () {
  31092. return Mesh._CAP_START;
  31093. },
  31094. enumerable: true,
  31095. configurable: true
  31096. });
  31097. Object.defineProperty(Mesh, "CAP_END", {
  31098. /**
  31099. * Mesh cap setting : one cap at the end of the mesh
  31100. */
  31101. get: function () {
  31102. return Mesh._CAP_END;
  31103. },
  31104. enumerable: true,
  31105. configurable: true
  31106. });
  31107. Object.defineProperty(Mesh, "CAP_ALL", {
  31108. /**
  31109. * Mesh cap setting : two caps, one at the beginning and one at the end of the mesh
  31110. */
  31111. get: function () {
  31112. return Mesh._CAP_ALL;
  31113. },
  31114. enumerable: true,
  31115. configurable: true
  31116. });
  31117. Object.defineProperty(Mesh.prototype, "onBeforeDraw", {
  31118. set: function (callback) {
  31119. if (this._onBeforeDrawObserver) {
  31120. this.onBeforeDrawObservable.remove(this._onBeforeDrawObserver);
  31121. }
  31122. this._onBeforeDrawObserver = this.onBeforeDrawObservable.add(callback);
  31123. },
  31124. enumerable: true,
  31125. configurable: true
  31126. });
  31127. Object.defineProperty(Mesh.prototype, "morphTargetManager", {
  31128. get: function () {
  31129. return this._morphTargetManager;
  31130. },
  31131. set: function (value) {
  31132. if (this._morphTargetManager === value) {
  31133. return;
  31134. }
  31135. this._morphTargetManager = value;
  31136. this._syncGeometryWithMorphTargetManager();
  31137. },
  31138. enumerable: true,
  31139. configurable: true
  31140. });
  31141. Object.defineProperty(Mesh.prototype, "source", {
  31142. get: function () {
  31143. return this._source;
  31144. },
  31145. enumerable: true,
  31146. configurable: true
  31147. });
  31148. Object.defineProperty(Mesh.prototype, "isUnIndexed", {
  31149. get: function () {
  31150. return this._unIndexed;
  31151. },
  31152. set: function (value) {
  31153. if (this._unIndexed !== value) {
  31154. this._unIndexed = value;
  31155. this._markSubMeshesAsAttributesDirty();
  31156. }
  31157. },
  31158. enumerable: true,
  31159. configurable: true
  31160. });
  31161. // Methods
  31162. /**
  31163. * Returns the string "Mesh".
  31164. */
  31165. Mesh.prototype.getClassName = function () {
  31166. return "Mesh";
  31167. };
  31168. /**
  31169. * Returns a string.
  31170. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  31171. */
  31172. Mesh.prototype.toString = function (fullDetails) {
  31173. var ret = _super.prototype.toString.call(this, fullDetails);
  31174. ret += ", n vertices: " + this.getTotalVertices();
  31175. ret += ", parent: " + (this._waitingParentId ? this._waitingParentId : (this.parent ? this.parent.name : "NONE"));
  31176. if (this.animations) {
  31177. for (var i = 0; i < this.animations.length; i++) {
  31178. ret += ", animation[0]: " + this.animations[i].toString(fullDetails);
  31179. }
  31180. }
  31181. if (fullDetails) {
  31182. if (this._geometry) {
  31183. var ib = this.getIndices();
  31184. var vb = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  31185. if (vb && ib) {
  31186. ret += ", flat shading: " + (vb.length / 3 === ib.length ? "YES" : "NO");
  31187. }
  31188. }
  31189. else {
  31190. ret += ", flat shading: UNKNOWN";
  31191. }
  31192. }
  31193. return ret;
  31194. };
  31195. Mesh.prototype._unBindEffect = function () {
  31196. _super.prototype._unBindEffect.call(this);
  31197. for (var _i = 0, _a = this.instances; _i < _a.length; _i++) {
  31198. var instance = _a[_i];
  31199. instance._unBindEffect();
  31200. }
  31201. };
  31202. Object.defineProperty(Mesh.prototype, "hasLODLevels", {
  31203. /**
  31204. * True if the mesh has some Levels Of Details (LOD).
  31205. * Returns a boolean.
  31206. */
  31207. get: function () {
  31208. return this._LODLevels.length > 0;
  31209. },
  31210. enumerable: true,
  31211. configurable: true
  31212. });
  31213. /**
  31214. * Gets the list of {BABYLON.MeshLODLevel} associated with the current mesh
  31215. * @returns an array of {BABYLON.MeshLODLevel}
  31216. */
  31217. Mesh.prototype.getLODLevels = function () {
  31218. return this._LODLevels;
  31219. };
  31220. Mesh.prototype._sortLODLevels = function () {
  31221. this._LODLevels.sort(function (a, b) {
  31222. if (a.distance < b.distance) {
  31223. return 1;
  31224. }
  31225. if (a.distance > b.distance) {
  31226. return -1;
  31227. }
  31228. return 0;
  31229. });
  31230. };
  31231. /**
  31232. * Add a mesh as LOD level triggered at the given distance.
  31233. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_LOD
  31234. * @param {number} distance The distance from the center of the object to show this level
  31235. * @param {Mesh} mesh The mesh to be added as LOD level
  31236. * @return {Mesh} This mesh (for chaining)
  31237. */
  31238. Mesh.prototype.addLODLevel = function (distance, mesh) {
  31239. if (mesh && mesh._masterMesh) {
  31240. BABYLON.Tools.Warn("You cannot use a mesh as LOD level twice");
  31241. return this;
  31242. }
  31243. var level = new BABYLON.MeshLODLevel(distance, mesh);
  31244. this._LODLevels.push(level);
  31245. if (mesh) {
  31246. mesh._masterMesh = this;
  31247. }
  31248. this._sortLODLevels();
  31249. return this;
  31250. };
  31251. /**
  31252. * Returns the LOD level mesh at the passed distance or null if not found.
  31253. * It is related to the method `addLODLevel(distance, mesh)`.
  31254. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_LOD
  31255. * Returns an object Mesh or `null`.
  31256. */
  31257. Mesh.prototype.getLODLevelAtDistance = function (distance) {
  31258. for (var index = 0; index < this._LODLevels.length; index++) {
  31259. var level = this._LODLevels[index];
  31260. if (level.distance === distance) {
  31261. return level.mesh;
  31262. }
  31263. }
  31264. return null;
  31265. };
  31266. /**
  31267. * Remove a mesh from the LOD array
  31268. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_LOD
  31269. * @param {Mesh} mesh The mesh to be removed.
  31270. * @return {Mesh} This mesh (for chaining)
  31271. */
  31272. Mesh.prototype.removeLODLevel = function (mesh) {
  31273. for (var index = 0; index < this._LODLevels.length; index++) {
  31274. if (this._LODLevels[index].mesh === mesh) {
  31275. this._LODLevels.splice(index, 1);
  31276. if (mesh) {
  31277. mesh._masterMesh = null;
  31278. }
  31279. }
  31280. }
  31281. this._sortLODLevels();
  31282. return this;
  31283. };
  31284. /**
  31285. * Returns the registered LOD mesh distant from the parameter `camera` position if any, else returns the current mesh.
  31286. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_LOD
  31287. */
  31288. Mesh.prototype.getLOD = function (camera, boundingSphere) {
  31289. if (!this._LODLevels || this._LODLevels.length === 0) {
  31290. return this;
  31291. }
  31292. var bSphere;
  31293. if (boundingSphere) {
  31294. bSphere = boundingSphere;
  31295. }
  31296. else {
  31297. var boundingInfo = this.getBoundingInfo();
  31298. bSphere = boundingInfo.boundingSphere;
  31299. }
  31300. var distanceToCamera = bSphere.centerWorld.subtract(camera.globalPosition).length();
  31301. if (this._LODLevels[this._LODLevels.length - 1].distance > distanceToCamera) {
  31302. if (this.onLODLevelSelection) {
  31303. this.onLODLevelSelection(distanceToCamera, this, this._LODLevels[this._LODLevels.length - 1].mesh);
  31304. }
  31305. return this;
  31306. }
  31307. for (var index = 0; index < this._LODLevels.length; index++) {
  31308. var level = this._LODLevels[index];
  31309. if (level.distance < distanceToCamera) {
  31310. if (level.mesh) {
  31311. level.mesh._preActivate();
  31312. level.mesh._updateSubMeshesBoundingInfo(this.worldMatrixFromCache);
  31313. }
  31314. if (this.onLODLevelSelection) {
  31315. this.onLODLevelSelection(distanceToCamera, this, level.mesh);
  31316. }
  31317. return level.mesh;
  31318. }
  31319. }
  31320. if (this.onLODLevelSelection) {
  31321. this.onLODLevelSelection(distanceToCamera, this, this);
  31322. }
  31323. return this;
  31324. };
  31325. Object.defineProperty(Mesh.prototype, "geometry", {
  31326. /**
  31327. * Returns the mesh internal Geometry object.
  31328. */
  31329. get: function () {
  31330. return this._geometry;
  31331. },
  31332. enumerable: true,
  31333. configurable: true
  31334. });
  31335. /**
  31336. * Returns a positive integer : the total number of vertices within the mesh geometry or zero if the mesh has no geometry.
  31337. */
  31338. Mesh.prototype.getTotalVertices = function () {
  31339. if (this._geometry === null || this._geometry === undefined) {
  31340. return 0;
  31341. }
  31342. return this._geometry.getTotalVertices();
  31343. };
  31344. /**
  31345. * Returns an array of integers or floats, or a Float32Array, depending on the requested `kind` (positions, indices, normals, etc).
  31346. * 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.
  31347. * You can force the copy with forceCopy === true
  31348. * Returns null if the mesh has no geometry or no vertex buffer.
  31349. * Possible `kind` values :
  31350. * - BABYLON.VertexBuffer.PositionKind
  31351. * - BABYLON.VertexBuffer.UVKind
  31352. * - BABYLON.VertexBuffer.UV2Kind
  31353. * - BABYLON.VertexBuffer.UV3Kind
  31354. * - BABYLON.VertexBuffer.UV4Kind
  31355. * - BABYLON.VertexBuffer.UV5Kind
  31356. * - BABYLON.VertexBuffer.UV6Kind
  31357. * - BABYLON.VertexBuffer.ColorKind
  31358. * - BABYLON.VertexBuffer.MatricesIndicesKind
  31359. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  31360. * - BABYLON.VertexBuffer.MatricesWeightsKind
  31361. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  31362. */
  31363. Mesh.prototype.getVerticesData = function (kind, copyWhenShared, forceCopy) {
  31364. if (!this._geometry) {
  31365. return null;
  31366. }
  31367. return this._geometry.getVerticesData(kind, copyWhenShared, forceCopy);
  31368. };
  31369. /**
  31370. * Returns the mesh VertexBuffer object from the requested `kind` : positions, indices, normals, etc.
  31371. * Returns `null` if the mesh has no geometry.
  31372. * Possible `kind` values :
  31373. * - BABYLON.VertexBuffer.PositionKind
  31374. * - BABYLON.VertexBuffer.UVKind
  31375. * - BABYLON.VertexBuffer.UV2Kind
  31376. * - BABYLON.VertexBuffer.UV3Kind
  31377. * - BABYLON.VertexBuffer.UV4Kind
  31378. * - BABYLON.VertexBuffer.UV5Kind
  31379. * - BABYLON.VertexBuffer.UV6Kind
  31380. * - BABYLON.VertexBuffer.ColorKind
  31381. * - BABYLON.VertexBuffer.MatricesIndicesKind
  31382. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  31383. * - BABYLON.VertexBuffer.MatricesWeightsKind
  31384. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  31385. */
  31386. Mesh.prototype.getVertexBuffer = function (kind) {
  31387. if (!this._geometry) {
  31388. return null;
  31389. }
  31390. return this._geometry.getVertexBuffer(kind);
  31391. };
  31392. Mesh.prototype.isVerticesDataPresent = function (kind) {
  31393. if (!this._geometry) {
  31394. if (this._delayInfo) {
  31395. return this._delayInfo.indexOf(kind) !== -1;
  31396. }
  31397. return false;
  31398. }
  31399. return this._geometry.isVerticesDataPresent(kind);
  31400. };
  31401. /**
  31402. * Returns a boolean defining if the vertex data for the requested `kind` is updatable.
  31403. * Possible `kind` values :
  31404. * - BABYLON.VertexBuffer.PositionKind
  31405. * - BABYLON.VertexBuffer.UVKind
  31406. * - BABYLON.VertexBuffer.UV2Kind
  31407. * - BABYLON.VertexBuffer.UV3Kind
  31408. * - BABYLON.VertexBuffer.UV4Kind
  31409. * - BABYLON.VertexBuffer.UV5Kind
  31410. * - BABYLON.VertexBuffer.UV6Kind
  31411. * - BABYLON.VertexBuffer.ColorKind
  31412. * - BABYLON.VertexBuffer.MatricesIndicesKind
  31413. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  31414. * - BABYLON.VertexBuffer.MatricesWeightsKind
  31415. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  31416. */
  31417. Mesh.prototype.isVertexBufferUpdatable = function (kind) {
  31418. if (!this._geometry) {
  31419. if (this._delayInfo) {
  31420. return this._delayInfo.indexOf(kind) !== -1;
  31421. }
  31422. return false;
  31423. }
  31424. return this._geometry.isVertexBufferUpdatable(kind);
  31425. };
  31426. /**
  31427. * Returns a string : the list of existing `kinds` of Vertex Data for this mesh.
  31428. * Possible `kind` values :
  31429. * - BABYLON.VertexBuffer.PositionKind
  31430. * - BABYLON.VertexBuffer.UVKind
  31431. * - BABYLON.VertexBuffer.UV2Kind
  31432. * - BABYLON.VertexBuffer.UV3Kind
  31433. * - BABYLON.VertexBuffer.UV4Kind
  31434. * - BABYLON.VertexBuffer.UV5Kind
  31435. * - BABYLON.VertexBuffer.UV6Kind
  31436. * - BABYLON.VertexBuffer.ColorKind
  31437. * - BABYLON.VertexBuffer.MatricesIndicesKind
  31438. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  31439. * - BABYLON.VertexBuffer.MatricesWeightsKind
  31440. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  31441. */
  31442. Mesh.prototype.getVerticesDataKinds = function () {
  31443. if (!this._geometry) {
  31444. var result = new Array();
  31445. if (this._delayInfo) {
  31446. this._delayInfo.forEach(function (kind, index, array) {
  31447. result.push(kind);
  31448. });
  31449. }
  31450. return result;
  31451. }
  31452. return this._geometry.getVerticesDataKinds();
  31453. };
  31454. /**
  31455. * Returns a positive integer : the total number of indices in this mesh geometry.
  31456. * Returns zero if the mesh has no geometry.
  31457. */
  31458. Mesh.prototype.getTotalIndices = function () {
  31459. if (!this._geometry) {
  31460. return 0;
  31461. }
  31462. return this._geometry.getTotalIndices();
  31463. };
  31464. /**
  31465. * Returns an array of integers or a typed array (Int32Array, Uint32Array, Uint16Array) populated with the mesh indices.
  31466. * 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.
  31467. * Returns an empty array if the mesh has no geometry.
  31468. */
  31469. Mesh.prototype.getIndices = function (copyWhenShared) {
  31470. if (!this._geometry) {
  31471. return [];
  31472. }
  31473. return this._geometry.getIndices(copyWhenShared);
  31474. };
  31475. Object.defineProperty(Mesh.prototype, "isBlocked", {
  31476. get: function () {
  31477. return this._masterMesh !== null && this._masterMesh !== undefined;
  31478. },
  31479. enumerable: true,
  31480. configurable: true
  31481. });
  31482. /**
  31483. * Determine if the current mesh is ready to be rendered
  31484. * @param completeCheck defines if a complete check (including materials and lights) has to be done (false by default)
  31485. * @param forceInstanceSupport will check if the mesh will be ready when used with instances (false by default)
  31486. * @returns true if all associated assets are ready (material, textures, shaders)
  31487. */
  31488. Mesh.prototype.isReady = function (completeCheck, forceInstanceSupport) {
  31489. if (completeCheck === void 0) { completeCheck = false; }
  31490. if (forceInstanceSupport === void 0) { forceInstanceSupport = false; }
  31491. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  31492. return false;
  31493. }
  31494. if (!_super.prototype.isReady.call(this, completeCheck)) {
  31495. return false;
  31496. }
  31497. if (!this.subMeshes || this.subMeshes.length === 0) {
  31498. return true;
  31499. }
  31500. if (!completeCheck) {
  31501. return true;
  31502. }
  31503. var engine = this.getEngine();
  31504. var scene = this.getScene();
  31505. var hardwareInstancedRendering = forceInstanceSupport || engine.getCaps().instancedArrays && this.instances.length > 0;
  31506. this.computeWorldMatrix();
  31507. var mat = this.material || scene.defaultMaterial;
  31508. if (mat) {
  31509. if (mat.storeEffectOnSubMeshes) {
  31510. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  31511. var subMesh = _a[_i];
  31512. var effectiveMaterial = subMesh.getMaterial();
  31513. if (effectiveMaterial) {
  31514. if (effectiveMaterial.storeEffectOnSubMeshes) {
  31515. if (!effectiveMaterial.isReadyForSubMesh(this, subMesh, hardwareInstancedRendering)) {
  31516. return false;
  31517. }
  31518. }
  31519. else {
  31520. if (!effectiveMaterial.isReady(this, hardwareInstancedRendering)) {
  31521. return false;
  31522. }
  31523. }
  31524. }
  31525. }
  31526. }
  31527. else {
  31528. if (!mat.isReady(this, hardwareInstancedRendering)) {
  31529. return false;
  31530. }
  31531. }
  31532. }
  31533. // Shadows
  31534. for (var _b = 0, _c = this._lightSources; _b < _c.length; _b++) {
  31535. var light = _c[_b];
  31536. var generator = light.getShadowGenerator();
  31537. if (generator) {
  31538. for (var _d = 0, _e = this.subMeshes; _d < _e.length; _d++) {
  31539. var subMesh = _e[_d];
  31540. if (!generator.isReady(subMesh, hardwareInstancedRendering)) {
  31541. return false;
  31542. }
  31543. }
  31544. }
  31545. }
  31546. // LOD
  31547. for (var _f = 0, _g = this._LODLevels; _f < _g.length; _f++) {
  31548. var lod = _g[_f];
  31549. if (lod.mesh && !lod.mesh.isReady(hardwareInstancedRendering)) {
  31550. return false;
  31551. }
  31552. }
  31553. return true;
  31554. };
  31555. Object.defineProperty(Mesh.prototype, "areNormalsFrozen", {
  31556. /**
  31557. * Boolean : true if the normals aren't to be recomputed on next mesh `positions` array update.
  31558. * This property is pertinent only for updatable parametric shapes.
  31559. */
  31560. get: function () {
  31561. return this._areNormalsFrozen;
  31562. },
  31563. enumerable: true,
  31564. configurable: true
  31565. });
  31566. /**
  31567. * This function affects parametric shapes on vertex position update only : ribbons, tubes, etc.
  31568. * It has no effect at all on other shapes.
  31569. * It prevents the mesh normals from being recomputed on next `positions` array update.
  31570. * Returns the Mesh.
  31571. */
  31572. Mesh.prototype.freezeNormals = function () {
  31573. this._areNormalsFrozen = true;
  31574. return this;
  31575. };
  31576. /**
  31577. * This function affects parametric shapes on vertex position update only : ribbons, tubes, etc.
  31578. * It has no effect at all on other shapes.
  31579. * It reactivates the mesh normals computation if it was previously frozen.
  31580. * Returns the Mesh.
  31581. */
  31582. Mesh.prototype.unfreezeNormals = function () {
  31583. this._areNormalsFrozen = false;
  31584. return this;
  31585. };
  31586. Object.defineProperty(Mesh.prototype, "overridenInstanceCount", {
  31587. /**
  31588. * Overrides instance count. Only applicable when custom instanced InterleavedVertexBuffer are used rather than InstancedMeshs
  31589. */
  31590. set: function (count) {
  31591. this._overridenInstanceCount = count;
  31592. },
  31593. enumerable: true,
  31594. configurable: true
  31595. });
  31596. // Methods
  31597. Mesh.prototype._preActivate = function () {
  31598. var sceneRenderId = this.getScene().getRenderId();
  31599. if (this._preActivateId === sceneRenderId) {
  31600. return this;
  31601. }
  31602. this._preActivateId = sceneRenderId;
  31603. this._visibleInstances = null;
  31604. return this;
  31605. };
  31606. Mesh.prototype._preActivateForIntermediateRendering = function (renderId) {
  31607. if (this._visibleInstances) {
  31608. this._visibleInstances.intermediateDefaultRenderId = renderId;
  31609. }
  31610. return this;
  31611. };
  31612. Mesh.prototype._registerInstanceForRenderId = function (instance, renderId) {
  31613. if (!this._visibleInstances) {
  31614. this._visibleInstances = {};
  31615. this._visibleInstances.defaultRenderId = renderId;
  31616. this._visibleInstances.selfDefaultRenderId = this._renderId;
  31617. }
  31618. if (!this._visibleInstances[renderId]) {
  31619. this._visibleInstances[renderId] = new Array();
  31620. }
  31621. this._visibleInstances[renderId].push(instance);
  31622. return this;
  31623. };
  31624. /**
  31625. * This method recomputes and sets a new BoundingInfo to the mesh unless it is locked.
  31626. * This means the mesh underlying bounding box and sphere are recomputed.
  31627. * Returns the Mesh.
  31628. */
  31629. Mesh.prototype.refreshBoundingInfo = function () {
  31630. return this._refreshBoundingInfo(false);
  31631. };
  31632. Mesh.prototype._refreshBoundingInfo = function (applySkeleton) {
  31633. if (this._boundingInfo && this._boundingInfo.isLocked) {
  31634. return this;
  31635. }
  31636. var data = this._getPositionData(applySkeleton);
  31637. if (data) {
  31638. var extend = BABYLON.Tools.ExtractMinAndMax(data, 0, this.getTotalVertices());
  31639. this._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  31640. }
  31641. if (this.subMeshes) {
  31642. for (var index = 0; index < this.subMeshes.length; index++) {
  31643. this.subMeshes[index].refreshBoundingInfo();
  31644. }
  31645. }
  31646. this._updateBoundingInfo();
  31647. return this;
  31648. };
  31649. Mesh.prototype._getPositionData = function (applySkeleton) {
  31650. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  31651. if (data && applySkeleton && this.skeleton) {
  31652. data = BABYLON.Tools.Slice(data);
  31653. var matricesIndicesData = this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind);
  31654. var matricesWeightsData = this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind);
  31655. if (matricesWeightsData && matricesIndicesData) {
  31656. var needExtras = this.numBoneInfluencers > 4;
  31657. var matricesIndicesExtraData = needExtras ? this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind) : null;
  31658. var matricesWeightsExtraData = needExtras ? this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind) : null;
  31659. var skeletonMatrices = this.skeleton.getTransformMatrices(this);
  31660. var tempVector = BABYLON.Tmp.Vector3[0];
  31661. var finalMatrix = BABYLON.Tmp.Matrix[0];
  31662. var tempMatrix = BABYLON.Tmp.Matrix[1];
  31663. var matWeightIdx = 0;
  31664. for (var index = 0; index < data.length; index += 3, matWeightIdx += 4) {
  31665. finalMatrix.reset();
  31666. var inf;
  31667. var weight;
  31668. for (inf = 0; inf < 4; inf++) {
  31669. weight = matricesWeightsData[matWeightIdx + inf];
  31670. if (weight <= 0)
  31671. break;
  31672. BABYLON.Matrix.FromFloat32ArrayToRefScaled(skeletonMatrices, Math.floor(matricesIndicesData[matWeightIdx + inf] * 16), weight, tempMatrix);
  31673. finalMatrix.addToSelf(tempMatrix);
  31674. }
  31675. if (needExtras) {
  31676. for (inf = 0; inf < 4; inf++) {
  31677. weight = matricesWeightsExtraData[matWeightIdx + inf];
  31678. if (weight <= 0)
  31679. break;
  31680. BABYLON.Matrix.FromFloat32ArrayToRefScaled(skeletonMatrices, Math.floor(matricesIndicesExtraData[matWeightIdx + inf] * 16), weight, tempMatrix);
  31681. finalMatrix.addToSelf(tempMatrix);
  31682. }
  31683. }
  31684. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(data[index], data[index + 1], data[index + 2], finalMatrix, tempVector);
  31685. tempVector.toArray(data, index);
  31686. }
  31687. }
  31688. }
  31689. return data;
  31690. };
  31691. Mesh.prototype._createGlobalSubMesh = function (force) {
  31692. var totalVertices = this.getTotalVertices();
  31693. if (!totalVertices || !this.getIndices()) {
  31694. return null;
  31695. }
  31696. // Check if we need to recreate the submeshes
  31697. if (this.subMeshes && this.subMeshes.length > 0) {
  31698. var ib = this.getIndices();
  31699. if (!ib) {
  31700. return null;
  31701. }
  31702. var totalIndices = ib.length;
  31703. var needToRecreate = false;
  31704. if (force) {
  31705. needToRecreate = true;
  31706. }
  31707. else {
  31708. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  31709. var submesh = _a[_i];
  31710. if (submesh.indexStart + submesh.indexCount >= totalIndices) {
  31711. needToRecreate = true;
  31712. break;
  31713. }
  31714. if (submesh.verticesStart + submesh.verticesCount >= totalVertices) {
  31715. needToRecreate = true;
  31716. break;
  31717. }
  31718. }
  31719. }
  31720. if (!needToRecreate) {
  31721. return this.subMeshes[0];
  31722. }
  31723. }
  31724. this.releaseSubMeshes();
  31725. return new BABYLON.SubMesh(0, 0, totalVertices, 0, this.getTotalIndices(), this);
  31726. };
  31727. Mesh.prototype.subdivide = function (count) {
  31728. if (count < 1) {
  31729. return;
  31730. }
  31731. var totalIndices = this.getTotalIndices();
  31732. var subdivisionSize = (totalIndices / count) | 0;
  31733. var offset = 0;
  31734. // Ensure that subdivisionSize is a multiple of 3
  31735. while (subdivisionSize % 3 !== 0) {
  31736. subdivisionSize++;
  31737. }
  31738. this.releaseSubMeshes();
  31739. for (var index = 0; index < count; index++) {
  31740. if (offset >= totalIndices) {
  31741. break;
  31742. }
  31743. BABYLON.SubMesh.CreateFromIndices(0, offset, Math.min(subdivisionSize, totalIndices - offset), this);
  31744. offset += subdivisionSize;
  31745. }
  31746. this.synchronizeInstances();
  31747. };
  31748. Mesh.prototype.setVerticesData = function (kind, data, updatable, stride) {
  31749. if (updatable === void 0) { updatable = false; }
  31750. if (!this._geometry) {
  31751. var vertexData = new BABYLON.VertexData();
  31752. vertexData.set(data, kind);
  31753. var scene = this.getScene();
  31754. new BABYLON.Geometry(BABYLON.Geometry.RandomId(), scene, vertexData, updatable, this);
  31755. }
  31756. else {
  31757. this._geometry.setVerticesData(kind, data, updatable, stride);
  31758. }
  31759. return this;
  31760. };
  31761. Mesh.prototype.markVerticesDataAsUpdatable = function (kind, updatable) {
  31762. if (updatable === void 0) { updatable = true; }
  31763. var vb = this.getVertexBuffer(kind);
  31764. if (!vb || vb.isUpdatable() === updatable) {
  31765. return;
  31766. }
  31767. this.setVerticesData(kind, this.getVerticesData(kind), updatable);
  31768. };
  31769. /**
  31770. * Sets the mesh VertexBuffer.
  31771. * Returns the Mesh.
  31772. */
  31773. Mesh.prototype.setVerticesBuffer = function (buffer) {
  31774. if (!this._geometry) {
  31775. this._geometry = BABYLON.Geometry.CreateGeometryForMesh(this);
  31776. }
  31777. this._geometry.setVerticesBuffer(buffer);
  31778. return this;
  31779. };
  31780. Mesh.prototype.updateVerticesData = function (kind, data, updateExtends, makeItUnique) {
  31781. if (!this._geometry) {
  31782. return this;
  31783. }
  31784. if (!makeItUnique) {
  31785. this._geometry.updateVerticesData(kind, data, updateExtends);
  31786. }
  31787. else {
  31788. this.makeGeometryUnique();
  31789. this.updateVerticesData(kind, data, updateExtends, false);
  31790. }
  31791. return this;
  31792. };
  31793. /**
  31794. * This method updates the vertex positions of an updatable mesh according to the `positionFunction` returned values.
  31795. * tuto : http://doc.babylonjs.com/tutorials/How_to_dynamically_morph_a_mesh#other-shapes-updatemeshpositions
  31796. * The parameter `positionFunction` is a simple JS function what is passed the mesh `positions` array. It doesn't need to return anything.
  31797. * The parameter `computeNormals` is a boolean (default true) to enable/disable the mesh normal recomputation after the vertex position update.
  31798. * Returns the Mesh.
  31799. */
  31800. Mesh.prototype.updateMeshPositions = function (positionFunction, computeNormals) {
  31801. if (computeNormals === void 0) { computeNormals = true; }
  31802. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  31803. if (!positions) {
  31804. return this;
  31805. }
  31806. positionFunction(positions);
  31807. this.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions, false, false);
  31808. if (computeNormals) {
  31809. var indices = this.getIndices();
  31810. var normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  31811. if (!normals) {
  31812. return this;
  31813. }
  31814. BABYLON.VertexData.ComputeNormals(positions, indices, normals);
  31815. this.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normals, false, false);
  31816. }
  31817. return this;
  31818. };
  31819. /**
  31820. * Creates a un-shared specific occurence of the geometry for the mesh.
  31821. * Returns the Mesh.
  31822. */
  31823. Mesh.prototype.makeGeometryUnique = function () {
  31824. if (!this._geometry) {
  31825. return this;
  31826. }
  31827. var oldGeometry = this._geometry;
  31828. var geometry = this._geometry.copy(BABYLON.Geometry.RandomId());
  31829. oldGeometry.releaseForMesh(this, true);
  31830. geometry.applyToMesh(this);
  31831. return this;
  31832. };
  31833. Mesh.prototype.setIndices = function (indices, totalVertices, updatable) {
  31834. if (totalVertices === void 0) { totalVertices = null; }
  31835. if (updatable === void 0) { updatable = false; }
  31836. if (!this._geometry) {
  31837. var vertexData = new BABYLON.VertexData();
  31838. vertexData.indices = indices;
  31839. var scene = this.getScene();
  31840. new BABYLON.Geometry(BABYLON.Geometry.RandomId(), scene, vertexData, updatable, this);
  31841. }
  31842. else {
  31843. this._geometry.setIndices(indices, totalVertices, updatable);
  31844. }
  31845. return this;
  31846. };
  31847. /**
  31848. * Update the current index buffer
  31849. * Expects an array populated with integers or a typed array (Int32Array, Uint32Array, Uint16Array)
  31850. * Returns the Mesh.
  31851. */
  31852. Mesh.prototype.updateIndices = function (indices, offset) {
  31853. if (!this._geometry) {
  31854. return this;
  31855. }
  31856. this._geometry.updateIndices(indices, offset);
  31857. return this;
  31858. };
  31859. /**
  31860. * Invert the geometry to move from a right handed system to a left handed one.
  31861. * Returns the Mesh.
  31862. */
  31863. Mesh.prototype.toLeftHanded = function () {
  31864. if (!this._geometry) {
  31865. return this;
  31866. }
  31867. this._geometry.toLeftHanded();
  31868. return this;
  31869. };
  31870. Mesh.prototype._bind = function (subMesh, effect, fillMode) {
  31871. if (!this._geometry) {
  31872. return this;
  31873. }
  31874. var engine = this.getScene().getEngine();
  31875. // Wireframe
  31876. var indexToBind;
  31877. if (this._unIndexed) {
  31878. indexToBind = null;
  31879. }
  31880. else {
  31881. switch (fillMode) {
  31882. case BABYLON.Material.PointFillMode:
  31883. indexToBind = null;
  31884. break;
  31885. case BABYLON.Material.WireFrameFillMode:
  31886. indexToBind = subMesh.getLinesIndexBuffer(this.getIndices(), engine);
  31887. break;
  31888. default:
  31889. case BABYLON.Material.TriangleFillMode:
  31890. indexToBind = this._unIndexed ? null : this._geometry.getIndexBuffer();
  31891. break;
  31892. }
  31893. }
  31894. // VBOs
  31895. this._geometry._bind(effect, indexToBind);
  31896. return this;
  31897. };
  31898. Mesh.prototype._draw = function (subMesh, fillMode, instancesCount, alternate) {
  31899. if (alternate === void 0) { alternate = false; }
  31900. if (!this._geometry || !this._geometry.getVertexBuffers() || (!this._unIndexed && !this._geometry.getIndexBuffer())) {
  31901. return this;
  31902. }
  31903. this.onBeforeDrawObservable.notifyObservers(this);
  31904. var scene = this.getScene();
  31905. var engine = scene.getEngine();
  31906. if (this._unIndexed || fillMode == BABYLON.Material.PointFillMode) {
  31907. // or triangles as points
  31908. engine.drawArraysType(fillMode, subMesh.verticesStart, subMesh.verticesCount, instancesCount);
  31909. }
  31910. else if (fillMode == BABYLON.Material.WireFrameFillMode) {
  31911. // Triangles as wireframe
  31912. engine.drawElementsType(fillMode, 0, subMesh.linesIndexCount, instancesCount);
  31913. }
  31914. else {
  31915. engine.drawElementsType(fillMode, subMesh.indexStart, subMesh.indexCount, instancesCount);
  31916. }
  31917. if (scene._isAlternateRenderingEnabled && !alternate) {
  31918. var effect = subMesh.effect || this._effectiveMaterial.getEffect();
  31919. if (!effect || !scene.activeCamera) {
  31920. return this;
  31921. }
  31922. scene._switchToAlternateCameraConfiguration(true);
  31923. this._effectiveMaterial.bindView(effect);
  31924. this._effectiveMaterial.bindViewProjection(effect);
  31925. engine.setViewport(scene.activeCamera._alternateCamera.viewport);
  31926. this._draw(subMesh, fillMode, instancesCount, true);
  31927. engine.setViewport(scene.activeCamera.viewport);
  31928. scene._switchToAlternateCameraConfiguration(false);
  31929. this._effectiveMaterial.bindView(effect);
  31930. this._effectiveMaterial.bindViewProjection(effect);
  31931. }
  31932. return this;
  31933. };
  31934. /**
  31935. * Registers for this mesh a javascript function called just before the rendering process.
  31936. * This function is passed the current mesh.
  31937. * Return the Mesh.
  31938. */
  31939. Mesh.prototype.registerBeforeRender = function (func) {
  31940. this.onBeforeRenderObservable.add(func);
  31941. return this;
  31942. };
  31943. /**
  31944. * Disposes a previously registered javascript function called before the rendering.
  31945. * This function is passed the current mesh.
  31946. * Returns the Mesh.
  31947. */
  31948. Mesh.prototype.unregisterBeforeRender = function (func) {
  31949. this.onBeforeRenderObservable.removeCallback(func);
  31950. return this;
  31951. };
  31952. /**
  31953. * Registers for this mesh a javascript function called just after the rendering is complete.
  31954. * This function is passed the current mesh.
  31955. * Returns the Mesh.
  31956. */
  31957. Mesh.prototype.registerAfterRender = function (func) {
  31958. this.onAfterRenderObservable.add(func);
  31959. return this;
  31960. };
  31961. /**
  31962. * Disposes a previously registered javascript function called after the rendering.
  31963. * This function is passed the current mesh.
  31964. * Return the Mesh.
  31965. */
  31966. Mesh.prototype.unregisterAfterRender = function (func) {
  31967. this.onAfterRenderObservable.removeCallback(func);
  31968. return this;
  31969. };
  31970. Mesh.prototype._getInstancesRenderList = function (subMeshId) {
  31971. var scene = this.getScene();
  31972. this._batchCache.mustReturn = false;
  31973. this._batchCache.renderSelf[subMeshId] = this.isEnabled() && this.isVisible;
  31974. this._batchCache.visibleInstances[subMeshId] = null;
  31975. if (this._visibleInstances) {
  31976. var currentRenderId = scene.getRenderId();
  31977. var defaultRenderId = (scene._isInIntermediateRendering() ? this._visibleInstances.intermediateDefaultRenderId : this._visibleInstances.defaultRenderId);
  31978. this._batchCache.visibleInstances[subMeshId] = this._visibleInstances[currentRenderId];
  31979. var selfRenderId = this._renderId;
  31980. if (!this._batchCache.visibleInstances[subMeshId] && defaultRenderId) {
  31981. this._batchCache.visibleInstances[subMeshId] = this._visibleInstances[defaultRenderId];
  31982. currentRenderId = Math.max(defaultRenderId, currentRenderId);
  31983. selfRenderId = Math.max(this._visibleInstances.selfDefaultRenderId, currentRenderId);
  31984. }
  31985. var visibleInstancesForSubMesh = this._batchCache.visibleInstances[subMeshId];
  31986. if (visibleInstancesForSubMesh && visibleInstancesForSubMesh.length) {
  31987. if (this._renderIdForInstances[subMeshId] === currentRenderId) {
  31988. this._batchCache.mustReturn = true;
  31989. return this._batchCache;
  31990. }
  31991. if (currentRenderId !== selfRenderId) {
  31992. this._batchCache.renderSelf[subMeshId] = false;
  31993. }
  31994. }
  31995. this._renderIdForInstances[subMeshId] = currentRenderId;
  31996. }
  31997. return this._batchCache;
  31998. };
  31999. Mesh.prototype._renderWithInstances = function (subMesh, fillMode, batch, effect, engine) {
  32000. var visibleInstances = batch.visibleInstances[subMesh._id];
  32001. if (!visibleInstances) {
  32002. return this;
  32003. }
  32004. var matricesCount = visibleInstances.length + 1;
  32005. var bufferSize = matricesCount * 16 * 4;
  32006. var currentInstancesBufferSize = this._instancesBufferSize;
  32007. var instancesBuffer = this._instancesBuffer;
  32008. while (this._instancesBufferSize < bufferSize) {
  32009. this._instancesBufferSize *= 2;
  32010. }
  32011. if (!this._instancesData || currentInstancesBufferSize != this._instancesBufferSize) {
  32012. this._instancesData = new Float32Array(this._instancesBufferSize / 4);
  32013. }
  32014. var offset = 0;
  32015. var instancesCount = 0;
  32016. var world = this.getWorldMatrix();
  32017. if (batch.renderSelf[subMesh._id]) {
  32018. world.copyToArray(this._instancesData, offset);
  32019. offset += 16;
  32020. instancesCount++;
  32021. }
  32022. if (visibleInstances) {
  32023. for (var instanceIndex = 0; instanceIndex < visibleInstances.length; instanceIndex++) {
  32024. var instance = visibleInstances[instanceIndex];
  32025. instance.getWorldMatrix().copyToArray(this._instancesData, offset);
  32026. offset += 16;
  32027. instancesCount++;
  32028. }
  32029. }
  32030. if (!instancesBuffer || currentInstancesBufferSize != this._instancesBufferSize) {
  32031. if (instancesBuffer) {
  32032. instancesBuffer.dispose();
  32033. }
  32034. instancesBuffer = new BABYLON.Buffer(engine, this._instancesData, true, 16, false, true);
  32035. this._instancesBuffer = instancesBuffer;
  32036. this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world0", 0, 4));
  32037. this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world1", 4, 4));
  32038. this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world2", 8, 4));
  32039. this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world3", 12, 4));
  32040. }
  32041. else {
  32042. instancesBuffer.updateDirectly(this._instancesData, 0, instancesCount);
  32043. }
  32044. this._bind(subMesh, effect, fillMode);
  32045. this._draw(subMesh, fillMode, instancesCount);
  32046. engine.unbindInstanceAttributes();
  32047. return this;
  32048. };
  32049. Mesh.prototype._processRendering = function (subMesh, effect, fillMode, batch, hardwareInstancedRendering, onBeforeDraw, effectiveMaterial) {
  32050. var scene = this.getScene();
  32051. var engine = scene.getEngine();
  32052. if (hardwareInstancedRendering) {
  32053. this._renderWithInstances(subMesh, fillMode, batch, effect, engine);
  32054. }
  32055. else {
  32056. if (batch.renderSelf[subMesh._id]) {
  32057. // Draw
  32058. if (onBeforeDraw) {
  32059. onBeforeDraw(false, this.getWorldMatrix(), effectiveMaterial);
  32060. }
  32061. this._draw(subMesh, fillMode, this._overridenInstanceCount);
  32062. }
  32063. var visibleInstancesForSubMesh = batch.visibleInstances[subMesh._id];
  32064. if (visibleInstancesForSubMesh) {
  32065. for (var instanceIndex = 0; instanceIndex < visibleInstancesForSubMesh.length; instanceIndex++) {
  32066. var instance = visibleInstancesForSubMesh[instanceIndex];
  32067. // World
  32068. var world = instance.getWorldMatrix();
  32069. if (onBeforeDraw) {
  32070. onBeforeDraw(true, world, effectiveMaterial);
  32071. }
  32072. // Draw
  32073. this._draw(subMesh, fillMode);
  32074. }
  32075. }
  32076. }
  32077. return this;
  32078. };
  32079. /**
  32080. * Triggers the draw call for the mesh.
  32081. * Usually, you don't need to call this method by your own because the mesh rendering is handled by the scene rendering manager.
  32082. * Returns the Mesh.
  32083. */
  32084. Mesh.prototype.render = function (subMesh, enableAlphaMode) {
  32085. this._checkOcclusionQuery();
  32086. if (this._isOccluded) {
  32087. return this;
  32088. }
  32089. var scene = this.getScene();
  32090. // Managing instances
  32091. var batch = this._getInstancesRenderList(subMesh._id);
  32092. if (batch.mustReturn) {
  32093. return this;
  32094. }
  32095. // Checking geometry state
  32096. if (!this._geometry || !this._geometry.getVertexBuffers() || (!this._unIndexed && !this._geometry.getIndexBuffer())) {
  32097. return this;
  32098. }
  32099. this.onBeforeRenderObservable.notifyObservers(this);
  32100. var engine = scene.getEngine();
  32101. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  32102. // Material
  32103. var material = subMesh.getMaterial();
  32104. if (!material) {
  32105. return this;
  32106. }
  32107. this._effectiveMaterial = material;
  32108. if (this._effectiveMaterial.storeEffectOnSubMeshes) {
  32109. if (!this._effectiveMaterial.isReadyForSubMesh(this, subMesh, hardwareInstancedRendering)) {
  32110. return this;
  32111. }
  32112. }
  32113. else if (!this._effectiveMaterial.isReady(this, hardwareInstancedRendering)) {
  32114. return this;
  32115. }
  32116. // Alpha mode
  32117. if (enableAlphaMode) {
  32118. engine.setAlphaMode(this._effectiveMaterial.alphaMode);
  32119. }
  32120. // Outline - step 1
  32121. var savedDepthWrite = engine.getDepthWrite();
  32122. if (this.renderOutline) {
  32123. engine.setDepthWrite(false);
  32124. scene.getOutlineRenderer().render(subMesh, batch);
  32125. engine.setDepthWrite(savedDepthWrite);
  32126. }
  32127. var effect;
  32128. if (this._effectiveMaterial.storeEffectOnSubMeshes) {
  32129. effect = subMesh.effect;
  32130. }
  32131. else {
  32132. effect = this._effectiveMaterial.getEffect();
  32133. }
  32134. if (!effect) {
  32135. return this;
  32136. }
  32137. var sideOrientation = this.overrideMaterialSideOrientation;
  32138. if (sideOrientation == null) {
  32139. sideOrientation = this._effectiveMaterial.sideOrientation;
  32140. if (this._getWorldMatrixDeterminant() < 0) {
  32141. sideOrientation = (sideOrientation === BABYLON.Material.ClockWiseSideOrientation ? BABYLON.Material.CounterClockWiseSideOrientation : BABYLON.Material.ClockWiseSideOrientation);
  32142. }
  32143. }
  32144. var reverse = this._effectiveMaterial._preBind(effect, sideOrientation);
  32145. if (this._effectiveMaterial.forceDepthWrite) {
  32146. engine.setDepthWrite(true);
  32147. }
  32148. // Bind
  32149. var fillMode = scene.forcePointsCloud ? BABYLON.Material.PointFillMode : (scene.forceWireframe ? BABYLON.Material.WireFrameFillMode : this._effectiveMaterial.fillMode);
  32150. if (!hardwareInstancedRendering) { // Binding will be done later because we need to add more info to the VB
  32151. this._bind(subMesh, effect, fillMode);
  32152. }
  32153. var world = this.getWorldMatrix();
  32154. if (this._effectiveMaterial.storeEffectOnSubMeshes) {
  32155. this._effectiveMaterial.bindForSubMesh(world, this, subMesh);
  32156. }
  32157. else {
  32158. this._effectiveMaterial.bind(world, this);
  32159. }
  32160. if (!this._effectiveMaterial.backFaceCulling && this._effectiveMaterial.separateCullingPass) {
  32161. engine.setState(true, this._effectiveMaterial.zOffset, false, !reverse);
  32162. this._processRendering(subMesh, effect, fillMode, batch, hardwareInstancedRendering, this._onBeforeDraw, this._effectiveMaterial);
  32163. engine.setState(true, this._effectiveMaterial.zOffset, false, reverse);
  32164. }
  32165. // Draw
  32166. this._processRendering(subMesh, effect, fillMode, batch, hardwareInstancedRendering, this._onBeforeDraw, this._effectiveMaterial);
  32167. // Unbind
  32168. this._effectiveMaterial.unbind();
  32169. // Outline - step 2
  32170. if (this.renderOutline && savedDepthWrite) {
  32171. engine.setDepthWrite(true);
  32172. engine.setColorWrite(false);
  32173. scene.getOutlineRenderer().render(subMesh, batch);
  32174. engine.setColorWrite(true);
  32175. }
  32176. // Overlay
  32177. if (this.renderOverlay) {
  32178. var currentMode = engine.getAlphaMode();
  32179. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  32180. scene.getOutlineRenderer().render(subMesh, batch, true);
  32181. engine.setAlphaMode(currentMode);
  32182. }
  32183. this.onAfterRenderObservable.notifyObservers(this);
  32184. return this;
  32185. };
  32186. Mesh.prototype._onBeforeDraw = function (isInstance, world, effectiveMaterial) {
  32187. if (isInstance && effectiveMaterial) {
  32188. effectiveMaterial.bindOnlyWorldMatrix(world);
  32189. }
  32190. };
  32191. /**
  32192. * Returns an array populated with ParticleSystem objects whose the mesh is the emitter.
  32193. */
  32194. Mesh.prototype.getEmittedParticleSystems = function () {
  32195. var results = new Array();
  32196. for (var index = 0; index < this.getScene().particleSystems.length; index++) {
  32197. var particleSystem = this.getScene().particleSystems[index];
  32198. if (particleSystem.emitter === this) {
  32199. results.push(particleSystem);
  32200. }
  32201. }
  32202. return results;
  32203. };
  32204. /**
  32205. * Returns an array populated with ParticleSystem objects whose the mesh or its children are the emitter.
  32206. */
  32207. Mesh.prototype.getHierarchyEmittedParticleSystems = function () {
  32208. var results = new Array();
  32209. var descendants = this.getDescendants();
  32210. descendants.push(this);
  32211. for (var index = 0; index < this.getScene().particleSystems.length; index++) {
  32212. var particleSystem = this.getScene().particleSystems[index];
  32213. var emitter = particleSystem.emitter;
  32214. if (emitter.position && descendants.indexOf(emitter) !== -1) {
  32215. results.push(particleSystem);
  32216. }
  32217. }
  32218. return results;
  32219. };
  32220. Mesh.prototype._checkDelayState = function () {
  32221. var scene = this.getScene();
  32222. if (this._geometry) {
  32223. this._geometry.load(scene);
  32224. }
  32225. else if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  32226. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADING;
  32227. this._queueLoad(scene);
  32228. }
  32229. return this;
  32230. };
  32231. Mesh.prototype._queueLoad = function (scene) {
  32232. var _this = this;
  32233. scene._addPendingData(this);
  32234. var getBinaryData = (this.delayLoadingFile.indexOf(".babylonbinarymeshdata") !== -1);
  32235. BABYLON.Tools.LoadFile(this.delayLoadingFile, function (data) {
  32236. if (data instanceof ArrayBuffer) {
  32237. _this._delayLoadingFunction(data, _this);
  32238. }
  32239. else {
  32240. _this._delayLoadingFunction(JSON.parse(data), _this);
  32241. }
  32242. _this.instances.forEach(function (instance) {
  32243. instance._syncSubMeshes();
  32244. });
  32245. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  32246. scene._removePendingData(_this);
  32247. }, function () { }, scene.database, getBinaryData);
  32248. return this;
  32249. };
  32250. /**
  32251. * Boolean, true is the mesh in the frustum defined by the Plane objects from the `frustumPlanes` array parameter.
  32252. */
  32253. Mesh.prototype.isInFrustum = function (frustumPlanes) {
  32254. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  32255. return false;
  32256. }
  32257. if (!_super.prototype.isInFrustum.call(this, frustumPlanes)) {
  32258. return false;
  32259. }
  32260. this._checkDelayState();
  32261. return true;
  32262. };
  32263. /**
  32264. * Sets the mesh material by the material or multiMaterial `id` property.
  32265. * The material `id` is a string identifying the material or the multiMaterial.
  32266. * This method returns the Mesh.
  32267. */
  32268. Mesh.prototype.setMaterialByID = function (id) {
  32269. var materials = this.getScene().materials;
  32270. var index;
  32271. for (index = materials.length - 1; index > -1; index--) {
  32272. if (materials[index].id === id) {
  32273. this.material = materials[index];
  32274. return this;
  32275. }
  32276. }
  32277. // Multi
  32278. var multiMaterials = this.getScene().multiMaterials;
  32279. for (index = multiMaterials.length - 1; index > -1; index--) {
  32280. if (multiMaterials[index].id === id) {
  32281. this.material = multiMaterials[index];
  32282. return this;
  32283. }
  32284. }
  32285. return this;
  32286. };
  32287. /**
  32288. * Returns as a new array populated with the mesh material and/or skeleton, if any.
  32289. */
  32290. Mesh.prototype.getAnimatables = function () {
  32291. var results = new Array();
  32292. if (this.material) {
  32293. results.push(this.material);
  32294. }
  32295. if (this.skeleton) {
  32296. results.push(this.skeleton);
  32297. }
  32298. return results;
  32299. };
  32300. /**
  32301. * Modifies the mesh geometry according to the passed transformation matrix.
  32302. * This method returns nothing but it really modifies the mesh even if it's originally not set as updatable.
  32303. * The mesh normals are modified accordingly the same transformation.
  32304. * tuto : http://doc.babylonjs.com/tutorials/How_Rotations_and_Translations_Work#baking-transform
  32305. * Note that, under the hood, this method sets a new VertexBuffer each call.
  32306. * Returns the Mesh.
  32307. */
  32308. Mesh.prototype.bakeTransformIntoVertices = function (transform) {
  32309. // Position
  32310. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  32311. return this;
  32312. }
  32313. var submeshes = this.subMeshes.splice(0);
  32314. this._resetPointsArrayCache();
  32315. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  32316. var temp = new Array();
  32317. var index;
  32318. for (index = 0; index < data.length; index += 3) {
  32319. BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.FromArray(data, index), transform).toArray(temp, index);
  32320. }
  32321. this.setVerticesData(BABYLON.VertexBuffer.PositionKind, temp, this.getVertexBuffer(BABYLON.VertexBuffer.PositionKind).isUpdatable());
  32322. // Normals
  32323. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  32324. return this;
  32325. }
  32326. data = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  32327. temp = [];
  32328. for (index = 0; index < data.length; index += 3) {
  32329. BABYLON.Vector3.TransformNormal(BABYLON.Vector3.FromArray(data, index), transform).normalize().toArray(temp, index);
  32330. }
  32331. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, temp, this.getVertexBuffer(BABYLON.VertexBuffer.NormalKind).isUpdatable());
  32332. // flip faces?
  32333. if (transform.m[0] * transform.m[5] * transform.m[10] < 0) {
  32334. this.flipFaces();
  32335. }
  32336. // Restore submeshes
  32337. this.releaseSubMeshes();
  32338. this.subMeshes = submeshes;
  32339. return this;
  32340. };
  32341. /**
  32342. * Modifies the mesh geometry according to its own current World Matrix.
  32343. * The mesh World Matrix is then reset.
  32344. * This method returns nothing but really modifies the mesh even if it's originally not set as updatable.
  32345. * tuto : tuto : http://doc.babylonjs.com/resources/baking_transformations
  32346. * Note that, under the hood, this method sets a new VertexBuffer each call.
  32347. * Returns the Mesh.
  32348. */
  32349. Mesh.prototype.bakeCurrentTransformIntoVertices = function () {
  32350. this.bakeTransformIntoVertices(this.computeWorldMatrix(true));
  32351. this.scaling.copyFromFloats(1, 1, 1);
  32352. this.position.copyFromFloats(0, 0, 0);
  32353. this.rotation.copyFromFloats(0, 0, 0);
  32354. //only if quaternion is already set
  32355. if (this.rotationQuaternion) {
  32356. this.rotationQuaternion = BABYLON.Quaternion.Identity();
  32357. }
  32358. this._worldMatrix = BABYLON.Matrix.Identity();
  32359. return this;
  32360. };
  32361. Object.defineProperty(Mesh.prototype, "_positions", {
  32362. // Cache
  32363. get: function () {
  32364. if (this._geometry) {
  32365. return this._geometry._positions;
  32366. }
  32367. return null;
  32368. },
  32369. enumerable: true,
  32370. configurable: true
  32371. });
  32372. Mesh.prototype._resetPointsArrayCache = function () {
  32373. if (this._geometry) {
  32374. this._geometry._resetPointsArrayCache();
  32375. }
  32376. return this;
  32377. };
  32378. Mesh.prototype._generatePointsArray = function () {
  32379. if (this._geometry) {
  32380. return this._geometry._generatePointsArray();
  32381. }
  32382. return false;
  32383. };
  32384. /**
  32385. * Returns a new Mesh object generated from the current mesh properties.
  32386. * This method must not get confused with createInstance().
  32387. * The parameter `name` is a string, the name given to the new mesh.
  32388. * The optional parameter `newParent` can be any Node object (default `null`).
  32389. * The optional parameter `doNotCloneChildren` (default `false`) allows/denies the recursive cloning of the original mesh children if any.
  32390. * 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.
  32391. */
  32392. Mesh.prototype.clone = function (name, newParent, doNotCloneChildren, clonePhysicsImpostor) {
  32393. if (clonePhysicsImpostor === void 0) { clonePhysicsImpostor = true; }
  32394. return new Mesh(name, this.getScene(), newParent, this, doNotCloneChildren, clonePhysicsImpostor);
  32395. };
  32396. /**
  32397. * Releases resources associated with this mesh.
  32398. * @param doNotRecurse Set to true to not recurse into each children (recurse into each children by default)
  32399. * @param disposeMaterialAndTextures Set to true to also dispose referenced materials and textures (false by default)
  32400. */
  32401. Mesh.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  32402. var _this = this;
  32403. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  32404. this.morphTargetManager = null;
  32405. if (this._geometry) {
  32406. this._geometry.releaseForMesh(this, true);
  32407. }
  32408. // Sources
  32409. var meshes = this.getScene().meshes;
  32410. meshes.forEach(function (abstractMesh) {
  32411. var mesh = abstractMesh;
  32412. if (mesh._source && mesh._source === _this) {
  32413. mesh._source = null;
  32414. }
  32415. });
  32416. this._source = null;
  32417. // Instances
  32418. if (this._instancesBuffer) {
  32419. this._instancesBuffer.dispose();
  32420. this._instancesBuffer = null;
  32421. }
  32422. while (this.instances.length) {
  32423. this.instances[0].dispose();
  32424. }
  32425. // Effect layers.
  32426. var effectLayers = this.getScene().effectLayers;
  32427. for (var i = 0; i < effectLayers.length; i++) {
  32428. var effectLayer = effectLayers[i];
  32429. if (effectLayer) {
  32430. effectLayer._disposeMesh(this);
  32431. }
  32432. }
  32433. _super.prototype.dispose.call(this, doNotRecurse, disposeMaterialAndTextures);
  32434. };
  32435. /**
  32436. * Modifies the mesh geometry according to a displacement map.
  32437. * 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.
  32438. * The mesh must be set as updatable. Its internal geometry is directly modified, no new buffer are allocated.
  32439. * This method returns nothing.
  32440. * The parameter `url` is a string, the URL from the image file is to be downloaded.
  32441. * The parameters `minHeight` and `maxHeight` are the lower and upper limits of the displacement.
  32442. * 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.
  32443. * The parameter `uvOffset` is an optional vector2 used to offset UV.
  32444. * The parameter `uvScale` is an optional vector2 used to scale UV.
  32445. *
  32446. * Returns the Mesh.
  32447. */
  32448. Mesh.prototype.applyDisplacementMap = function (url, minHeight, maxHeight, onSuccess, uvOffset, uvScale) {
  32449. var _this = this;
  32450. var scene = this.getScene();
  32451. var onload = function (img) {
  32452. // Getting height map data
  32453. var canvas = document.createElement("canvas");
  32454. var context = canvas.getContext("2d");
  32455. var heightMapWidth = img.width;
  32456. var heightMapHeight = img.height;
  32457. canvas.width = heightMapWidth;
  32458. canvas.height = heightMapHeight;
  32459. context.drawImage(img, 0, 0);
  32460. // Create VertexData from map data
  32461. //Cast is due to wrong definition in lib.d.ts from ts 1.3 - https://github.com/Microsoft/TypeScript/issues/949
  32462. var buffer = context.getImageData(0, 0, heightMapWidth, heightMapHeight).data;
  32463. _this.applyDisplacementMapFromBuffer(buffer, heightMapWidth, heightMapHeight, minHeight, maxHeight, uvOffset, uvScale);
  32464. //execute success callback, if set
  32465. if (onSuccess) {
  32466. onSuccess(_this);
  32467. }
  32468. };
  32469. BABYLON.Tools.LoadImage(url, onload, function () { }, scene.database);
  32470. return this;
  32471. };
  32472. /**
  32473. * Modifies the mesh geometry according to a displacementMap buffer.
  32474. * 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.
  32475. * The mesh must be set as updatable. Its internal geometry is directly modified, no new buffer are allocated.
  32476. * This method returns nothing.
  32477. * 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.
  32478. * The parameters `heightMapWidth` and `heightMapHeight` are positive integers to set the width and height of the buffer image.
  32479. * The parameters `minHeight` and `maxHeight` are the lower and upper limits of the displacement.
  32480. * The parameter `uvOffset` is an optional vector2 used to offset UV.
  32481. * The parameter `uvScale` is an optional vector2 used to scale UV.
  32482. *
  32483. * Returns the Mesh.
  32484. */
  32485. Mesh.prototype.applyDisplacementMapFromBuffer = function (buffer, heightMapWidth, heightMapHeight, minHeight, maxHeight, uvOffset, uvScale) {
  32486. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)
  32487. || !this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)
  32488. || !this.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  32489. BABYLON.Tools.Warn("Cannot call applyDisplacementMap: Given mesh is not complete. Position, Normal or UV are missing");
  32490. return this;
  32491. }
  32492. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  32493. var normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  32494. var uvs = this.getVerticesData(BABYLON.VertexBuffer.UVKind);
  32495. var position = BABYLON.Vector3.Zero();
  32496. var normal = BABYLON.Vector3.Zero();
  32497. var uv = BABYLON.Vector2.Zero();
  32498. uvOffset = uvOffset || BABYLON.Vector2.Zero();
  32499. uvScale = uvScale || new BABYLON.Vector2(1, 1);
  32500. for (var index = 0; index < positions.length; index += 3) {
  32501. BABYLON.Vector3.FromArrayToRef(positions, index, position);
  32502. BABYLON.Vector3.FromArrayToRef(normals, index, normal);
  32503. BABYLON.Vector2.FromArrayToRef(uvs, (index / 3) * 2, uv);
  32504. // Compute height
  32505. var u = ((Math.abs(uv.x * uvScale.x + uvOffset.x) * heightMapWidth) % heightMapWidth) | 0;
  32506. var v = ((Math.abs(uv.y * uvScale.y + uvOffset.y) * heightMapHeight) % heightMapHeight) | 0;
  32507. var pos = (u + v * heightMapWidth) * 4;
  32508. var r = buffer[pos] / 255.0;
  32509. var g = buffer[pos + 1] / 255.0;
  32510. var b = buffer[pos + 2] / 255.0;
  32511. var gradient = r * 0.3 + g * 0.59 + b * 0.11;
  32512. normal.normalize();
  32513. normal.scaleInPlace(minHeight + (maxHeight - minHeight) * gradient);
  32514. position = position.add(normal);
  32515. position.toArray(positions, index);
  32516. }
  32517. BABYLON.VertexData.ComputeNormals(positions, this.getIndices(), normals);
  32518. this.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions);
  32519. this.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normals);
  32520. return this;
  32521. };
  32522. /**
  32523. * Modify the mesh to get a flat shading rendering.
  32524. * This means each mesh facet will then have its own normals. Usually new vertices are added in the mesh geometry to get this result.
  32525. * This method returns the Mesh.
  32526. * Warning : the mesh is really modified even if not set originally as updatable and, under the hood, a new VertexBuffer is allocated.
  32527. */
  32528. Mesh.prototype.convertToFlatShadedMesh = function () {
  32529. /// <summary>Update normals and vertices to get a flat shading rendering.</summary>
  32530. /// <summary>Warning: This may imply adding vertices to the mesh in order to get exactly 3 vertices per face</summary>
  32531. var kinds = this.getVerticesDataKinds();
  32532. var vbs = {};
  32533. var data = {};
  32534. var newdata = {};
  32535. var updatableNormals = false;
  32536. var kindIndex;
  32537. var kind;
  32538. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  32539. kind = kinds[kindIndex];
  32540. var vertexBuffer = this.getVertexBuffer(kind);
  32541. if (kind === BABYLON.VertexBuffer.NormalKind) {
  32542. updatableNormals = vertexBuffer.isUpdatable();
  32543. kinds.splice(kindIndex, 1);
  32544. kindIndex--;
  32545. continue;
  32546. }
  32547. vbs[kind] = vertexBuffer;
  32548. data[kind] = vbs[kind].getData();
  32549. newdata[kind] = [];
  32550. }
  32551. // Save previous submeshes
  32552. var previousSubmeshes = this.subMeshes.slice(0);
  32553. var indices = this.getIndices();
  32554. var totalIndices = this.getTotalIndices();
  32555. // Generating unique vertices per face
  32556. var index;
  32557. for (index = 0; index < totalIndices; index++) {
  32558. var vertexIndex = indices[index];
  32559. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  32560. kind = kinds[kindIndex];
  32561. var stride = vbs[kind].getStrideSize();
  32562. for (var offset = 0; offset < stride; offset++) {
  32563. newdata[kind].push(data[kind][vertexIndex * stride + offset]);
  32564. }
  32565. }
  32566. }
  32567. // Updating faces & normal
  32568. var normals = [];
  32569. var positions = newdata[BABYLON.VertexBuffer.PositionKind];
  32570. for (index = 0; index < totalIndices; index += 3) {
  32571. indices[index] = index;
  32572. indices[index + 1] = index + 1;
  32573. indices[index + 2] = index + 2;
  32574. var p1 = BABYLON.Vector3.FromArray(positions, index * 3);
  32575. var p2 = BABYLON.Vector3.FromArray(positions, (index + 1) * 3);
  32576. var p3 = BABYLON.Vector3.FromArray(positions, (index + 2) * 3);
  32577. var p1p2 = p1.subtract(p2);
  32578. var p3p2 = p3.subtract(p2);
  32579. var normal = BABYLON.Vector3.Normalize(BABYLON.Vector3.Cross(p1p2, p3p2));
  32580. // Store same normals for every vertex
  32581. for (var localIndex = 0; localIndex < 3; localIndex++) {
  32582. normals.push(normal.x);
  32583. normals.push(normal.y);
  32584. normals.push(normal.z);
  32585. }
  32586. }
  32587. this.setIndices(indices);
  32588. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals, updatableNormals);
  32589. // Updating vertex buffers
  32590. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  32591. kind = kinds[kindIndex];
  32592. this.setVerticesData(kind, newdata[kind], vbs[kind].isUpdatable());
  32593. }
  32594. // Updating submeshes
  32595. this.releaseSubMeshes();
  32596. for (var submeshIndex = 0; submeshIndex < previousSubmeshes.length; submeshIndex++) {
  32597. var previousOne = previousSubmeshes[submeshIndex];
  32598. BABYLON.SubMesh.AddToMesh(previousOne.materialIndex, previousOne.indexStart, previousOne.indexCount, previousOne.indexStart, previousOne.indexCount, this);
  32599. }
  32600. this.synchronizeInstances();
  32601. return this;
  32602. };
  32603. /**
  32604. * This method removes all the mesh indices and add new vertices (duplication) in order to unfold facets into buffers.
  32605. * In other words, more vertices, no more indices and a single bigger VBO.
  32606. * The mesh is really modified even if not set originally as updatable. Under the hood, a new VertexBuffer is allocated.
  32607. * Returns the Mesh.
  32608. */
  32609. Mesh.prototype.convertToUnIndexedMesh = function () {
  32610. /// <summary>Remove indices by unfolding faces into buffers</summary>
  32611. /// <summary>Warning: This implies adding vertices to the mesh in order to get exactly 3 vertices per face</summary>
  32612. var kinds = this.getVerticesDataKinds();
  32613. var vbs = {};
  32614. var data = {};
  32615. var newdata = {};
  32616. var kindIndex;
  32617. var kind;
  32618. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  32619. kind = kinds[kindIndex];
  32620. var vertexBuffer = this.getVertexBuffer(kind);
  32621. vbs[kind] = vertexBuffer;
  32622. data[kind] = vbs[kind].getData();
  32623. newdata[kind] = [];
  32624. }
  32625. // Save previous submeshes
  32626. var previousSubmeshes = this.subMeshes.slice(0);
  32627. var indices = this.getIndices();
  32628. var totalIndices = this.getTotalIndices();
  32629. // Generating unique vertices per face
  32630. var index;
  32631. for (index = 0; index < totalIndices; index++) {
  32632. var vertexIndex = indices[index];
  32633. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  32634. kind = kinds[kindIndex];
  32635. var stride = vbs[kind].getStrideSize();
  32636. for (var offset = 0; offset < stride; offset++) {
  32637. newdata[kind].push(data[kind][vertexIndex * stride + offset]);
  32638. }
  32639. }
  32640. }
  32641. // Updating indices
  32642. for (index = 0; index < totalIndices; index += 3) {
  32643. indices[index] = index;
  32644. indices[index + 1] = index + 1;
  32645. indices[index + 2] = index + 2;
  32646. }
  32647. this.setIndices(indices);
  32648. // Updating vertex buffers
  32649. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  32650. kind = kinds[kindIndex];
  32651. this.setVerticesData(kind, newdata[kind], vbs[kind].isUpdatable());
  32652. }
  32653. // Updating submeshes
  32654. this.releaseSubMeshes();
  32655. for (var submeshIndex = 0; submeshIndex < previousSubmeshes.length; submeshIndex++) {
  32656. var previousOne = previousSubmeshes[submeshIndex];
  32657. BABYLON.SubMesh.AddToMesh(previousOne.materialIndex, previousOne.indexStart, previousOne.indexCount, previousOne.indexStart, previousOne.indexCount, this);
  32658. }
  32659. this._unIndexed = true;
  32660. this.synchronizeInstances();
  32661. return this;
  32662. };
  32663. /**
  32664. * Inverses facet orientations and inverts also the normals with `flipNormals` (default `false`) if true.
  32665. * This method returns the Mesh.
  32666. * Warning : the mesh is really modified even if not set originally as updatable. A new VertexBuffer is created under the hood each call.
  32667. */
  32668. Mesh.prototype.flipFaces = function (flipNormals) {
  32669. if (flipNormals === void 0) { flipNormals = false; }
  32670. var vertex_data = BABYLON.VertexData.ExtractFromMesh(this);
  32671. var i;
  32672. if (flipNormals && this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind) && vertex_data.normals) {
  32673. for (i = 0; i < vertex_data.normals.length; i++) {
  32674. vertex_data.normals[i] *= -1;
  32675. }
  32676. }
  32677. if (vertex_data.indices) {
  32678. var temp;
  32679. for (i = 0; i < vertex_data.indices.length; i += 3) {
  32680. // reassign indices
  32681. temp = vertex_data.indices[i + 1];
  32682. vertex_data.indices[i + 1] = vertex_data.indices[i + 2];
  32683. vertex_data.indices[i + 2] = temp;
  32684. }
  32685. }
  32686. vertex_data.applyToMesh(this);
  32687. return this;
  32688. };
  32689. // Instances
  32690. /**
  32691. * Creates a new InstancedMesh object from the mesh model.
  32692. * An instance shares the same properties and the same material than its model.
  32693. * Only these properties of each instance can then be set individually :
  32694. * - position
  32695. * - rotation
  32696. * - rotationQuaternion
  32697. * - setPivotMatrix
  32698. * - scaling
  32699. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_Instances
  32700. * Warning : this method is not supported for Line mesh and LineSystem
  32701. */
  32702. Mesh.prototype.createInstance = function (name) {
  32703. return new BABYLON.InstancedMesh(name, this);
  32704. };
  32705. /**
  32706. * Synchronises all the mesh instance submeshes to the current mesh submeshes, if any.
  32707. * After this call, all the mesh instances have the same submeshes than the current mesh.
  32708. * This method returns the Mesh.
  32709. */
  32710. Mesh.prototype.synchronizeInstances = function () {
  32711. for (var instanceIndex = 0; instanceIndex < this.instances.length; instanceIndex++) {
  32712. var instance = this.instances[instanceIndex];
  32713. instance._syncSubMeshes();
  32714. }
  32715. return this;
  32716. };
  32717. /**
  32718. * Simplify the mesh according to the given array of settings.
  32719. * Function will return immediately and will simplify async. It returns the Mesh.
  32720. * @param settings a collection of simplification settings.
  32721. * @param parallelProcessing should all levels calculate parallel or one after the other.
  32722. * @param type the type of simplification to run.
  32723. * @param successCallback optional success callback to be called after the simplification finished processing all settings.
  32724. */
  32725. Mesh.prototype.simplify = function (settings, parallelProcessing, simplificationType, successCallback) {
  32726. if (parallelProcessing === void 0) { parallelProcessing = true; }
  32727. if (simplificationType === void 0) { simplificationType = BABYLON.SimplificationType.QUADRATIC; }
  32728. this.getScene().simplificationQueue.addTask({
  32729. settings: settings,
  32730. parallelProcessing: parallelProcessing,
  32731. mesh: this,
  32732. simplificationType: simplificationType,
  32733. successCallback: successCallback
  32734. });
  32735. return this;
  32736. };
  32737. /**
  32738. * Optimization of the mesh's indices, in case a mesh has duplicated vertices.
  32739. * The function will only reorder the indices and will not remove unused vertices to avoid problems with submeshes.
  32740. * This should be used together with the simplification to avoid disappearing triangles.
  32741. * Returns the Mesh.
  32742. * @param successCallback an optional success callback to be called after the optimization finished.
  32743. */
  32744. Mesh.prototype.optimizeIndices = function (successCallback) {
  32745. var _this = this;
  32746. var indices = this.getIndices();
  32747. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  32748. if (!positions || !indices) {
  32749. return this;
  32750. }
  32751. var vectorPositions = new Array();
  32752. for (var pos = 0; pos < positions.length; pos = pos + 3) {
  32753. vectorPositions.push(BABYLON.Vector3.FromArray(positions, pos));
  32754. }
  32755. var dupes = new Array();
  32756. BABYLON.AsyncLoop.SyncAsyncForLoop(vectorPositions.length, 40, function (iteration) {
  32757. var realPos = vectorPositions.length - 1 - iteration;
  32758. var testedPosition = vectorPositions[realPos];
  32759. for (var j = 0; j < realPos; ++j) {
  32760. var againstPosition = vectorPositions[j];
  32761. if (testedPosition.equals(againstPosition)) {
  32762. dupes[realPos] = j;
  32763. break;
  32764. }
  32765. }
  32766. }, function () {
  32767. for (var i = 0; i < indices.length; ++i) {
  32768. indices[i] = dupes[indices[i]] || indices[i];
  32769. }
  32770. //indices are now reordered
  32771. var originalSubMeshes = _this.subMeshes.slice(0);
  32772. _this.setIndices(indices);
  32773. _this.subMeshes = originalSubMeshes;
  32774. if (successCallback) {
  32775. successCallback(_this);
  32776. }
  32777. });
  32778. return this;
  32779. };
  32780. Mesh.prototype.serialize = function (serializationObject) {
  32781. serializationObject.name = this.name;
  32782. serializationObject.id = this.id;
  32783. serializationObject.type = this.getClassName();
  32784. if (BABYLON.Tags && BABYLON.Tags.HasTags(this)) {
  32785. serializationObject.tags = BABYLON.Tags.GetTags(this);
  32786. }
  32787. serializationObject.position = this.position.asArray();
  32788. if (this.rotationQuaternion) {
  32789. serializationObject.rotationQuaternion = this.rotationQuaternion.asArray();
  32790. }
  32791. else if (this.rotation) {
  32792. serializationObject.rotation = this.rotation.asArray();
  32793. }
  32794. serializationObject.scaling = this.scaling.asArray();
  32795. serializationObject.localMatrix = this.getPivotMatrix().asArray();
  32796. serializationObject.isEnabled = this.isEnabled(false);
  32797. serializationObject.isVisible = this.isVisible;
  32798. serializationObject.infiniteDistance = this.infiniteDistance;
  32799. serializationObject.pickable = this.isPickable;
  32800. serializationObject.receiveShadows = this.receiveShadows;
  32801. serializationObject.billboardMode = this.billboardMode;
  32802. serializationObject.visibility = this.visibility;
  32803. serializationObject.checkCollisions = this.checkCollisions;
  32804. serializationObject.isBlocker = this.isBlocker;
  32805. // Parent
  32806. if (this.parent) {
  32807. serializationObject.parentId = this.parent.id;
  32808. }
  32809. // Geometry
  32810. serializationObject.isUnIndexed = this.isUnIndexed;
  32811. var geometry = this._geometry;
  32812. if (geometry) {
  32813. var geometryId = geometry.id;
  32814. serializationObject.geometryId = geometryId;
  32815. // SubMeshes
  32816. serializationObject.subMeshes = [];
  32817. for (var subIndex = 0; subIndex < this.subMeshes.length; subIndex++) {
  32818. var subMesh = this.subMeshes[subIndex];
  32819. serializationObject.subMeshes.push({
  32820. materialIndex: subMesh.materialIndex,
  32821. verticesStart: subMesh.verticesStart,
  32822. verticesCount: subMesh.verticesCount,
  32823. indexStart: subMesh.indexStart,
  32824. indexCount: subMesh.indexCount
  32825. });
  32826. }
  32827. }
  32828. // Material
  32829. if (this.material) {
  32830. serializationObject.materialId = this.material.id;
  32831. }
  32832. else {
  32833. this.material = null;
  32834. }
  32835. // Morph targets
  32836. if (this.morphTargetManager) {
  32837. serializationObject.morphTargetManagerId = this.morphTargetManager.uniqueId;
  32838. }
  32839. // Skeleton
  32840. if (this.skeleton) {
  32841. serializationObject.skeletonId = this.skeleton.id;
  32842. }
  32843. // Physics
  32844. //TODO implement correct serialization for physics impostors.
  32845. var impostor = this.getPhysicsImpostor();
  32846. if (impostor) {
  32847. serializationObject.physicsMass = impostor.getParam("mass");
  32848. serializationObject.physicsFriction = impostor.getParam("friction");
  32849. serializationObject.physicsRestitution = impostor.getParam("mass");
  32850. serializationObject.physicsImpostor = impostor.type;
  32851. }
  32852. // Metadata
  32853. if (this.metadata) {
  32854. serializationObject.metadata = this.metadata;
  32855. }
  32856. // Instances
  32857. serializationObject.instances = [];
  32858. for (var index = 0; index < this.instances.length; index++) {
  32859. var instance = this.instances[index];
  32860. var serializationInstance = {
  32861. name: instance.name,
  32862. id: instance.id,
  32863. position: instance.position.asArray(),
  32864. scaling: instance.scaling.asArray()
  32865. };
  32866. if (instance.rotationQuaternion) {
  32867. serializationInstance.rotationQuaternion = instance.rotationQuaternion.asArray();
  32868. }
  32869. else if (instance.rotation) {
  32870. serializationInstance.rotation = instance.rotation.asArray();
  32871. }
  32872. serializationObject.instances.push(serializationInstance);
  32873. // Animations
  32874. BABYLON.Animation.AppendSerializedAnimations(instance, serializationInstance);
  32875. serializationInstance.ranges = instance.serializeAnimationRanges();
  32876. }
  32877. //
  32878. // Animations
  32879. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  32880. serializationObject.ranges = this.serializeAnimationRanges();
  32881. // Layer mask
  32882. serializationObject.layerMask = this.layerMask;
  32883. // Alpha
  32884. serializationObject.alphaIndex = this.alphaIndex;
  32885. serializationObject.hasVertexAlpha = this.hasVertexAlpha;
  32886. // Overlay
  32887. serializationObject.overlayAlpha = this.overlayAlpha;
  32888. serializationObject.overlayColor = this.overlayColor.asArray();
  32889. serializationObject.renderOverlay = this.renderOverlay;
  32890. // Fog
  32891. serializationObject.applyFog = this.applyFog;
  32892. // Action Manager
  32893. if (this.actionManager) {
  32894. serializationObject.actions = this.actionManager.serialize(this.name);
  32895. }
  32896. };
  32897. Mesh.prototype._syncGeometryWithMorphTargetManager = function () {
  32898. if (!this.geometry) {
  32899. return;
  32900. }
  32901. this._markSubMeshesAsAttributesDirty();
  32902. var morphTargetManager = this._morphTargetManager;
  32903. if (morphTargetManager && morphTargetManager.vertexCount) {
  32904. if (morphTargetManager.vertexCount !== this.getTotalVertices()) {
  32905. BABYLON.Tools.Error("Mesh is incompatible with morph targets. Targets and mesh must all have the same vertices count.");
  32906. this.morphTargetManager = null;
  32907. return;
  32908. }
  32909. for (var index = 0; index < morphTargetManager.numInfluencers; index++) {
  32910. var morphTarget = morphTargetManager.getActiveTarget(index);
  32911. var positions = morphTarget.getPositions();
  32912. if (!positions) {
  32913. BABYLON.Tools.Error("Invalid morph target. Target must have positions.");
  32914. return;
  32915. }
  32916. this.geometry.setVerticesData(BABYLON.VertexBuffer.PositionKind + index, positions, false, 3);
  32917. var normals = morphTarget.getNormals();
  32918. if (normals) {
  32919. this.geometry.setVerticesData(BABYLON.VertexBuffer.NormalKind + index, normals, false, 3);
  32920. }
  32921. var tangents = morphTarget.getTangents();
  32922. if (tangents) {
  32923. this.geometry.setVerticesData(BABYLON.VertexBuffer.TangentKind + index, tangents, false, 3);
  32924. }
  32925. }
  32926. }
  32927. else {
  32928. var index = 0;
  32929. // Positions
  32930. while (this.geometry.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind + index)) {
  32931. this.geometry.removeVerticesData(BABYLON.VertexBuffer.PositionKind + index);
  32932. if (this.geometry.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind + index)) {
  32933. this.geometry.removeVerticesData(BABYLON.VertexBuffer.NormalKind + index);
  32934. }
  32935. if (this.geometry.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind + index)) {
  32936. this.geometry.removeVerticesData(BABYLON.VertexBuffer.TangentKind + index);
  32937. }
  32938. index++;
  32939. }
  32940. }
  32941. };
  32942. // Statics
  32943. /**
  32944. * Returns a new Mesh object parsed from the source provided.
  32945. * The parameter `parsedMesh` is the source.
  32946. * The parameter `rootUrl` is a string, it's the root URL to prefix the `delayLoadingFile` property with
  32947. */
  32948. Mesh.Parse = function (parsedMesh, scene, rootUrl) {
  32949. var mesh;
  32950. if (parsedMesh.type && parsedMesh.type === "GroundMesh") {
  32951. mesh = BABYLON.GroundMesh.Parse(parsedMesh, scene);
  32952. }
  32953. else {
  32954. mesh = new Mesh(parsedMesh.name, scene);
  32955. }
  32956. mesh.id = parsedMesh.id;
  32957. if (BABYLON.Tags) {
  32958. BABYLON.Tags.AddTagsTo(mesh, parsedMesh.tags);
  32959. }
  32960. mesh.position = BABYLON.Vector3.FromArray(parsedMesh.position);
  32961. if (parsedMesh.metadata !== undefined) {
  32962. mesh.metadata = parsedMesh.metadata;
  32963. }
  32964. if (parsedMesh.rotationQuaternion) {
  32965. mesh.rotationQuaternion = BABYLON.Quaternion.FromArray(parsedMesh.rotationQuaternion);
  32966. }
  32967. else if (parsedMesh.rotation) {
  32968. mesh.rotation = BABYLON.Vector3.FromArray(parsedMesh.rotation);
  32969. }
  32970. mesh.scaling = BABYLON.Vector3.FromArray(parsedMesh.scaling);
  32971. if (parsedMesh.localMatrix) {
  32972. mesh.setPreTransformMatrix(BABYLON.Matrix.FromArray(parsedMesh.localMatrix));
  32973. }
  32974. else if (parsedMesh.pivotMatrix) {
  32975. mesh.setPivotMatrix(BABYLON.Matrix.FromArray(parsedMesh.pivotMatrix));
  32976. }
  32977. mesh.setEnabled(parsedMesh.isEnabled);
  32978. mesh.isVisible = parsedMesh.isVisible;
  32979. mesh.infiniteDistance = parsedMesh.infiniteDistance;
  32980. mesh.showBoundingBox = parsedMesh.showBoundingBox;
  32981. mesh.showSubMeshesBoundingBox = parsedMesh.showSubMeshesBoundingBox;
  32982. if (parsedMesh.applyFog !== undefined) {
  32983. mesh.applyFog = parsedMesh.applyFog;
  32984. }
  32985. if (parsedMesh.pickable !== undefined) {
  32986. mesh.isPickable = parsedMesh.pickable;
  32987. }
  32988. if (parsedMesh.alphaIndex !== undefined) {
  32989. mesh.alphaIndex = parsedMesh.alphaIndex;
  32990. }
  32991. mesh.receiveShadows = parsedMesh.receiveShadows;
  32992. mesh.billboardMode = parsedMesh.billboardMode;
  32993. if (parsedMesh.visibility !== undefined) {
  32994. mesh.visibility = parsedMesh.visibility;
  32995. }
  32996. mesh.checkCollisions = parsedMesh.checkCollisions;
  32997. if (parsedMesh.isBlocker !== undefined) {
  32998. mesh.isBlocker = parsedMesh.isBlocker;
  32999. }
  33000. mesh._shouldGenerateFlatShading = parsedMesh.useFlatShading;
  33001. // freezeWorldMatrix
  33002. if (parsedMesh.freezeWorldMatrix) {
  33003. mesh._waitingFreezeWorldMatrix = parsedMesh.freezeWorldMatrix;
  33004. }
  33005. // Parent
  33006. if (parsedMesh.parentId) {
  33007. mesh._waitingParentId = parsedMesh.parentId;
  33008. }
  33009. // Actions
  33010. if (parsedMesh.actions !== undefined) {
  33011. mesh._waitingActions = parsedMesh.actions;
  33012. }
  33013. // Overlay
  33014. if (parsedMesh.overlayAlpha !== undefined) {
  33015. mesh.overlayAlpha = parsedMesh.overlayAlpha;
  33016. }
  33017. if (parsedMesh.overlayColor !== undefined) {
  33018. mesh.overlayColor = BABYLON.Color3.FromArray(parsedMesh.overlayColor);
  33019. }
  33020. if (parsedMesh.renderOverlay !== undefined) {
  33021. mesh.renderOverlay = parsedMesh.renderOverlay;
  33022. }
  33023. // Geometry
  33024. mesh.isUnIndexed = !!parsedMesh.isUnIndexed;
  33025. mesh.hasVertexAlpha = parsedMesh.hasVertexAlpha;
  33026. if (parsedMesh.delayLoadingFile) {
  33027. mesh.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  33028. mesh.delayLoadingFile = rootUrl + parsedMesh.delayLoadingFile;
  33029. mesh._boundingInfo = new BABYLON.BoundingInfo(BABYLON.Vector3.FromArray(parsedMesh.boundingBoxMinimum), BABYLON.Vector3.FromArray(parsedMesh.boundingBoxMaximum));
  33030. if (parsedMesh._binaryInfo) {
  33031. mesh._binaryInfo = parsedMesh._binaryInfo;
  33032. }
  33033. mesh._delayInfo = [];
  33034. if (parsedMesh.hasUVs) {
  33035. mesh._delayInfo.push(BABYLON.VertexBuffer.UVKind);
  33036. }
  33037. if (parsedMesh.hasUVs2) {
  33038. mesh._delayInfo.push(BABYLON.VertexBuffer.UV2Kind);
  33039. }
  33040. if (parsedMesh.hasUVs3) {
  33041. mesh._delayInfo.push(BABYLON.VertexBuffer.UV3Kind);
  33042. }
  33043. if (parsedMesh.hasUVs4) {
  33044. mesh._delayInfo.push(BABYLON.VertexBuffer.UV4Kind);
  33045. }
  33046. if (parsedMesh.hasUVs5) {
  33047. mesh._delayInfo.push(BABYLON.VertexBuffer.UV5Kind);
  33048. }
  33049. if (parsedMesh.hasUVs6) {
  33050. mesh._delayInfo.push(BABYLON.VertexBuffer.UV6Kind);
  33051. }
  33052. if (parsedMesh.hasColors) {
  33053. mesh._delayInfo.push(BABYLON.VertexBuffer.ColorKind);
  33054. }
  33055. if (parsedMesh.hasMatricesIndices) {
  33056. mesh._delayInfo.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  33057. }
  33058. if (parsedMesh.hasMatricesWeights) {
  33059. mesh._delayInfo.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  33060. }
  33061. mesh._delayLoadingFunction = BABYLON.Geometry._ImportGeometry;
  33062. if (BABYLON.SceneLoader.ForceFullSceneLoadingForIncremental) {
  33063. mesh._checkDelayState();
  33064. }
  33065. }
  33066. else {
  33067. BABYLON.Geometry._ImportGeometry(parsedMesh, mesh);
  33068. }
  33069. // Material
  33070. if (parsedMesh.materialId) {
  33071. mesh.setMaterialByID(parsedMesh.materialId);
  33072. }
  33073. else {
  33074. mesh.material = null;
  33075. }
  33076. // Morph targets
  33077. if (parsedMesh.morphTargetManagerId > -1) {
  33078. mesh.morphTargetManager = scene.getMorphTargetManagerById(parsedMesh.morphTargetManagerId);
  33079. }
  33080. // Skeleton
  33081. if (parsedMesh.skeletonId > -1) {
  33082. mesh.skeleton = scene.getLastSkeletonByID(parsedMesh.skeletonId);
  33083. if (parsedMesh.numBoneInfluencers) {
  33084. mesh.numBoneInfluencers = parsedMesh.numBoneInfluencers;
  33085. }
  33086. }
  33087. // Animations
  33088. if (parsedMesh.animations) {
  33089. for (var animationIndex = 0; animationIndex < parsedMesh.animations.length; animationIndex++) {
  33090. var parsedAnimation = parsedMesh.animations[animationIndex];
  33091. mesh.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  33092. }
  33093. BABYLON.Node.ParseAnimationRanges(mesh, parsedMesh, scene);
  33094. }
  33095. if (parsedMesh.autoAnimate) {
  33096. scene.beginAnimation(mesh, parsedMesh.autoAnimateFrom, parsedMesh.autoAnimateTo, parsedMesh.autoAnimateLoop, parsedMesh.autoAnimateSpeed || 1.0);
  33097. }
  33098. // Layer Mask
  33099. if (parsedMesh.layerMask && (!isNaN(parsedMesh.layerMask))) {
  33100. mesh.layerMask = Math.abs(parseInt(parsedMesh.layerMask));
  33101. }
  33102. else {
  33103. mesh.layerMask = 0x0FFFFFFF;
  33104. }
  33105. // Physics
  33106. if (parsedMesh.physicsImpostor) {
  33107. mesh.physicsImpostor = new BABYLON.PhysicsImpostor(mesh, parsedMesh.physicsImpostor, {
  33108. mass: parsedMesh.physicsMass,
  33109. friction: parsedMesh.physicsFriction,
  33110. restitution: parsedMesh.physicsRestitution
  33111. }, scene);
  33112. }
  33113. // Instances
  33114. if (parsedMesh.instances) {
  33115. for (var index = 0; index < parsedMesh.instances.length; index++) {
  33116. var parsedInstance = parsedMesh.instances[index];
  33117. var instance = mesh.createInstance(parsedInstance.name);
  33118. if (parsedInstance.id) {
  33119. instance.id = parsedInstance.id;
  33120. }
  33121. if (BABYLON.Tags) {
  33122. BABYLON.Tags.AddTagsTo(instance, parsedInstance.tags);
  33123. }
  33124. instance.position = BABYLON.Vector3.FromArray(parsedInstance.position);
  33125. if (parsedInstance.parentId) {
  33126. instance._waitingParentId = parsedInstance.parentId;
  33127. }
  33128. if (parsedInstance.rotationQuaternion) {
  33129. instance.rotationQuaternion = BABYLON.Quaternion.FromArray(parsedInstance.rotationQuaternion);
  33130. }
  33131. else if (parsedInstance.rotation) {
  33132. instance.rotation = BABYLON.Vector3.FromArray(parsedInstance.rotation);
  33133. }
  33134. instance.scaling = BABYLON.Vector3.FromArray(parsedInstance.scaling);
  33135. instance.checkCollisions = mesh.checkCollisions;
  33136. if (parsedMesh.animations) {
  33137. for (animationIndex = 0; animationIndex < parsedMesh.animations.length; animationIndex++) {
  33138. parsedAnimation = parsedMesh.animations[animationIndex];
  33139. instance.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  33140. }
  33141. BABYLON.Node.ParseAnimationRanges(instance, parsedMesh, scene);
  33142. }
  33143. }
  33144. }
  33145. return mesh;
  33146. };
  33147. /**
  33148. * Creates a ribbon mesh.
  33149. * Please consider using the same method from the MeshBuilder class instead.
  33150. * 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.
  33151. *
  33152. * Please read this full tutorial to understand how to design a ribbon : http://doc.babylonjs.com/tutorials/Ribbon_Tutorial
  33153. * The parameter `pathArray` is a required array of paths, what are each an array of successive Vector3. The pathArray parameter depicts the ribbon geometry.
  33154. * The parameter `closeArray` (boolean, default false) creates a seam between the first and the last paths of the path array.
  33155. * The parameter `closePath` (boolean, default false) creates a seam between the first and the last points of each path of the path array.
  33156. * 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.
  33157. * 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.
  33158. * 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
  33159. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  33160. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  33161. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33162. */
  33163. Mesh.CreateRibbon = function (name, pathArray, closeArray, closePath, offset, scene, updatable, sideOrientation, instance) {
  33164. if (closeArray === void 0) { closeArray = false; }
  33165. if (updatable === void 0) { updatable = false; }
  33166. return BABYLON.MeshBuilder.CreateRibbon(name, {
  33167. pathArray: pathArray,
  33168. closeArray: closeArray,
  33169. closePath: closePath,
  33170. offset: offset,
  33171. updatable: updatable,
  33172. sideOrientation: sideOrientation,
  33173. instance: instance
  33174. }, scene);
  33175. };
  33176. /**
  33177. * Creates a plane polygonal mesh. By default, this is a disc.
  33178. * Please consider using the same method from the MeshBuilder class instead.
  33179. * The parameter `radius` sets the radius size (float) of the polygon (default 0.5).
  33180. * 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.
  33181. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  33182. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  33183. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33184. */
  33185. Mesh.CreateDisc = function (name, radius, tessellation, scene, updatable, sideOrientation) {
  33186. if (scene === void 0) { scene = null; }
  33187. var options = {
  33188. radius: radius,
  33189. tessellation: tessellation,
  33190. sideOrientation: sideOrientation,
  33191. updatable: updatable
  33192. };
  33193. return BABYLON.MeshBuilder.CreateDisc(name, options, scene);
  33194. };
  33195. /**
  33196. * Creates a box mesh.
  33197. * Please consider using the same method from the MeshBuilder class instead.
  33198. * The parameter `size` sets the size (float) of each box side (default 1).
  33199. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  33200. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  33201. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33202. */
  33203. Mesh.CreateBox = function (name, size, scene, updatable, sideOrientation) {
  33204. if (scene === void 0) { scene = null; }
  33205. var options = {
  33206. size: size,
  33207. sideOrientation: sideOrientation,
  33208. updatable: updatable
  33209. };
  33210. return BABYLON.MeshBuilder.CreateBox(name, options, scene);
  33211. };
  33212. /**
  33213. * Creates a sphere mesh.
  33214. * Please consider using the same method from the MeshBuilder class instead.
  33215. * The parameter `diameter` sets the diameter size (float) of the sphere (default 1).
  33216. * The parameter `segments` sets the sphere number of horizontal stripes (positive integer, default 32).
  33217. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  33218. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  33219. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33220. */
  33221. Mesh.CreateSphere = function (name, segments, diameter, scene, updatable, sideOrientation) {
  33222. var options = {
  33223. segments: segments,
  33224. diameterX: diameter,
  33225. diameterY: diameter,
  33226. diameterZ: diameter,
  33227. sideOrientation: sideOrientation,
  33228. updatable: updatable
  33229. };
  33230. return BABYLON.MeshBuilder.CreateSphere(name, options, scene);
  33231. };
  33232. /**
  33233. * Creates a cylinder or a cone mesh.
  33234. * Please consider using the same method from the MeshBuilder class instead.
  33235. * The parameter `height` sets the height size (float) of the cylinder/cone (float, default 2).
  33236. * The parameter `diameter` sets the diameter of the top and bottom cap at once (float, default 1).
  33237. * 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.
  33238. * The parameter `tessellation` sets the number of cylinder sides (positive integer, default 24). Set it to 3 to get a prism for instance.
  33239. * The parameter `subdivisions` sets the number of rings along the cylinder height (positive integer, default 1).
  33240. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  33241. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  33242. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33243. */
  33244. Mesh.CreateCylinder = function (name, height, diameterTop, diameterBottom, tessellation, subdivisions, scene, updatable, sideOrientation) {
  33245. if (scene === undefined || !(scene instanceof BABYLON.Scene)) {
  33246. if (scene !== undefined) {
  33247. sideOrientation = updatable || Mesh.DEFAULTSIDE;
  33248. updatable = scene;
  33249. }
  33250. scene = subdivisions;
  33251. subdivisions = 1;
  33252. }
  33253. var options = {
  33254. height: height,
  33255. diameterTop: diameterTop,
  33256. diameterBottom: diameterBottom,
  33257. tessellation: tessellation,
  33258. subdivisions: subdivisions,
  33259. sideOrientation: sideOrientation,
  33260. updatable: updatable
  33261. };
  33262. return BABYLON.MeshBuilder.CreateCylinder(name, options, scene);
  33263. };
  33264. // Torus (Code from SharpDX.org)
  33265. /**
  33266. * Creates a torus mesh.
  33267. * Please consider using the same method from the MeshBuilder class instead.
  33268. * The parameter `diameter` sets the diameter size (float) of the torus (default 1).
  33269. * The parameter `thickness` sets the diameter size of the tube of the torus (float, default 0.5).
  33270. * The parameter `tessellation` sets the number of torus sides (postive integer, default 16).
  33271. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  33272. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  33273. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33274. */
  33275. Mesh.CreateTorus = function (name, diameter, thickness, tessellation, scene, updatable, sideOrientation) {
  33276. var options = {
  33277. diameter: diameter,
  33278. thickness: thickness,
  33279. tessellation: tessellation,
  33280. sideOrientation: sideOrientation,
  33281. updatable: updatable
  33282. };
  33283. return BABYLON.MeshBuilder.CreateTorus(name, options, scene);
  33284. };
  33285. /**
  33286. * Creates a torus knot mesh.
  33287. * Please consider using the same method from the MeshBuilder class instead.
  33288. * The parameter `radius` sets the global radius size (float) of the torus knot (default 2).
  33289. * The parameter `radialSegments` sets the number of sides on each tube segments (positive integer, default 32).
  33290. * The parameter `tubularSegments` sets the number of tubes to decompose the knot into (positive integer, default 32).
  33291. * The parameters `p` and `q` are the number of windings on each axis (positive integers, default 2 and 3).
  33292. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  33293. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  33294. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33295. */
  33296. Mesh.CreateTorusKnot = function (name, radius, tube, radialSegments, tubularSegments, p, q, scene, updatable, sideOrientation) {
  33297. var options = {
  33298. radius: radius,
  33299. tube: tube,
  33300. radialSegments: radialSegments,
  33301. tubularSegments: tubularSegments,
  33302. p: p,
  33303. q: q,
  33304. sideOrientation: sideOrientation,
  33305. updatable: updatable
  33306. };
  33307. return BABYLON.MeshBuilder.CreateTorusKnot(name, options, scene);
  33308. };
  33309. /**
  33310. * Creates a line mesh.
  33311. * Please consider using the same method from the MeshBuilder class instead.
  33312. * 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.
  33313. * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function.
  33314. * The parameter `points` is an array successive Vector3.
  33315. * 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
  33316. * When updating an instance, remember that only point positions can change, not the number of points.
  33317. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33318. */
  33319. Mesh.CreateLines = function (name, points, scene, updatable, instance) {
  33320. if (scene === void 0) { scene = null; }
  33321. if (updatable === void 0) { updatable = false; }
  33322. if (instance === void 0) { instance = null; }
  33323. var options = {
  33324. points: points,
  33325. updatable: updatable,
  33326. instance: instance
  33327. };
  33328. return BABYLON.MeshBuilder.CreateLines(name, options, scene);
  33329. };
  33330. /**
  33331. * Creates a dashed line mesh.
  33332. * Please consider using the same method from the MeshBuilder class instead.
  33333. * 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.
  33334. * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function.
  33335. * The parameter `points` is an array successive Vector3.
  33336. * The parameter `dashNb` is the intended total number of dashes (positive integer, default 200).
  33337. * The parameter `dashSize` is the size of the dashes relatively the dash number (positive float, default 3).
  33338. * The parameter `gapSize` is the size of the gap between two successive dashes relatively the dash number (positive float, default 1).
  33339. * 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
  33340. * When updating an instance, remember that only point positions can change, not the number of points.
  33341. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33342. */
  33343. Mesh.CreateDashedLines = function (name, points, dashSize, gapSize, dashNb, scene, updatable, instance) {
  33344. if (scene === void 0) { scene = null; }
  33345. var options = {
  33346. points: points,
  33347. dashSize: dashSize,
  33348. gapSize: gapSize,
  33349. dashNb: dashNb,
  33350. updatable: updatable,
  33351. instance: instance
  33352. };
  33353. return BABYLON.MeshBuilder.CreateDashedLines(name, options, scene);
  33354. };
  33355. /**
  33356. * Creates a polygon mesh.
  33357. * Please consider using the same method from the MeshBuilder class instead.
  33358. * The polygon's shape will depend on the input parameters and is constructed parallel to a ground mesh.
  33359. * 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.
  33360. * You can set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  33361. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33362. * Remember you can only change the shape positions, not their number when updating a polygon.
  33363. */
  33364. Mesh.CreatePolygon = function (name, shape, scene, holes, updatable, sideOrientation) {
  33365. var options = {
  33366. shape: shape,
  33367. holes: holes,
  33368. updatable: updatable,
  33369. sideOrientation: sideOrientation
  33370. };
  33371. return BABYLON.MeshBuilder.CreatePolygon(name, options, scene);
  33372. };
  33373. /**
  33374. * Creates an extruded polygon mesh, with depth in the Y direction.
  33375. * Please consider using the same method from the MeshBuilder class instead.
  33376. */
  33377. Mesh.ExtrudePolygon = function (name, shape, depth, scene, holes, updatable, sideOrientation) {
  33378. var options = {
  33379. shape: shape,
  33380. holes: holes,
  33381. depth: depth,
  33382. updatable: updatable,
  33383. sideOrientation: sideOrientation
  33384. };
  33385. return BABYLON.MeshBuilder.ExtrudePolygon(name, options, scene);
  33386. };
  33387. /**
  33388. * Creates an extruded shape mesh.
  33389. * 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.
  33390. * Please consider using the same method from the MeshBuilder class instead.
  33391. *
  33392. * Please read this full tutorial to understand how to design an extruded shape : http://doc.babylonjs.com/tutorials/Parametric_Shapes#extrusion
  33393. * 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
  33394. * extruded along the Z axis.
  33395. * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along.
  33396. * 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.
  33397. * The parameter `scale` (float, default 1) is the value to scale the shape.
  33398. * 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
  33399. * 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
  33400. * Remember you can only change the shape or path point positions, not their number when updating an extruded shape.
  33401. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  33402. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  33403. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33404. */
  33405. Mesh.ExtrudeShape = function (name, shape, path, scale, rotation, cap, scene, updatable, sideOrientation, instance) {
  33406. if (scene === void 0) { scene = null; }
  33407. var options = {
  33408. shape: shape,
  33409. path: path,
  33410. scale: scale,
  33411. rotation: rotation,
  33412. cap: (cap === 0) ? 0 : cap || Mesh.NO_CAP,
  33413. sideOrientation: sideOrientation,
  33414. instance: instance,
  33415. updatable: updatable
  33416. };
  33417. return BABYLON.MeshBuilder.ExtrudeShape(name, options, scene);
  33418. };
  33419. /**
  33420. * Creates an custom extruded shape mesh.
  33421. * 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.
  33422. * Please consider using the same method from the MeshBuilder class instead.
  33423. *
  33424. * Please read this full tutorial to understand how to design a custom extruded shape : http://doc.babylonjs.com/tutorials/Parametric_Shapes#extrusion
  33425. * 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
  33426. * extruded along the Z axis.
  33427. * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along.
  33428. * 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
  33429. * and the distance of this point from the begining of the path :
  33430. * ```javascript
  33431. * var rotationFunction = function(i, distance) {
  33432. * // do things
  33433. * return rotationValue; }
  33434. * ```
  33435. * It must returns a float value that will be the rotation in radians applied to the shape on each path point.
  33436. * 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
  33437. * and the distance of this point from the begining of the path :
  33438. * ```javascript
  33439. * var scaleFunction = function(i, distance) {
  33440. * // do things
  33441. * return scaleValue;}
  33442. * ```
  33443. * It must returns a float value that will be the scale value applied to the shape on each path point.
  33444. * The parameter `ribbonClosePath` (boolean, default false) forces the extrusion underlying ribbon to close all the paths in its `pathArray`.
  33445. * The parameter `ribbonCloseArray` (boolean, default false) forces the extrusion underlying ribbon to close its `pathArray`.
  33446. * 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
  33447. * 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
  33448. * Remember you can only change the shape or path point positions, not their number when updating an extruded shape.
  33449. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  33450. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  33451. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33452. */
  33453. Mesh.ExtrudeShapeCustom = function (name, shape, path, scaleFunction, rotationFunction, ribbonCloseArray, ribbonClosePath, cap, scene, updatable, sideOrientation, instance) {
  33454. var options = {
  33455. shape: shape,
  33456. path: path,
  33457. scaleFunction: scaleFunction,
  33458. rotationFunction: rotationFunction,
  33459. ribbonCloseArray: ribbonCloseArray,
  33460. ribbonClosePath: ribbonClosePath,
  33461. cap: (cap === 0) ? 0 : cap || Mesh.NO_CAP,
  33462. sideOrientation: sideOrientation,
  33463. instance: instance,
  33464. updatable: updatable
  33465. };
  33466. return BABYLON.MeshBuilder.ExtrudeShapeCustom(name, options, scene);
  33467. };
  33468. /**
  33469. * Creates lathe mesh.
  33470. * The lathe is a shape with a symetry axis : a 2D model shape is rotated around this axis to design the lathe.
  33471. * Please consider using the same method from the MeshBuilder class instead.
  33472. * 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
  33473. * rotated around the Y axis. It's usually a 2D shape, so the Vector3 z coordinates are often set to zero.
  33474. * The parameter `radius` (positive float, default 1) is the radius value of the lathe.
  33475. * The parameter `tessellation` (positive integer, default 64) is the side number of the lathe.
  33476. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  33477. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  33478. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33479. */
  33480. Mesh.CreateLathe = function (name, shape, radius, tessellation, scene, updatable, sideOrientation) {
  33481. var options = {
  33482. shape: shape,
  33483. radius: radius,
  33484. tessellation: tessellation,
  33485. sideOrientation: sideOrientation,
  33486. updatable: updatable
  33487. };
  33488. return BABYLON.MeshBuilder.CreateLathe(name, options, scene);
  33489. };
  33490. /**
  33491. * Creates a plane mesh.
  33492. * Please consider using the same method from the MeshBuilder class instead.
  33493. * The parameter `size` sets the size (float) of both sides of the plane at once (default 1).
  33494. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  33495. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  33496. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33497. */
  33498. Mesh.CreatePlane = function (name, size, scene, updatable, sideOrientation) {
  33499. var options = {
  33500. size: size,
  33501. width: size,
  33502. height: size,
  33503. sideOrientation: sideOrientation,
  33504. updatable: updatable
  33505. };
  33506. return BABYLON.MeshBuilder.CreatePlane(name, options, scene);
  33507. };
  33508. /**
  33509. * Creates a ground mesh.
  33510. * Please consider using the same method from the MeshBuilder class instead.
  33511. * The parameters `width` and `height` (floats, default 1) set the width and height sizes of the ground.
  33512. * The parameter `subdivisions` (positive integer) sets the number of subdivisions per side.
  33513. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33514. */
  33515. Mesh.CreateGround = function (name, width, height, subdivisions, scene, updatable) {
  33516. var options = {
  33517. width: width,
  33518. height: height,
  33519. subdivisions: subdivisions,
  33520. updatable: updatable
  33521. };
  33522. return BABYLON.MeshBuilder.CreateGround(name, options, scene);
  33523. };
  33524. /**
  33525. * Creates a tiled ground mesh.
  33526. * Please consider using the same method from the MeshBuilder class instead.
  33527. * The parameters `xmin` and `xmax` (floats, default -1 and 1) set the ground minimum and maximum X coordinates.
  33528. * The parameters `zmin` and `zmax` (floats, default -1 and 1) set the ground minimum and maximum Z coordinates.
  33529. * The parameter `subdivisions` is a javascript object `{w: positive integer, h: positive integer}` (default `{w: 6, h: 6}`). `w` and `h` are the
  33530. * numbers of subdivisions on the ground width and height. Each subdivision is called a tile.
  33531. * The parameter `precision` is a javascript object `{w: positive integer, h: positive integer}` (default `{w: 2, h: 2}`). `w` and `h` are the
  33532. * numbers of subdivisions on the ground width and height of each tile.
  33533. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33534. */
  33535. Mesh.CreateTiledGround = function (name, xmin, zmin, xmax, zmax, subdivisions, precision, scene, updatable) {
  33536. var options = {
  33537. xmin: xmin,
  33538. zmin: zmin,
  33539. xmax: xmax,
  33540. zmax: zmax,
  33541. subdivisions: subdivisions,
  33542. precision: precision,
  33543. updatable: updatable
  33544. };
  33545. return BABYLON.MeshBuilder.CreateTiledGround(name, options, scene);
  33546. };
  33547. /**
  33548. * Creates a ground mesh from a height map.
  33549. * tuto : http://doc.babylonjs.com/tutorials/14._Height_Map
  33550. * Please consider using the same method from the MeshBuilder class instead.
  33551. * The parameter `url` sets the URL of the height map image resource.
  33552. * The parameters `width` and `height` (positive floats, default 10) set the ground width and height sizes.
  33553. * The parameter `subdivisions` (positive integer, default 1) sets the number of subdivision per side.
  33554. * The parameter `minHeight` (float, default 0) is the minimum altitude on the ground.
  33555. * The parameter `maxHeight` (float, default 1) is the maximum altitude on the ground.
  33556. * 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).
  33557. * This function is passed the newly built mesh :
  33558. * ```javascript
  33559. * function(mesh) { // do things
  33560. * return; }
  33561. * ```
  33562. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33563. */
  33564. Mesh.CreateGroundFromHeightMap = function (name, url, width, height, subdivisions, minHeight, maxHeight, scene, updatable, onReady) {
  33565. var options = {
  33566. width: width,
  33567. height: height,
  33568. subdivisions: subdivisions,
  33569. minHeight: minHeight,
  33570. maxHeight: maxHeight,
  33571. updatable: updatable,
  33572. onReady: onReady
  33573. };
  33574. return BABYLON.MeshBuilder.CreateGroundFromHeightMap(name, url, options, scene);
  33575. };
  33576. /**
  33577. * Creates a tube mesh.
  33578. * 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.
  33579. * Please consider using the same method from the MeshBuilder class instead.
  33580. * The parameter `path` is a required array of successive Vector3. It is the curve used as the axis of the tube.
  33581. * The parameter `radius` (positive float, default 1) sets the tube radius size.
  33582. * The parameter `tessellation` (positive float, default 64) is the number of sides on the tubular surface.
  33583. * The parameter `radiusFunction` (javascript function, default null) is a vanilla javascript function. If it is not null, it overwrittes the parameter `radius`.
  33584. * 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.
  33585. * It must return a radius value (positive float) :
  33586. * ```javascript
  33587. * var radiusFunction = function(i, distance) {
  33588. * // do things
  33589. * return radius; }
  33590. * ```
  33591. * 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
  33592. * 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
  33593. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  33594. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  33595. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33596. */
  33597. Mesh.CreateTube = function (name, path, radius, tessellation, radiusFunction, cap, scene, updatable, sideOrientation, instance) {
  33598. var options = {
  33599. path: path,
  33600. radius: radius,
  33601. tessellation: tessellation,
  33602. radiusFunction: radiusFunction,
  33603. arc: 1,
  33604. cap: cap,
  33605. updatable: updatable,
  33606. sideOrientation: sideOrientation,
  33607. instance: instance
  33608. };
  33609. return BABYLON.MeshBuilder.CreateTube(name, options, scene);
  33610. };
  33611. /**
  33612. * Creates a polyhedron mesh.
  33613. * Please consider using the same method from the MeshBuilder class instead.
  33614. * 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
  33615. * to choose the wanted type.
  33616. * The parameter `size` (positive float, default 1) sets the polygon size.
  33617. * You can overwrite the `size` on each dimension bu using the parameters `sizeX`, `sizeY` or `sizeZ` (positive floats, default to `size` value).
  33618. * 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`.
  33619. * 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
  33620. * 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)`).
  33621. * 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
  33622. * 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.
  33623. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  33624. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  33625. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33626. */
  33627. Mesh.CreatePolyhedron = function (name, options, scene) {
  33628. return BABYLON.MeshBuilder.CreatePolyhedron(name, options, scene);
  33629. };
  33630. /**
  33631. * Creates a sphere based upon an icosahedron with 20 triangular faces which can be subdivided.
  33632. * Please consider using the same method from the MeshBuilder class instead.
  33633. * The parameter `radius` sets the radius size (float) of the icosphere (default 1).
  33634. * 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`).
  33635. * The parameter `subdivisions` sets the number of subdivisions (postive integer, default 4). The more subdivisions, the more faces on the icosphere whatever its size.
  33636. * 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.
  33637. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  33638. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  33639. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33640. */
  33641. Mesh.CreateIcoSphere = function (name, options, scene) {
  33642. return BABYLON.MeshBuilder.CreateIcoSphere(name, options, scene);
  33643. };
  33644. /**
  33645. * Creates a decal mesh.
  33646. * Please consider using the same method from the MeshBuilder class instead.
  33647. * 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.
  33648. * The parameter `position` (Vector3, default `(0, 0, 0)`) sets the position of the decal in World coordinates.
  33649. * The parameter `normal` (Vector3, default Vector3.Up) sets the normal of the mesh where the decal is applied onto in World coordinates.
  33650. * The parameter `size` (Vector3, default `(1, 1, 1)`) sets the decal scaling.
  33651. * The parameter `angle` (float in radian, default 0) sets the angle to rotate the decal.
  33652. */
  33653. Mesh.CreateDecal = function (name, sourceMesh, position, normal, size, angle) {
  33654. var options = {
  33655. position: position,
  33656. normal: normal,
  33657. size: size,
  33658. angle: angle
  33659. };
  33660. return BABYLON.MeshBuilder.CreateDecal(name, sourceMesh, options);
  33661. };
  33662. // Skeletons
  33663. /**
  33664. * @returns original positions used for CPU skinning. Useful for integrating Morphing with skeletons in same mesh.
  33665. */
  33666. Mesh.prototype.setPositionsForCPUSkinning = function () {
  33667. if (!this._sourcePositions) {
  33668. var source = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  33669. if (!source) {
  33670. return this._sourcePositions;
  33671. }
  33672. this._sourcePositions = new Float32Array(source);
  33673. if (!this.isVertexBufferUpdatable(BABYLON.VertexBuffer.PositionKind)) {
  33674. this.setVerticesData(BABYLON.VertexBuffer.PositionKind, source, true);
  33675. }
  33676. }
  33677. return this._sourcePositions;
  33678. };
  33679. /**
  33680. * @returns original normals used for CPU skinning. Useful for integrating Morphing with skeletons in same mesh.
  33681. */
  33682. Mesh.prototype.setNormalsForCPUSkinning = function () {
  33683. if (!this._sourceNormals) {
  33684. var source = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  33685. if (!source) {
  33686. return this._sourceNormals;
  33687. }
  33688. this._sourceNormals = new Float32Array(source);
  33689. if (!this.isVertexBufferUpdatable(BABYLON.VertexBuffer.NormalKind)) {
  33690. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, source, true);
  33691. }
  33692. }
  33693. return this._sourceNormals;
  33694. };
  33695. /**
  33696. * Updates the vertex buffer by applying transformation from the bones.
  33697. * Returns the Mesh.
  33698. *
  33699. * @param {skeleton} skeleton to apply
  33700. */
  33701. Mesh.prototype.applySkeleton = function (skeleton) {
  33702. if (!this.geometry) {
  33703. return this;
  33704. }
  33705. if (this.geometry._softwareSkinningRenderId == this.getScene().getRenderId()) {
  33706. return this;
  33707. }
  33708. this.geometry._softwareSkinningRenderId = this.getScene().getRenderId();
  33709. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  33710. return this;
  33711. }
  33712. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  33713. return this;
  33714. }
  33715. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  33716. return this;
  33717. }
  33718. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  33719. return this;
  33720. }
  33721. if (!this._sourcePositions) {
  33722. var submeshes = this.subMeshes.slice();
  33723. this.setPositionsForCPUSkinning();
  33724. this.subMeshes = submeshes;
  33725. }
  33726. if (!this._sourceNormals) {
  33727. this.setNormalsForCPUSkinning();
  33728. }
  33729. // positionsData checks for not being Float32Array will only pass at most once
  33730. var positionsData = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  33731. if (!positionsData) {
  33732. return this;
  33733. }
  33734. if (!(positionsData instanceof Float32Array)) {
  33735. positionsData = new Float32Array(positionsData);
  33736. }
  33737. // normalsData checks for not being Float32Array will only pass at most once
  33738. var normalsData = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  33739. if (!normalsData) {
  33740. return this;
  33741. }
  33742. if (!(normalsData instanceof Float32Array)) {
  33743. normalsData = new Float32Array(normalsData);
  33744. }
  33745. var matricesIndicesData = this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind);
  33746. var matricesWeightsData = this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind);
  33747. if (!matricesWeightsData || !matricesIndicesData) {
  33748. return this;
  33749. }
  33750. var needExtras = this.numBoneInfluencers > 4;
  33751. var matricesIndicesExtraData = needExtras ? this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind) : null;
  33752. var matricesWeightsExtraData = needExtras ? this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind) : null;
  33753. var skeletonMatrices = skeleton.getTransformMatrices(this);
  33754. var tempVector3 = BABYLON.Vector3.Zero();
  33755. var finalMatrix = new BABYLON.Matrix();
  33756. var tempMatrix = new BABYLON.Matrix();
  33757. var matWeightIdx = 0;
  33758. var inf;
  33759. for (var index = 0; index < positionsData.length; index += 3, matWeightIdx += 4) {
  33760. var weight;
  33761. for (inf = 0; inf < 4; inf++) {
  33762. weight = matricesWeightsData[matWeightIdx + inf];
  33763. if (weight > 0) {
  33764. BABYLON.Matrix.FromFloat32ArrayToRefScaled(skeletonMatrices, Math.floor(matricesIndicesData[matWeightIdx + inf] * 16), weight, tempMatrix);
  33765. finalMatrix.addToSelf(tempMatrix);
  33766. }
  33767. else
  33768. break;
  33769. }
  33770. if (needExtras) {
  33771. for (inf = 0; inf < 4; inf++) {
  33772. weight = matricesWeightsExtraData[matWeightIdx + inf];
  33773. if (weight > 0) {
  33774. BABYLON.Matrix.FromFloat32ArrayToRefScaled(skeletonMatrices, Math.floor(matricesIndicesExtraData[matWeightIdx + inf] * 16), weight, tempMatrix);
  33775. finalMatrix.addToSelf(tempMatrix);
  33776. }
  33777. else
  33778. break;
  33779. }
  33780. }
  33781. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(this._sourcePositions[index], this._sourcePositions[index + 1], this._sourcePositions[index + 2], finalMatrix, tempVector3);
  33782. tempVector3.toArray(positionsData, index);
  33783. BABYLON.Vector3.TransformNormalFromFloatsToRef(this._sourceNormals[index], this._sourceNormals[index + 1], this._sourceNormals[index + 2], finalMatrix, tempVector3);
  33784. tempVector3.toArray(normalsData, index);
  33785. finalMatrix.reset();
  33786. }
  33787. this.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positionsData);
  33788. this.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normalsData);
  33789. return this;
  33790. };
  33791. // Tools
  33792. /**
  33793. * Returns an object `{min:` Vector3`, max:` Vector3`}`
  33794. * This min and max Vector3 are the minimum and maximum vectors of each mesh bounding box from the passed array, in the World system
  33795. */
  33796. Mesh.MinMax = function (meshes) {
  33797. var minVector = null;
  33798. var maxVector = null;
  33799. meshes.forEach(function (mesh, index, array) {
  33800. var boundingInfo = mesh.getBoundingInfo();
  33801. var boundingBox = boundingInfo.boundingBox;
  33802. if (!minVector || !maxVector) {
  33803. minVector = boundingBox.minimumWorld;
  33804. maxVector = boundingBox.maximumWorld;
  33805. }
  33806. else {
  33807. minVector.minimizeInPlace(boundingBox.minimumWorld);
  33808. maxVector.maximizeInPlace(boundingBox.maximumWorld);
  33809. }
  33810. });
  33811. if (!minVector || !maxVector) {
  33812. return {
  33813. min: BABYLON.Vector3.Zero(),
  33814. max: BABYLON.Vector3.Zero()
  33815. };
  33816. }
  33817. return {
  33818. min: minVector,
  33819. max: maxVector
  33820. };
  33821. };
  33822. /**
  33823. * Returns a Vector3, the center of the `{min:` Vector3`, max:` Vector3`}` or the center of MinMax vector3 computed from a mesh array.
  33824. */
  33825. Mesh.Center = function (meshesOrMinMaxVector) {
  33826. var minMaxVector = (meshesOrMinMaxVector instanceof Array) ? Mesh.MinMax(meshesOrMinMaxVector) : meshesOrMinMaxVector;
  33827. return BABYLON.Vector3.Center(minMaxVector.min, minMaxVector.max);
  33828. };
  33829. /**
  33830. * Merge the array of meshes into a single mesh for performance reasons.
  33831. * @param {Array<Mesh>} meshes - The vertices source. They should all be of the same material. Entries can empty
  33832. * @param {boolean} disposeSource - When true (default), dispose of the vertices from the source meshes
  33833. * @param {boolean} allow32BitsIndices - When the sum of the vertices > 64k, this must be set to true.
  33834. * @param {Mesh} meshSubclass - When set, vertices inserted into this Mesh. Meshes can then be merged into a Mesh sub-class.
  33835. * @param {boolean} subdivideWithSubMeshes - When true (false default), subdivide mesh to his subMesh array with meshes source.
  33836. */
  33837. Mesh.MergeMeshes = function (meshes, disposeSource, allow32BitsIndices, meshSubclass, subdivideWithSubMeshes) {
  33838. if (disposeSource === void 0) { disposeSource = true; }
  33839. var index;
  33840. if (!allow32BitsIndices) {
  33841. var totalVertices = 0;
  33842. // Counting vertices
  33843. for (index = 0; index < meshes.length; index++) {
  33844. if (meshes[index]) {
  33845. totalVertices += meshes[index].getTotalVertices();
  33846. if (totalVertices > 65536) {
  33847. BABYLON.Tools.Warn("Cannot merge meshes because resulting mesh will have more than 65536 vertices. Please use allow32BitsIndices = true to use 32 bits indices");
  33848. return null;
  33849. }
  33850. }
  33851. }
  33852. }
  33853. // Merge
  33854. var vertexData = null;
  33855. var otherVertexData;
  33856. var indiceArray = new Array();
  33857. var source = null;
  33858. for (index = 0; index < meshes.length; index++) {
  33859. if (meshes[index]) {
  33860. meshes[index].computeWorldMatrix(true);
  33861. otherVertexData = BABYLON.VertexData.ExtractFromMesh(meshes[index], true);
  33862. otherVertexData.transform(meshes[index].getWorldMatrix());
  33863. if (vertexData) {
  33864. vertexData.merge(otherVertexData);
  33865. }
  33866. else {
  33867. vertexData = otherVertexData;
  33868. source = meshes[index];
  33869. }
  33870. if (subdivideWithSubMeshes) {
  33871. indiceArray.push(meshes[index].getTotalIndices());
  33872. }
  33873. }
  33874. }
  33875. source = source;
  33876. if (!meshSubclass) {
  33877. meshSubclass = new Mesh(source.name + "_merged", source.getScene());
  33878. }
  33879. vertexData.applyToMesh(meshSubclass);
  33880. // Setting properties
  33881. meshSubclass.material = source.material;
  33882. meshSubclass.checkCollisions = source.checkCollisions;
  33883. // Cleaning
  33884. if (disposeSource) {
  33885. for (index = 0; index < meshes.length; index++) {
  33886. if (meshes[index]) {
  33887. meshes[index].dispose();
  33888. }
  33889. }
  33890. }
  33891. // Subdivide
  33892. if (subdivideWithSubMeshes) {
  33893. //-- Suppresions du submesh global
  33894. meshSubclass.releaseSubMeshes();
  33895. index = 0;
  33896. var offset = 0;
  33897. //-- aplique la subdivision en fonction du tableau d'indices
  33898. while (index < indiceArray.length) {
  33899. BABYLON.SubMesh.CreateFromIndices(0, offset, indiceArray[index], meshSubclass);
  33900. offset += indiceArray[index];
  33901. index++;
  33902. }
  33903. }
  33904. return meshSubclass;
  33905. };
  33906. // Consts
  33907. Mesh._FRONTSIDE = 0;
  33908. Mesh._BACKSIDE = 1;
  33909. Mesh._DOUBLESIDE = 2;
  33910. Mesh._DEFAULTSIDE = 0;
  33911. Mesh._NO_CAP = 0;
  33912. Mesh._CAP_START = 1;
  33913. Mesh._CAP_END = 2;
  33914. Mesh._CAP_ALL = 3;
  33915. return Mesh;
  33916. }(BABYLON.AbstractMesh));
  33917. BABYLON.Mesh = Mesh;
  33918. })(BABYLON || (BABYLON = {}));
  33919. //# sourceMappingURL=babylon.mesh.js.map
  33920. var BABYLON;
  33921. (function (BABYLON) {
  33922. var BaseSubMesh = /** @class */ (function () {
  33923. function BaseSubMesh() {
  33924. }
  33925. Object.defineProperty(BaseSubMesh.prototype, "effect", {
  33926. get: function () {
  33927. return this._materialEffect;
  33928. },
  33929. enumerable: true,
  33930. configurable: true
  33931. });
  33932. BaseSubMesh.prototype.setEffect = function (effect, defines) {
  33933. if (defines === void 0) { defines = null; }
  33934. if (this._materialEffect === effect) {
  33935. if (!effect) {
  33936. this._materialDefines = null;
  33937. }
  33938. return;
  33939. }
  33940. this._materialDefines = defines;
  33941. this._materialEffect = effect;
  33942. };
  33943. return BaseSubMesh;
  33944. }());
  33945. BABYLON.BaseSubMesh = BaseSubMesh;
  33946. var SubMesh = /** @class */ (function (_super) {
  33947. __extends(SubMesh, _super);
  33948. function SubMesh(materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh, renderingMesh, createBoundingBox) {
  33949. if (createBoundingBox === void 0) { createBoundingBox = true; }
  33950. var _this = _super.call(this) || this;
  33951. _this.materialIndex = materialIndex;
  33952. _this.verticesStart = verticesStart;
  33953. _this.verticesCount = verticesCount;
  33954. _this.indexStart = indexStart;
  33955. _this.indexCount = indexCount;
  33956. _this._renderId = 0;
  33957. _this._mesh = mesh;
  33958. _this._renderingMesh = renderingMesh || mesh;
  33959. mesh.subMeshes.push(_this);
  33960. _this._trianglePlanes = [];
  33961. _this._id = mesh.subMeshes.length - 1;
  33962. if (createBoundingBox) {
  33963. _this.refreshBoundingInfo();
  33964. mesh.computeWorldMatrix(true);
  33965. }
  33966. return _this;
  33967. }
  33968. SubMesh.AddToMesh = function (materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh, renderingMesh, createBoundingBox) {
  33969. if (createBoundingBox === void 0) { createBoundingBox = true; }
  33970. return new SubMesh(materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh, renderingMesh, createBoundingBox);
  33971. };
  33972. Object.defineProperty(SubMesh.prototype, "IsGlobal", {
  33973. get: function () {
  33974. return (this.verticesStart === 0 && this.verticesCount == this._mesh.getTotalVertices());
  33975. },
  33976. enumerable: true,
  33977. configurable: true
  33978. });
  33979. /**
  33980. * Returns the submesh BoudingInfo object.
  33981. */
  33982. SubMesh.prototype.getBoundingInfo = function () {
  33983. if (this.IsGlobal) {
  33984. return this._mesh.getBoundingInfo();
  33985. }
  33986. return this._boundingInfo;
  33987. };
  33988. /**
  33989. * Sets the submesh BoundingInfo.
  33990. * Return the SubMesh.
  33991. */
  33992. SubMesh.prototype.setBoundingInfo = function (boundingInfo) {
  33993. this._boundingInfo = boundingInfo;
  33994. return this;
  33995. };
  33996. /**
  33997. * Returns the mesh of the current submesh.
  33998. */
  33999. SubMesh.prototype.getMesh = function () {
  34000. return this._mesh;
  34001. };
  34002. /**
  34003. * Returns the rendering mesh of the submesh.
  34004. */
  34005. SubMesh.prototype.getRenderingMesh = function () {
  34006. return this._renderingMesh;
  34007. };
  34008. /**
  34009. * Returns the submesh material.
  34010. */
  34011. SubMesh.prototype.getMaterial = function () {
  34012. var rootMaterial = this._renderingMesh.material;
  34013. if (rootMaterial === null || rootMaterial === undefined) {
  34014. return this._mesh.getScene().defaultMaterial;
  34015. }
  34016. else if (rootMaterial.getSubMaterial) {
  34017. var multiMaterial = rootMaterial;
  34018. var effectiveMaterial = multiMaterial.getSubMaterial(this.materialIndex);
  34019. if (this._currentMaterial !== effectiveMaterial) {
  34020. this._currentMaterial = effectiveMaterial;
  34021. this._materialDefines = null;
  34022. }
  34023. return effectiveMaterial;
  34024. }
  34025. return rootMaterial;
  34026. };
  34027. // Methods
  34028. /**
  34029. * Sets a new updated BoundingInfo object to the submesh.
  34030. * Returns the SubMesh.
  34031. */
  34032. SubMesh.prototype.refreshBoundingInfo = function () {
  34033. this._lastColliderWorldVertices = null;
  34034. if (this.IsGlobal || !this._renderingMesh || !this._renderingMesh.geometry) {
  34035. return this;
  34036. }
  34037. var data = this._renderingMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  34038. if (!data) {
  34039. this._boundingInfo = this._mesh.getBoundingInfo();
  34040. return this;
  34041. }
  34042. var indices = this._renderingMesh.getIndices();
  34043. var extend;
  34044. //is this the only submesh?
  34045. if (this.indexStart === 0 && this.indexCount === indices.length) {
  34046. var boundingInfo = this._renderingMesh.getBoundingInfo();
  34047. //the rendering mesh's bounding info can be used, it is the standard submesh for all indices.
  34048. extend = { minimum: boundingInfo.minimum.clone(), maximum: boundingInfo.maximum.clone() };
  34049. }
  34050. else {
  34051. extend = BABYLON.Tools.ExtractMinAndMaxIndexed(data, indices, this.indexStart, this.indexCount, this._renderingMesh.geometry.boundingBias);
  34052. }
  34053. this._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  34054. return this;
  34055. };
  34056. SubMesh.prototype._checkCollision = function (collider) {
  34057. var boundingInfo = this.getBoundingInfo();
  34058. return boundingInfo._checkCollision(collider);
  34059. };
  34060. /**
  34061. * Updates the submesh BoundingInfo.
  34062. * Returns the Submesh.
  34063. */
  34064. SubMesh.prototype.updateBoundingInfo = function (world) {
  34065. var boundingInfo = this.getBoundingInfo();
  34066. if (!boundingInfo) {
  34067. this.refreshBoundingInfo();
  34068. boundingInfo = this.getBoundingInfo();
  34069. }
  34070. boundingInfo.update(world);
  34071. return this;
  34072. };
  34073. /**
  34074. * True is the submesh bounding box intersects the frustum defined by the passed array of planes.
  34075. * Boolean returned.
  34076. */
  34077. SubMesh.prototype.isInFrustum = function (frustumPlanes) {
  34078. var boundingInfo = this.getBoundingInfo();
  34079. if (!boundingInfo) {
  34080. return false;
  34081. }
  34082. return boundingInfo.isInFrustum(frustumPlanes);
  34083. };
  34084. /**
  34085. * True is the submesh bounding box is completely inside the frustum defined by the passed array of planes.
  34086. * Boolean returned.
  34087. */
  34088. SubMesh.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  34089. var boundingInfo = this.getBoundingInfo();
  34090. if (!boundingInfo) {
  34091. return false;
  34092. }
  34093. return boundingInfo.isCompletelyInFrustum(frustumPlanes);
  34094. };
  34095. /**
  34096. * Renders the submesh.
  34097. * Returns it.
  34098. */
  34099. SubMesh.prototype.render = function (enableAlphaMode) {
  34100. this._renderingMesh.render(this, enableAlphaMode);
  34101. return this;
  34102. };
  34103. /**
  34104. * Returns a new Index Buffer.
  34105. * Type returned : WebGLBuffer.
  34106. */
  34107. SubMesh.prototype.getLinesIndexBuffer = function (indices, engine) {
  34108. if (!this._linesIndexBuffer) {
  34109. var linesIndices = [];
  34110. for (var index = this.indexStart; index < this.indexStart + this.indexCount; index += 3) {
  34111. linesIndices.push(indices[index], indices[index + 1], indices[index + 1], indices[index + 2], indices[index + 2], indices[index]);
  34112. }
  34113. this._linesIndexBuffer = engine.createIndexBuffer(linesIndices);
  34114. this.linesIndexCount = linesIndices.length;
  34115. }
  34116. return this._linesIndexBuffer;
  34117. };
  34118. /**
  34119. * True is the passed Ray intersects the submesh bounding box.
  34120. * Boolean returned.
  34121. */
  34122. SubMesh.prototype.canIntersects = function (ray) {
  34123. var boundingInfo = this.getBoundingInfo();
  34124. if (!boundingInfo) {
  34125. return false;
  34126. }
  34127. return ray.intersectsBox(boundingInfo.boundingBox);
  34128. };
  34129. /**
  34130. * Returns an object IntersectionInfo.
  34131. */
  34132. SubMesh.prototype.intersects = function (ray, positions, indices, fastCheck) {
  34133. var intersectInfo = null;
  34134. var material = this.getMaterial();
  34135. if (!material) {
  34136. return null;
  34137. }
  34138. switch (material.fillMode) {
  34139. case BABYLON.Material.PointListDrawMode:
  34140. case BABYLON.Material.LineListDrawMode:
  34141. case BABYLON.Material.LineLoopDrawMode:
  34142. case BABYLON.Material.LineStripDrawMode:
  34143. case BABYLON.Material.TriangleFanDrawMode:
  34144. case BABYLON.Material.TriangleStripDrawMode:
  34145. return null;
  34146. }
  34147. // LineMesh first as it's also a Mesh...
  34148. if (BABYLON.LinesMesh && this._mesh instanceof BABYLON.LinesMesh) {
  34149. var lineMesh = this._mesh;
  34150. // Line test
  34151. for (var index = this.indexStart; index < this.indexStart + this.indexCount; index += 2) {
  34152. var p0 = positions[indices[index]];
  34153. var p1 = positions[indices[index + 1]];
  34154. var length = ray.intersectionSegment(p0, p1, lineMesh.intersectionThreshold);
  34155. if (length < 0) {
  34156. continue;
  34157. }
  34158. if (fastCheck || !intersectInfo || length < intersectInfo.distance) {
  34159. intersectInfo = new BABYLON.IntersectionInfo(null, null, length);
  34160. if (fastCheck) {
  34161. break;
  34162. }
  34163. }
  34164. }
  34165. }
  34166. else {
  34167. // Triangles test
  34168. for (var index = this.indexStart; index < this.indexStart + this.indexCount; index += 3) {
  34169. var p0 = positions[indices[index]];
  34170. var p1 = positions[indices[index + 1]];
  34171. var p2 = positions[indices[index + 2]];
  34172. var currentIntersectInfo = ray.intersectsTriangle(p0, p1, p2);
  34173. if (currentIntersectInfo) {
  34174. if (currentIntersectInfo.distance < 0) {
  34175. continue;
  34176. }
  34177. if (fastCheck || !intersectInfo || currentIntersectInfo.distance < intersectInfo.distance) {
  34178. intersectInfo = currentIntersectInfo;
  34179. intersectInfo.faceId = index / 3;
  34180. if (fastCheck) {
  34181. break;
  34182. }
  34183. }
  34184. }
  34185. }
  34186. }
  34187. return intersectInfo;
  34188. };
  34189. SubMesh.prototype._rebuild = function () {
  34190. if (this._linesIndexBuffer) {
  34191. this._linesIndexBuffer = null;
  34192. }
  34193. };
  34194. // Clone
  34195. /**
  34196. * Creates a new Submesh from the passed Mesh.
  34197. */
  34198. SubMesh.prototype.clone = function (newMesh, newRenderingMesh) {
  34199. var result = new SubMesh(this.materialIndex, this.verticesStart, this.verticesCount, this.indexStart, this.indexCount, newMesh, newRenderingMesh, false);
  34200. if (!this.IsGlobal) {
  34201. var boundingInfo = this.getBoundingInfo();
  34202. if (!boundingInfo) {
  34203. return result;
  34204. }
  34205. result._boundingInfo = new BABYLON.BoundingInfo(boundingInfo.minimum, boundingInfo.maximum);
  34206. }
  34207. return result;
  34208. };
  34209. // Dispose
  34210. /**
  34211. * Disposes the Submesh.
  34212. * Returns nothing.
  34213. */
  34214. SubMesh.prototype.dispose = function () {
  34215. if (this._linesIndexBuffer) {
  34216. this._mesh.getScene().getEngine()._releaseBuffer(this._linesIndexBuffer);
  34217. this._linesIndexBuffer = null;
  34218. }
  34219. // Remove from mesh
  34220. var index = this._mesh.subMeshes.indexOf(this);
  34221. this._mesh.subMeshes.splice(index, 1);
  34222. };
  34223. // Statics
  34224. /**
  34225. * Creates a new Submesh from the passed parameters :
  34226. * - materialIndex (integer) : the index of the main mesh material.
  34227. * - startIndex (integer) : the index where to start the copy in the mesh indices array.
  34228. * - indexCount (integer) : the number of indices to copy then from the startIndex.
  34229. * - mesh (Mesh) : the main mesh to create the submesh from.
  34230. * - renderingMesh (optional Mesh) : rendering mesh.
  34231. */
  34232. SubMesh.CreateFromIndices = function (materialIndex, startIndex, indexCount, mesh, renderingMesh) {
  34233. var minVertexIndex = Number.MAX_VALUE;
  34234. var maxVertexIndex = -Number.MAX_VALUE;
  34235. renderingMesh = (renderingMesh || mesh);
  34236. var indices = renderingMesh.getIndices();
  34237. for (var index = startIndex; index < startIndex + indexCount; index++) {
  34238. var vertexIndex = indices[index];
  34239. if (vertexIndex < minVertexIndex)
  34240. minVertexIndex = vertexIndex;
  34241. if (vertexIndex > maxVertexIndex)
  34242. maxVertexIndex = vertexIndex;
  34243. }
  34244. return new SubMesh(materialIndex, minVertexIndex, maxVertexIndex - minVertexIndex + 1, startIndex, indexCount, mesh, renderingMesh);
  34245. };
  34246. return SubMesh;
  34247. }(BaseSubMesh));
  34248. BABYLON.SubMesh = SubMesh;
  34249. })(BABYLON || (BABYLON = {}));
  34250. //# sourceMappingURL=babylon.subMesh.js.map
  34251. var __assign = (this && this.__assign) || Object.assign || function(t) {
  34252. for (var s, i = 1, n = arguments.length; i < n; i++) {
  34253. s = arguments[i];
  34254. for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
  34255. t[p] = s[p];
  34256. }
  34257. return t;
  34258. };
  34259. var BABYLON;
  34260. (function (BABYLON) {
  34261. /**
  34262. * Manages the defines for the Material
  34263. */
  34264. var MaterialDefines = /** @class */ (function () {
  34265. function MaterialDefines() {
  34266. this._isDirty = true;
  34267. /** @hidden */
  34268. this._areLightsDirty = true;
  34269. /** @hidden */
  34270. this._areAttributesDirty = true;
  34271. /** @hidden */
  34272. this._areTexturesDirty = true;
  34273. /** @hidden */
  34274. this._areFresnelDirty = true;
  34275. /** @hidden */
  34276. this._areMiscDirty = true;
  34277. /** @hidden */
  34278. this._areImageProcessingDirty = true;
  34279. /** @hidden */
  34280. this._normals = false;
  34281. /** @hidden */
  34282. this._uvs = false;
  34283. /** @hidden */
  34284. this._needNormals = false;
  34285. /** @hidden */
  34286. this._needUVs = false;
  34287. }
  34288. Object.defineProperty(MaterialDefines.prototype, "isDirty", {
  34289. /**
  34290. * Specifies if the material needs to be re-calculated
  34291. */
  34292. get: function () {
  34293. return this._isDirty;
  34294. },
  34295. enumerable: true,
  34296. configurable: true
  34297. });
  34298. /**
  34299. * Marks the material to indicate that it has been re-calculated
  34300. */
  34301. MaterialDefines.prototype.markAsProcessed = function () {
  34302. this._isDirty = false;
  34303. this._areAttributesDirty = false;
  34304. this._areTexturesDirty = false;
  34305. this._areFresnelDirty = false;
  34306. this._areLightsDirty = false;
  34307. this._areMiscDirty = false;
  34308. this._areImageProcessingDirty = false;
  34309. };
  34310. /**
  34311. * Marks the material to indicate that it needs to be re-calculated
  34312. */
  34313. MaterialDefines.prototype.markAsUnprocessed = function () {
  34314. this._isDirty = true;
  34315. };
  34316. /**
  34317. * Marks the material to indicate all of its defines need to be re-calculated
  34318. */
  34319. MaterialDefines.prototype.markAllAsDirty = function () {
  34320. this._areTexturesDirty = true;
  34321. this._areAttributesDirty = true;
  34322. this._areLightsDirty = true;
  34323. this._areFresnelDirty = true;
  34324. this._areMiscDirty = true;
  34325. this._areImageProcessingDirty = true;
  34326. this._isDirty = true;
  34327. };
  34328. /**
  34329. * Marks the material to indicate that image processing needs to be re-calculated
  34330. */
  34331. MaterialDefines.prototype.markAsImageProcessingDirty = function () {
  34332. this._areImageProcessingDirty = true;
  34333. this._isDirty = true;
  34334. };
  34335. /**
  34336. * Marks the material to indicate the lights need to be re-calculated
  34337. */
  34338. MaterialDefines.prototype.markAsLightDirty = function () {
  34339. this._areLightsDirty = true;
  34340. this._isDirty = true;
  34341. };
  34342. /**
  34343. * Marks the attribute state as changed
  34344. */
  34345. MaterialDefines.prototype.markAsAttributesDirty = function () {
  34346. this._areAttributesDirty = true;
  34347. this._isDirty = true;
  34348. };
  34349. /**
  34350. * Marks the texture state as changed
  34351. */
  34352. MaterialDefines.prototype.markAsTexturesDirty = function () {
  34353. this._areTexturesDirty = true;
  34354. this._isDirty = true;
  34355. };
  34356. /**
  34357. * Marks the fresnel state as changed
  34358. */
  34359. MaterialDefines.prototype.markAsFresnelDirty = function () {
  34360. this._areFresnelDirty = true;
  34361. this._isDirty = true;
  34362. };
  34363. /**
  34364. * Marks the misc state as changed
  34365. */
  34366. MaterialDefines.prototype.markAsMiscDirty = function () {
  34367. this._areMiscDirty = true;
  34368. this._isDirty = true;
  34369. };
  34370. /**
  34371. * Rebuilds the material defines
  34372. */
  34373. MaterialDefines.prototype.rebuild = function () {
  34374. if (this._keys) {
  34375. delete this._keys;
  34376. }
  34377. this._keys = [];
  34378. for (var _i = 0, _a = Object.keys(this); _i < _a.length; _i++) {
  34379. var key = _a[_i];
  34380. if (key[0] === "_") {
  34381. continue;
  34382. }
  34383. this._keys.push(key);
  34384. }
  34385. };
  34386. /**
  34387. * Specifies if two material defines are equal
  34388. * @param other - A material define instance to compare to
  34389. * @returns - Boolean indicating if the material defines are equal (true) or not (false)
  34390. */
  34391. MaterialDefines.prototype.isEqual = function (other) {
  34392. if (this._keys.length !== other._keys.length) {
  34393. return false;
  34394. }
  34395. for (var index = 0; index < this._keys.length; index++) {
  34396. var prop = this._keys[index];
  34397. if (this[prop] !== other[prop]) {
  34398. return false;
  34399. }
  34400. }
  34401. return true;
  34402. };
  34403. /**
  34404. * Clones this instance's defines to another instance
  34405. * @param other - material defines to clone values to
  34406. */
  34407. MaterialDefines.prototype.cloneTo = function (other) {
  34408. if (this._keys.length !== other._keys.length) {
  34409. other._keys = this._keys.slice(0);
  34410. }
  34411. for (var index = 0; index < this._keys.length; index++) {
  34412. var prop = this._keys[index];
  34413. other[prop] = this[prop];
  34414. }
  34415. };
  34416. /**
  34417. * Resets the material define values
  34418. */
  34419. MaterialDefines.prototype.reset = function () {
  34420. for (var index = 0; index < this._keys.length; index++) {
  34421. var prop = this._keys[index];
  34422. var type = typeof this[prop];
  34423. switch (type) {
  34424. case "number":
  34425. this[prop] = 0;
  34426. break;
  34427. case "string":
  34428. this[prop] = "";
  34429. break;
  34430. default:
  34431. this[prop] = false;
  34432. break;
  34433. }
  34434. }
  34435. };
  34436. /**
  34437. * Converts the material define values to a string
  34438. * @returns - String of material define information
  34439. */
  34440. MaterialDefines.prototype.toString = function () {
  34441. var result = "";
  34442. for (var index = 0; index < this._keys.length; index++) {
  34443. var prop = this._keys[index];
  34444. var value = this[prop];
  34445. var type = typeof value;
  34446. switch (type) {
  34447. case "number":
  34448. case "string":
  34449. result += "#define " + prop + " " + value + "\n";
  34450. break;
  34451. default:
  34452. if (value) {
  34453. result += "#define " + prop + "\n";
  34454. }
  34455. break;
  34456. }
  34457. }
  34458. return result;
  34459. };
  34460. return MaterialDefines;
  34461. }());
  34462. BABYLON.MaterialDefines = MaterialDefines;
  34463. /**
  34464. * Base class for the main features of a material in Babylon.js
  34465. */
  34466. var Material = /** @class */ (function () {
  34467. /**
  34468. * Creates a material instance
  34469. * @param name defines the name of the material
  34470. * @param scene defines the scene to reference
  34471. * @param doNotAdd specifies if the material should be added to the scene
  34472. */
  34473. function Material(name, scene, doNotAdd) {
  34474. /**
  34475. * Specifies if the ready state should be checked on each call
  34476. */
  34477. this.checkReadyOnEveryCall = false;
  34478. /**
  34479. * Specifies if the ready state should be checked once
  34480. */
  34481. this.checkReadyOnlyOnce = false;
  34482. /**
  34483. * The state of the material
  34484. */
  34485. this.state = "";
  34486. /**
  34487. * The alpha value of the material
  34488. */
  34489. this._alpha = 1.0;
  34490. /**
  34491. * Specifies if back face culling is enabled
  34492. */
  34493. this._backFaceCulling = true;
  34494. /**
  34495. * Specifies if the material should be serialized
  34496. */
  34497. this.doNotSerialize = false;
  34498. /**
  34499. * Specifies if the effect should be stored on sub meshes
  34500. */
  34501. this.storeEffectOnSubMeshes = false;
  34502. /**
  34503. * An event triggered when the material is disposed
  34504. */
  34505. this.onDisposeObservable = new BABYLON.Observable();
  34506. /**
  34507. * An event triggered when the material is bound
  34508. */
  34509. this.onBindObservable = new BABYLON.Observable();
  34510. /**
  34511. * An event triggered when the material is unbound
  34512. */
  34513. this.onUnBindObservable = new BABYLON.Observable();
  34514. /**
  34515. * Stores the value of the alpha mode
  34516. */
  34517. this._alphaMode = BABYLON.Engine.ALPHA_COMBINE;
  34518. /**
  34519. * Stores the state of the need depth pre-pass value
  34520. */
  34521. this._needDepthPrePass = false;
  34522. /**
  34523. * Specifies if depth writing should be disabled
  34524. */
  34525. this.disableDepthWrite = false;
  34526. /**
  34527. * Specifies if depth writing should be forced
  34528. */
  34529. this.forceDepthWrite = false;
  34530. /**
  34531. * Specifies if there should be a separate pass for culling
  34532. */
  34533. this.separateCullingPass = false;
  34534. /**
  34535. * Stores the state specifing if fog should be enabled
  34536. */
  34537. this._fogEnabled = true;
  34538. /**
  34539. * Stores the size of points
  34540. */
  34541. this.pointSize = 1.0;
  34542. /**
  34543. * Stores the z offset value
  34544. */
  34545. this.zOffset = 0;
  34546. /**
  34547. * Specifies if the material was previously ready
  34548. */
  34549. this._wasPreviouslyReady = false;
  34550. /**
  34551. * Stores the fill mode state
  34552. */
  34553. this._fillMode = Material.TriangleFillMode;
  34554. this.name = name;
  34555. this.id = name || BABYLON.Tools.RandomId();
  34556. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  34557. if (this._scene.useRightHandedSystem) {
  34558. this.sideOrientation = Material.ClockWiseSideOrientation;
  34559. }
  34560. else {
  34561. this.sideOrientation = Material.CounterClockWiseSideOrientation;
  34562. }
  34563. this._uniformBuffer = new BABYLON.UniformBuffer(this._scene.getEngine());
  34564. this._useUBO = this.getScene().getEngine().supportsUniformBuffers;
  34565. if (!doNotAdd) {
  34566. this._scene.materials.push(this);
  34567. }
  34568. }
  34569. Object.defineProperty(Material, "TriangleFillMode", {
  34570. /**
  34571. * Returns the triangle fill mode
  34572. */
  34573. get: function () {
  34574. return Material._TriangleFillMode;
  34575. },
  34576. enumerable: true,
  34577. configurable: true
  34578. });
  34579. Object.defineProperty(Material, "WireFrameFillMode", {
  34580. /**
  34581. * Returns the wireframe mode
  34582. */
  34583. get: function () {
  34584. return Material._WireFrameFillMode;
  34585. },
  34586. enumerable: true,
  34587. configurable: true
  34588. });
  34589. Object.defineProperty(Material, "PointFillMode", {
  34590. /**
  34591. * Returns the point fill mode
  34592. */
  34593. get: function () {
  34594. return Material._PointFillMode;
  34595. },
  34596. enumerable: true,
  34597. configurable: true
  34598. });
  34599. Object.defineProperty(Material, "PointListDrawMode", {
  34600. /**
  34601. * Returns the point list draw mode
  34602. */
  34603. get: function () {
  34604. return Material._PointListDrawMode;
  34605. },
  34606. enumerable: true,
  34607. configurable: true
  34608. });
  34609. Object.defineProperty(Material, "LineListDrawMode", {
  34610. /**
  34611. * Returns the line list draw mode
  34612. */
  34613. get: function () {
  34614. return Material._LineListDrawMode;
  34615. },
  34616. enumerable: true,
  34617. configurable: true
  34618. });
  34619. Object.defineProperty(Material, "LineLoopDrawMode", {
  34620. /**
  34621. * Returns the line loop draw mode
  34622. */
  34623. get: function () {
  34624. return Material._LineLoopDrawMode;
  34625. },
  34626. enumerable: true,
  34627. configurable: true
  34628. });
  34629. Object.defineProperty(Material, "LineStripDrawMode", {
  34630. /**
  34631. * Returns the line strip draw mode
  34632. */
  34633. get: function () {
  34634. return Material._LineStripDrawMode;
  34635. },
  34636. enumerable: true,
  34637. configurable: true
  34638. });
  34639. Object.defineProperty(Material, "TriangleStripDrawMode", {
  34640. /**
  34641. * Returns the triangle strip draw mode
  34642. */
  34643. get: function () {
  34644. return Material._TriangleStripDrawMode;
  34645. },
  34646. enumerable: true,
  34647. configurable: true
  34648. });
  34649. Object.defineProperty(Material, "TriangleFanDrawMode", {
  34650. /**
  34651. * Returns the triangle fan draw mode
  34652. */
  34653. get: function () {
  34654. return Material._TriangleFanDrawMode;
  34655. },
  34656. enumerable: true,
  34657. configurable: true
  34658. });
  34659. Object.defineProperty(Material, "ClockWiseSideOrientation", {
  34660. /**
  34661. * Returns the clock-wise side orientation
  34662. */
  34663. get: function () {
  34664. return Material._ClockWiseSideOrientation;
  34665. },
  34666. enumerable: true,
  34667. configurable: true
  34668. });
  34669. Object.defineProperty(Material, "CounterClockWiseSideOrientation", {
  34670. /**
  34671. * Returns the counter clock-wise side orientation
  34672. */
  34673. get: function () {
  34674. return Material._CounterClockWiseSideOrientation;
  34675. },
  34676. enumerable: true,
  34677. configurable: true
  34678. });
  34679. Object.defineProperty(Material, "TextureDirtyFlag", {
  34680. /**
  34681. * Returns the dirty texture flag value
  34682. */
  34683. get: function () {
  34684. return Material._TextureDirtyFlag;
  34685. },
  34686. enumerable: true,
  34687. configurable: true
  34688. });
  34689. Object.defineProperty(Material, "LightDirtyFlag", {
  34690. /**
  34691. * Returns the dirty light flag value
  34692. */
  34693. get: function () {
  34694. return Material._LightDirtyFlag;
  34695. },
  34696. enumerable: true,
  34697. configurable: true
  34698. });
  34699. Object.defineProperty(Material, "FresnelDirtyFlag", {
  34700. /**
  34701. * Returns the dirty fresnel flag value
  34702. */
  34703. get: function () {
  34704. return Material._FresnelDirtyFlag;
  34705. },
  34706. enumerable: true,
  34707. configurable: true
  34708. });
  34709. Object.defineProperty(Material, "AttributesDirtyFlag", {
  34710. /**
  34711. * Returns the dirty attributes flag value
  34712. */
  34713. get: function () {
  34714. return Material._AttributesDirtyFlag;
  34715. },
  34716. enumerable: true,
  34717. configurable: true
  34718. });
  34719. Object.defineProperty(Material, "MiscDirtyFlag", {
  34720. /**
  34721. * Returns the dirty misc flag value
  34722. */
  34723. get: function () {
  34724. return Material._MiscDirtyFlag;
  34725. },
  34726. enumerable: true,
  34727. configurable: true
  34728. });
  34729. Object.defineProperty(Material.prototype, "alpha", {
  34730. /**
  34731. * Gets the alpha value of the material
  34732. */
  34733. get: function () {
  34734. return this._alpha;
  34735. },
  34736. /**
  34737. * Sets the alpha value of the material
  34738. */
  34739. set: function (value) {
  34740. if (this._alpha === value) {
  34741. return;
  34742. }
  34743. this._alpha = value;
  34744. this.markAsDirty(Material.MiscDirtyFlag);
  34745. },
  34746. enumerable: true,
  34747. configurable: true
  34748. });
  34749. Object.defineProperty(Material.prototype, "backFaceCulling", {
  34750. /**
  34751. * Gets the back-face culling state
  34752. */
  34753. get: function () {
  34754. return this._backFaceCulling;
  34755. },
  34756. /**
  34757. * Sets the back-face culling state
  34758. */
  34759. set: function (value) {
  34760. if (this._backFaceCulling === value) {
  34761. return;
  34762. }
  34763. this._backFaceCulling = value;
  34764. this.markAsDirty(Material.TextureDirtyFlag);
  34765. },
  34766. enumerable: true,
  34767. configurable: true
  34768. });
  34769. Object.defineProperty(Material.prototype, "onDispose", {
  34770. /**
  34771. * Called during a dispose event
  34772. */
  34773. set: function (callback) {
  34774. if (this._onDisposeObserver) {
  34775. this.onDisposeObservable.remove(this._onDisposeObserver);
  34776. }
  34777. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  34778. },
  34779. enumerable: true,
  34780. configurable: true
  34781. });
  34782. Object.defineProperty(Material.prototype, "onBind", {
  34783. /**
  34784. * Called during a bind event
  34785. */
  34786. set: function (callback) {
  34787. if (this._onBindObserver) {
  34788. this.onBindObservable.remove(this._onBindObserver);
  34789. }
  34790. this._onBindObserver = this.onBindObservable.add(callback);
  34791. },
  34792. enumerable: true,
  34793. configurable: true
  34794. });
  34795. Object.defineProperty(Material.prototype, "alphaMode", {
  34796. /**
  34797. * Gets the value of the alpha mode
  34798. */
  34799. get: function () {
  34800. return this._alphaMode;
  34801. },
  34802. /**
  34803. * Sets the value of the alpha mode.
  34804. *
  34805. * | Value | Type | Description |
  34806. * | --- | --- | --- |
  34807. * | 0 | ALPHA_DISABLE | |
  34808. * | 1 | ALPHA_ADD | |
  34809. * | 2 | ALPHA_COMBINE | |
  34810. * | 3 | ALPHA_SUBTRACT | |
  34811. * | 4 | ALPHA_MULTIPLY | |
  34812. * | 5 | ALPHA_MAXIMIZED | |
  34813. * | 6 | ALPHA_ONEONE | |
  34814. * | 7 | ALPHA_PREMULTIPLIED | |
  34815. * | 8 | ALPHA_PREMULTIPLIED_PORTERDUFF | |
  34816. * | 9 | ALPHA_INTERPOLATE | |
  34817. * | 10 | ALPHA_SCREENMODE | |
  34818. *
  34819. */
  34820. set: function (value) {
  34821. if (this._alphaMode === value) {
  34822. return;
  34823. }
  34824. this._alphaMode = value;
  34825. this.markAsDirty(Material.TextureDirtyFlag);
  34826. },
  34827. enumerable: true,
  34828. configurable: true
  34829. });
  34830. Object.defineProperty(Material.prototype, "needDepthPrePass", {
  34831. /**
  34832. * Gets the depth pre-pass value
  34833. */
  34834. get: function () {
  34835. return this._needDepthPrePass;
  34836. },
  34837. /**
  34838. * Sets the need depth pre-pass value
  34839. */
  34840. set: function (value) {
  34841. if (this._needDepthPrePass === value) {
  34842. return;
  34843. }
  34844. this._needDepthPrePass = value;
  34845. if (this._needDepthPrePass) {
  34846. this.checkReadyOnEveryCall = true;
  34847. }
  34848. },
  34849. enumerable: true,
  34850. configurable: true
  34851. });
  34852. Object.defineProperty(Material.prototype, "fogEnabled", {
  34853. /**
  34854. * Gets the value of the fog enabled state
  34855. */
  34856. get: function () {
  34857. return this._fogEnabled;
  34858. },
  34859. /**
  34860. * Sets the state for enabling fog
  34861. */
  34862. set: function (value) {
  34863. if (this._fogEnabled === value) {
  34864. return;
  34865. }
  34866. this._fogEnabled = value;
  34867. this.markAsDirty(Material.MiscDirtyFlag);
  34868. },
  34869. enumerable: true,
  34870. configurable: true
  34871. });
  34872. Object.defineProperty(Material.prototype, "wireframe", {
  34873. /**
  34874. * Gets a value specifying if wireframe mode is enabled
  34875. */
  34876. get: function () {
  34877. switch (this._fillMode) {
  34878. case Material.WireFrameFillMode:
  34879. case Material.LineListDrawMode:
  34880. case Material.LineLoopDrawMode:
  34881. case Material.LineStripDrawMode:
  34882. return true;
  34883. }
  34884. return this._scene.forceWireframe;
  34885. },
  34886. /**
  34887. * Sets the state of wireframe mode
  34888. */
  34889. set: function (value) {
  34890. this.fillMode = (value ? Material.WireFrameFillMode : Material.TriangleFillMode);
  34891. },
  34892. enumerable: true,
  34893. configurable: true
  34894. });
  34895. Object.defineProperty(Material.prototype, "pointsCloud", {
  34896. /**
  34897. * Gets the value specifying if point clouds are enabled
  34898. */
  34899. get: function () {
  34900. switch (this._fillMode) {
  34901. case Material.PointFillMode:
  34902. case Material.PointListDrawMode:
  34903. return true;
  34904. }
  34905. return this._scene.forcePointsCloud;
  34906. },
  34907. /**
  34908. * Sets the state of point cloud mode
  34909. */
  34910. set: function (value) {
  34911. this.fillMode = (value ? Material.PointFillMode : Material.TriangleFillMode);
  34912. },
  34913. enumerable: true,
  34914. configurable: true
  34915. });
  34916. Object.defineProperty(Material.prototype, "fillMode", {
  34917. /**
  34918. * Gets the material fill mode
  34919. */
  34920. get: function () {
  34921. return this._fillMode;
  34922. },
  34923. /**
  34924. * Sets the material fill mode
  34925. */
  34926. set: function (value) {
  34927. if (this._fillMode === value) {
  34928. return;
  34929. }
  34930. this._fillMode = value;
  34931. this.markAsDirty(Material.MiscDirtyFlag);
  34932. },
  34933. enumerable: true,
  34934. configurable: true
  34935. });
  34936. /**
  34937. * Returns a string representation of the current material
  34938. * @param fullDetails defines a boolean indicating which levels of logging is desired
  34939. * @returns a string with material information
  34940. */
  34941. Material.prototype.toString = function (fullDetails) {
  34942. var ret = "Name: " + this.name;
  34943. if (fullDetails) {
  34944. }
  34945. return ret;
  34946. };
  34947. /**
  34948. * Gets the class name of the material
  34949. * @returns a string with the class name of the material
  34950. */
  34951. Material.prototype.getClassName = function () {
  34952. return "Material";
  34953. };
  34954. Object.defineProperty(Material.prototype, "isFrozen", {
  34955. /**
  34956. * Specifies if updates for the material been locked
  34957. */
  34958. get: function () {
  34959. return this.checkReadyOnlyOnce;
  34960. },
  34961. enumerable: true,
  34962. configurable: true
  34963. });
  34964. /**
  34965. * Locks updates for the material
  34966. */
  34967. Material.prototype.freeze = function () {
  34968. this.checkReadyOnlyOnce = true;
  34969. };
  34970. /**
  34971. * Unlocks updates for the material
  34972. */
  34973. Material.prototype.unfreeze = function () {
  34974. this.checkReadyOnlyOnce = false;
  34975. };
  34976. /**
  34977. * Specifies if the material is ready to be used
  34978. * @param mesh defines the mesh to check
  34979. * @param useInstances specifies if instances should be used
  34980. * @returns a boolean indicating if the material is ready to be used
  34981. */
  34982. Material.prototype.isReady = function (mesh, useInstances) {
  34983. return true;
  34984. };
  34985. /**
  34986. * Specifies that the submesh is ready to be used
  34987. * @param mesh defines the mesh to check
  34988. * @param subMesh defines which submesh to check
  34989. * @param useInstances specifies that instances should be used
  34990. * @returns a boolean indicating that the submesh is ready or not
  34991. */
  34992. Material.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  34993. return false;
  34994. };
  34995. /**
  34996. * Returns the material effect
  34997. * @returns the effect associated with the material
  34998. */
  34999. Material.prototype.getEffect = function () {
  35000. return this._effect;
  35001. };
  35002. /**
  35003. * Returns the current scene
  35004. * @returns a Scene
  35005. */
  35006. Material.prototype.getScene = function () {
  35007. return this._scene;
  35008. };
  35009. /**
  35010. * Specifies if the material will require alpha blending
  35011. * @returns a boolean specifying if alpha blending is needed
  35012. */
  35013. Material.prototype.needAlphaBlending = function () {
  35014. return (this.alpha < 1.0);
  35015. };
  35016. /**
  35017. * Specifies if the mesh will require alpha blending
  35018. * @param mesh defines the mesh to check
  35019. * @returns a boolean specifying if alpha blending is needed for the mesh
  35020. */
  35021. Material.prototype.needAlphaBlendingForMesh = function (mesh) {
  35022. return this.needAlphaBlending() || (mesh.visibility < 1.0) || mesh.hasVertexAlpha;
  35023. };
  35024. /**
  35025. * Specifies if this material should be rendered in alpha test mode
  35026. * @returns a boolean specifying if an alpha test is needed.
  35027. */
  35028. Material.prototype.needAlphaTesting = function () {
  35029. return false;
  35030. };
  35031. /**
  35032. * Gets the texture used for the alpha test
  35033. * @returns the texture to use for alpha testing
  35034. */
  35035. Material.prototype.getAlphaTestTexture = function () {
  35036. return null;
  35037. };
  35038. /**
  35039. * Marks the material to indicate that it needs to be re-calculated
  35040. */
  35041. Material.prototype.markDirty = function () {
  35042. this._wasPreviouslyReady = false;
  35043. };
  35044. /** @hidden */
  35045. Material.prototype._preBind = function (effect, overrideOrientation) {
  35046. if (overrideOrientation === void 0) { overrideOrientation = null; }
  35047. var engine = this._scene.getEngine();
  35048. var orientation = (overrideOrientation == null) ? this.sideOrientation : overrideOrientation;
  35049. var reverse = orientation === Material.ClockWiseSideOrientation;
  35050. engine.enableEffect(effect ? effect : this._effect);
  35051. engine.setState(this.backFaceCulling, this.zOffset, false, reverse);
  35052. return reverse;
  35053. };
  35054. /**
  35055. * Binds the material to the mesh
  35056. * @param world defines the world transformation matrix
  35057. * @param mesh defines the mesh to bind the material to
  35058. */
  35059. Material.prototype.bind = function (world, mesh) {
  35060. };
  35061. /**
  35062. * Binds the submesh to the material
  35063. * @param world defines the world transformation matrix
  35064. * @param mesh defines the mesh containing the submesh
  35065. * @param subMesh defines the submesh to bind the material to
  35066. */
  35067. Material.prototype.bindForSubMesh = function (world, mesh, subMesh) {
  35068. };
  35069. /**
  35070. * Binds the world matrix to the material
  35071. * @param world defines the world transformation matrix
  35072. */
  35073. Material.prototype.bindOnlyWorldMatrix = function (world) {
  35074. };
  35075. /**
  35076. * Binds the scene's uniform buffer to the effect.
  35077. * @param effect defines the effect to bind to the scene uniform buffer
  35078. * @param sceneUbo defines the uniform buffer storing scene data
  35079. */
  35080. Material.prototype.bindSceneUniformBuffer = function (effect, sceneUbo) {
  35081. sceneUbo.bindToEffect(effect, "Scene");
  35082. };
  35083. /**
  35084. * Binds the view matrix to the effect
  35085. * @param effect defines the effect to bind the view matrix to
  35086. */
  35087. Material.prototype.bindView = function (effect) {
  35088. if (!this._useUBO) {
  35089. effect.setMatrix("view", this.getScene().getViewMatrix());
  35090. }
  35091. else {
  35092. this.bindSceneUniformBuffer(effect, this.getScene().getSceneUniformBuffer());
  35093. }
  35094. };
  35095. /**
  35096. * Binds the view projection matrix to the effect
  35097. * @param effect defines the effect to bind the view projection matrix to
  35098. */
  35099. Material.prototype.bindViewProjection = function (effect) {
  35100. if (!this._useUBO) {
  35101. effect.setMatrix("viewProjection", this.getScene().getTransformMatrix());
  35102. }
  35103. else {
  35104. this.bindSceneUniformBuffer(effect, this.getScene().getSceneUniformBuffer());
  35105. }
  35106. };
  35107. /**
  35108. * Specifies if material alpha testing should be turned on for the mesh
  35109. * @param mesh defines the mesh to check
  35110. */
  35111. Material.prototype._shouldTurnAlphaTestOn = function (mesh) {
  35112. return (!this.needAlphaBlendingForMesh(mesh) && this.needAlphaTesting());
  35113. };
  35114. /**
  35115. * Processes to execute after binding the material to a mesh
  35116. * @param mesh defines the rendered mesh
  35117. */
  35118. Material.prototype._afterBind = function (mesh) {
  35119. this._scene._cachedMaterial = this;
  35120. if (mesh) {
  35121. this._scene._cachedVisibility = mesh.visibility;
  35122. }
  35123. else {
  35124. this._scene._cachedVisibility = 1;
  35125. }
  35126. if (mesh) {
  35127. this.onBindObservable.notifyObservers(mesh);
  35128. }
  35129. if (this.disableDepthWrite) {
  35130. var engine = this._scene.getEngine();
  35131. this._cachedDepthWriteState = engine.getDepthWrite();
  35132. engine.setDepthWrite(false);
  35133. }
  35134. };
  35135. /**
  35136. * Unbinds the material from the mesh
  35137. */
  35138. Material.prototype.unbind = function () {
  35139. this.onUnBindObservable.notifyObservers(this);
  35140. if (this.disableDepthWrite) {
  35141. var engine = this._scene.getEngine();
  35142. engine.setDepthWrite(this._cachedDepthWriteState);
  35143. }
  35144. };
  35145. /**
  35146. * Gets the active textures from the material
  35147. * @returns an array of textures
  35148. */
  35149. Material.prototype.getActiveTextures = function () {
  35150. return [];
  35151. };
  35152. /**
  35153. * Specifies if the material uses a texture
  35154. * @param texture defines the texture to check against the material
  35155. * @returns a boolean specifying if the material uses the texture
  35156. */
  35157. Material.prototype.hasTexture = function (texture) {
  35158. return false;
  35159. };
  35160. /**
  35161. * Makes a duplicate of the material, and gives it a new name
  35162. * @param name defines the new name for the duplicated material
  35163. * @returns the cloned material
  35164. */
  35165. Material.prototype.clone = function (name) {
  35166. return null;
  35167. };
  35168. /**
  35169. * Gets the meshes bound to the material
  35170. * @returns an array of meshes bound to the material
  35171. */
  35172. Material.prototype.getBindedMeshes = function () {
  35173. var result = new Array();
  35174. for (var index = 0; index < this._scene.meshes.length; index++) {
  35175. var mesh = this._scene.meshes[index];
  35176. if (mesh.material === this) {
  35177. result.push(mesh);
  35178. }
  35179. }
  35180. return result;
  35181. };
  35182. /**
  35183. * Force shader compilation
  35184. * @param mesh defines the mesh associated with this material
  35185. * @param onCompiled defines a function to execute once the material is compiled
  35186. * @param options defines the options to configure the compilation
  35187. */
  35188. Material.prototype.forceCompilation = function (mesh, onCompiled, options) {
  35189. var _this = this;
  35190. var localOptions = __assign({ clipPlane: false }, options);
  35191. var subMesh = new BABYLON.BaseSubMesh();
  35192. var scene = this.getScene();
  35193. var checkReady = function () {
  35194. if (!_this._scene || !_this._scene.getEngine()) {
  35195. return;
  35196. }
  35197. if (subMesh._materialDefines) {
  35198. subMesh._materialDefines._renderId = -1;
  35199. }
  35200. var clipPlaneState = scene.clipPlane;
  35201. if (localOptions.clipPlane) {
  35202. scene.clipPlane = new BABYLON.Plane(0, 0, 0, 1);
  35203. }
  35204. if (_this.storeEffectOnSubMeshes) {
  35205. if (_this.isReadyForSubMesh(mesh, subMesh)) {
  35206. if (onCompiled) {
  35207. onCompiled(_this);
  35208. }
  35209. }
  35210. else {
  35211. setTimeout(checkReady, 16);
  35212. }
  35213. }
  35214. else {
  35215. if (_this.isReady(mesh)) {
  35216. if (onCompiled) {
  35217. onCompiled(_this);
  35218. }
  35219. }
  35220. else {
  35221. setTimeout(checkReady, 16);
  35222. }
  35223. }
  35224. if (localOptions.clipPlane) {
  35225. scene.clipPlane = clipPlaneState;
  35226. }
  35227. };
  35228. checkReady();
  35229. };
  35230. /**
  35231. * Force shader compilation
  35232. * @param mesh defines the mesh that will use this material
  35233. * @param options defines additional options for compiling the shaders
  35234. * @returns a promise that resolves when the compilation completes
  35235. */
  35236. Material.prototype.forceCompilationAsync = function (mesh, options) {
  35237. var _this = this;
  35238. return new Promise(function (resolve) {
  35239. _this.forceCompilation(mesh, function () {
  35240. resolve();
  35241. }, options);
  35242. });
  35243. };
  35244. /**
  35245. * Marks a define in the material to indicate that it needs to be re-computed
  35246. * @param flag defines a flag used to determine which parts of the material have to be marked as dirty
  35247. */
  35248. Material.prototype.markAsDirty = function (flag) {
  35249. if (flag & Material.TextureDirtyFlag) {
  35250. this._markAllSubMeshesAsTexturesDirty();
  35251. }
  35252. if (flag & Material.LightDirtyFlag) {
  35253. this._markAllSubMeshesAsLightsDirty();
  35254. }
  35255. if (flag & Material.FresnelDirtyFlag) {
  35256. this._markAllSubMeshesAsFresnelDirty();
  35257. }
  35258. if (flag & Material.AttributesDirtyFlag) {
  35259. this._markAllSubMeshesAsAttributesDirty();
  35260. }
  35261. if (flag & Material.MiscDirtyFlag) {
  35262. this._markAllSubMeshesAsMiscDirty();
  35263. }
  35264. this.getScene().resetCachedMaterial();
  35265. };
  35266. /**
  35267. * Marks all submeshes of a material to indicate that their material defines need to be re-calculated
  35268. * @param func defines a function which checks material defines against the submeshes
  35269. */
  35270. Material.prototype._markAllSubMeshesAsDirty = function (func) {
  35271. for (var _i = 0, _a = this.getScene().meshes; _i < _a.length; _i++) {
  35272. var mesh = _a[_i];
  35273. if (!mesh.subMeshes) {
  35274. continue;
  35275. }
  35276. for (var _b = 0, _c = mesh.subMeshes; _b < _c.length; _b++) {
  35277. var subMesh = _c[_b];
  35278. if (subMesh.getMaterial() !== this) {
  35279. continue;
  35280. }
  35281. if (!subMesh._materialDefines) {
  35282. continue;
  35283. }
  35284. func(subMesh._materialDefines);
  35285. }
  35286. }
  35287. };
  35288. /**
  35289. * Indicates that image processing needs to be re-calculated for all submeshes
  35290. */
  35291. Material.prototype._markAllSubMeshesAsImageProcessingDirty = function () {
  35292. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsImageProcessingDirty(); });
  35293. };
  35294. /**
  35295. * Indicates that textures need to be re-calculated for all submeshes
  35296. */
  35297. Material.prototype._markAllSubMeshesAsTexturesDirty = function () {
  35298. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsTexturesDirty(); });
  35299. };
  35300. /**
  35301. * Indicates that fresnel needs to be re-calculated for all submeshes
  35302. */
  35303. Material.prototype._markAllSubMeshesAsFresnelDirty = function () {
  35304. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsFresnelDirty(); });
  35305. };
  35306. /**
  35307. * Indicates that fresnel and misc need to be re-calculated for all submeshes
  35308. */
  35309. Material.prototype._markAllSubMeshesAsFresnelAndMiscDirty = function () {
  35310. this._markAllSubMeshesAsDirty(function (defines) {
  35311. defines.markAsFresnelDirty();
  35312. defines.markAsMiscDirty();
  35313. });
  35314. };
  35315. /**
  35316. * Indicates that lights need to be re-calculated for all submeshes
  35317. */
  35318. Material.prototype._markAllSubMeshesAsLightsDirty = function () {
  35319. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsLightDirty(); });
  35320. };
  35321. /**
  35322. * Indicates that attributes need to be re-calculated for all submeshes
  35323. */
  35324. Material.prototype._markAllSubMeshesAsAttributesDirty = function () {
  35325. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsAttributesDirty(); });
  35326. };
  35327. /**
  35328. * Indicates that misc needs to be re-calculated for all submeshes
  35329. */
  35330. Material.prototype._markAllSubMeshesAsMiscDirty = function () {
  35331. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsMiscDirty(); });
  35332. };
  35333. /**
  35334. * Indicates that textures and misc need to be re-calculated for all submeshes
  35335. */
  35336. Material.prototype._markAllSubMeshesAsTexturesAndMiscDirty = function () {
  35337. this._markAllSubMeshesAsDirty(function (defines) {
  35338. defines.markAsTexturesDirty();
  35339. defines.markAsMiscDirty();
  35340. });
  35341. };
  35342. /**
  35343. * Disposes the material
  35344. * @param forceDisposeEffect specifies if effects should be forcefully disposed
  35345. * @param forceDisposeTextures specifies if textures should be forcefully disposed
  35346. */
  35347. Material.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  35348. // Animations
  35349. this.getScene().stopAnimation(this);
  35350. this.getScene().freeProcessedMaterials();
  35351. // Remove from scene
  35352. var index = this._scene.materials.indexOf(this);
  35353. if (index >= 0) {
  35354. this._scene.materials.splice(index, 1);
  35355. }
  35356. // Remove from meshes
  35357. for (index = 0; index < this._scene.meshes.length; index++) {
  35358. var mesh = this._scene.meshes[index];
  35359. if (mesh.material === this) {
  35360. mesh.material = null;
  35361. if (mesh.geometry) {
  35362. var geometry = (mesh.geometry);
  35363. if (this.storeEffectOnSubMeshes) {
  35364. for (var _i = 0, _a = mesh.subMeshes; _i < _a.length; _i++) {
  35365. var subMesh = _a[_i];
  35366. geometry._releaseVertexArrayObject(subMesh._materialEffect);
  35367. if (forceDisposeEffect && subMesh._materialEffect) {
  35368. this._scene.getEngine()._releaseEffect(subMesh._materialEffect);
  35369. }
  35370. }
  35371. }
  35372. else {
  35373. geometry._releaseVertexArrayObject(this._effect);
  35374. }
  35375. }
  35376. }
  35377. }
  35378. this._uniformBuffer.dispose();
  35379. // Shader are kept in cache for further use but we can get rid of this by using forceDisposeEffect
  35380. if (forceDisposeEffect && this._effect) {
  35381. if (!this.storeEffectOnSubMeshes) {
  35382. this._scene.getEngine()._releaseEffect(this._effect);
  35383. }
  35384. this._effect = null;
  35385. }
  35386. // Callback
  35387. this.onDisposeObservable.notifyObservers(this);
  35388. this.onDisposeObservable.clear();
  35389. this.onBindObservable.clear();
  35390. this.onUnBindObservable.clear();
  35391. };
  35392. /**
  35393. * Serializes this material
  35394. * @returns the serialized material object
  35395. */
  35396. Material.prototype.serialize = function () {
  35397. return BABYLON.SerializationHelper.Serialize(this);
  35398. };
  35399. /**
  35400. * Creates a MultiMaterial from parsed MultiMaterial data.
  35401. * @param parsedMultiMaterial defines parsed MultiMaterial data.
  35402. * @param scene defines the hosting scene
  35403. * @returns a new MultiMaterial
  35404. */
  35405. Material.ParseMultiMaterial = function (parsedMultiMaterial, scene) {
  35406. var multiMaterial = new BABYLON.MultiMaterial(parsedMultiMaterial.name, scene);
  35407. multiMaterial.id = parsedMultiMaterial.id;
  35408. if (BABYLON.Tags) {
  35409. BABYLON.Tags.AddTagsTo(multiMaterial, parsedMultiMaterial.tags);
  35410. }
  35411. for (var matIndex = 0; matIndex < parsedMultiMaterial.materials.length; matIndex++) {
  35412. var subMatId = parsedMultiMaterial.materials[matIndex];
  35413. if (subMatId) {
  35414. multiMaterial.subMaterials.push(scene.getMaterialByID(subMatId));
  35415. }
  35416. else {
  35417. multiMaterial.subMaterials.push(null);
  35418. }
  35419. }
  35420. return multiMaterial;
  35421. };
  35422. /**
  35423. * Creates a material from parsed material data
  35424. * @param parsedMaterial defines parsed material data
  35425. * @param scene defines the hosting scene
  35426. * @param rootUrl defines the root URL to use to load textures
  35427. * @returns a new material
  35428. */
  35429. Material.Parse = function (parsedMaterial, scene, rootUrl) {
  35430. if (!parsedMaterial.customType || parsedMaterial.customType === "BABYLON.StandardMaterial") {
  35431. return BABYLON.StandardMaterial.Parse(parsedMaterial, scene, rootUrl);
  35432. }
  35433. if (parsedMaterial.customType === "BABYLON.PBRMaterial" && parsedMaterial.overloadedAlbedo) {
  35434. parsedMaterial.customType = "BABYLON.LegacyPBRMaterial";
  35435. if (!BABYLON.LegacyPBRMaterial) {
  35436. BABYLON.Tools.Error("Your scene is trying to load a legacy version of the PBRMaterial, please, include it from the materials library.");
  35437. return;
  35438. }
  35439. }
  35440. var materialType = BABYLON.Tools.Instantiate(parsedMaterial.customType);
  35441. return materialType.Parse(parsedMaterial, scene, rootUrl);
  35442. ;
  35443. };
  35444. // Triangle views
  35445. Material._TriangleFillMode = 0;
  35446. Material._WireFrameFillMode = 1;
  35447. Material._PointFillMode = 2;
  35448. // Draw modes
  35449. Material._PointListDrawMode = 3;
  35450. Material._LineListDrawMode = 4;
  35451. Material._LineLoopDrawMode = 5;
  35452. Material._LineStripDrawMode = 6;
  35453. Material._TriangleStripDrawMode = 7;
  35454. Material._TriangleFanDrawMode = 8;
  35455. /**
  35456. * Stores the clock-wise side orientation
  35457. */
  35458. Material._ClockWiseSideOrientation = 0;
  35459. /**
  35460. * Stores the counter clock-wise side orientation
  35461. */
  35462. Material._CounterClockWiseSideOrientation = 1;
  35463. /**
  35464. * The dirty texture flag value
  35465. */
  35466. Material._TextureDirtyFlag = 1;
  35467. /**
  35468. * The dirty light flag value
  35469. */
  35470. Material._LightDirtyFlag = 2;
  35471. /**
  35472. * The dirty fresnel flag value
  35473. */
  35474. Material._FresnelDirtyFlag = 4;
  35475. /**
  35476. * The dirty attribute flag value
  35477. */
  35478. Material._AttributesDirtyFlag = 8;
  35479. /**
  35480. * The dirty misc flag value
  35481. */
  35482. Material._MiscDirtyFlag = 16;
  35483. __decorate([
  35484. BABYLON.serialize()
  35485. ], Material.prototype, "id", void 0);
  35486. __decorate([
  35487. BABYLON.serialize()
  35488. ], Material.prototype, "name", void 0);
  35489. __decorate([
  35490. BABYLON.serialize()
  35491. ], Material.prototype, "checkReadyOnEveryCall", void 0);
  35492. __decorate([
  35493. BABYLON.serialize()
  35494. ], Material.prototype, "checkReadyOnlyOnce", void 0);
  35495. __decorate([
  35496. BABYLON.serialize()
  35497. ], Material.prototype, "state", void 0);
  35498. __decorate([
  35499. BABYLON.serialize("alpha")
  35500. ], Material.prototype, "_alpha", void 0);
  35501. __decorate([
  35502. BABYLON.serialize("backFaceCulling")
  35503. ], Material.prototype, "_backFaceCulling", void 0);
  35504. __decorate([
  35505. BABYLON.serialize()
  35506. ], Material.prototype, "sideOrientation", void 0);
  35507. __decorate([
  35508. BABYLON.serialize("alphaMode")
  35509. ], Material.prototype, "_alphaMode", void 0);
  35510. __decorate([
  35511. BABYLON.serialize()
  35512. ], Material.prototype, "_needDepthPrePass", void 0);
  35513. __decorate([
  35514. BABYLON.serialize()
  35515. ], Material.prototype, "disableDepthWrite", void 0);
  35516. __decorate([
  35517. BABYLON.serialize()
  35518. ], Material.prototype, "forceDepthWrite", void 0);
  35519. __decorate([
  35520. BABYLON.serialize()
  35521. ], Material.prototype, "separateCullingPass", void 0);
  35522. __decorate([
  35523. BABYLON.serialize("fogEnabled")
  35524. ], Material.prototype, "_fogEnabled", void 0);
  35525. __decorate([
  35526. BABYLON.serialize()
  35527. ], Material.prototype, "pointSize", void 0);
  35528. __decorate([
  35529. BABYLON.serialize()
  35530. ], Material.prototype, "zOffset", void 0);
  35531. __decorate([
  35532. BABYLON.serialize()
  35533. ], Material.prototype, "wireframe", null);
  35534. __decorate([
  35535. BABYLON.serialize()
  35536. ], Material.prototype, "pointsCloud", null);
  35537. __decorate([
  35538. BABYLON.serialize()
  35539. ], Material.prototype, "fillMode", null);
  35540. return Material;
  35541. }());
  35542. BABYLON.Material = Material;
  35543. })(BABYLON || (BABYLON = {}));
  35544. //# sourceMappingURL=babylon.material.js.map
  35545. var BABYLON;
  35546. (function (BABYLON) {
  35547. var UniformBuffer = /** @class */ (function () {
  35548. /**
  35549. * Uniform buffer objects.
  35550. *
  35551. * Handles blocks of uniform on the GPU.
  35552. *
  35553. * If WebGL 2 is not available, this class falls back on traditionnal setUniformXXX calls.
  35554. *
  35555. * For more information, please refer to :
  35556. * https://www.khronos.org/opengl/wiki/Uniform_Buffer_Object
  35557. */
  35558. function UniformBuffer(engine, data, dynamic) {
  35559. this._engine = engine;
  35560. this._noUBO = !engine.supportsUniformBuffers;
  35561. this._dynamic = dynamic;
  35562. this._data = data || [];
  35563. this._uniformLocations = {};
  35564. this._uniformSizes = {};
  35565. this._uniformLocationPointer = 0;
  35566. this._needSync = false;
  35567. if (this._noUBO) {
  35568. this.updateMatrix3x3 = this._updateMatrix3x3ForEffect;
  35569. this.updateMatrix2x2 = this._updateMatrix2x2ForEffect;
  35570. this.updateFloat = this._updateFloatForEffect;
  35571. this.updateFloat2 = this._updateFloat2ForEffect;
  35572. this.updateFloat3 = this._updateFloat3ForEffect;
  35573. this.updateFloat4 = this._updateFloat4ForEffect;
  35574. this.updateMatrix = this._updateMatrixForEffect;
  35575. this.updateVector3 = this._updateVector3ForEffect;
  35576. this.updateVector4 = this._updateVector4ForEffect;
  35577. this.updateColor3 = this._updateColor3ForEffect;
  35578. this.updateColor4 = this._updateColor4ForEffect;
  35579. }
  35580. else {
  35581. this._engine._uniformBuffers.push(this);
  35582. this.updateMatrix3x3 = this._updateMatrix3x3ForUniform;
  35583. this.updateMatrix2x2 = this._updateMatrix2x2ForUniform;
  35584. this.updateFloat = this._updateFloatForUniform;
  35585. this.updateFloat2 = this._updateFloat2ForUniform;
  35586. this.updateFloat3 = this._updateFloat3ForUniform;
  35587. this.updateFloat4 = this._updateFloat4ForUniform;
  35588. this.updateMatrix = this._updateMatrixForUniform;
  35589. this.updateVector3 = this._updateVector3ForUniform;
  35590. this.updateVector4 = this._updateVector4ForUniform;
  35591. this.updateColor3 = this._updateColor3ForUniform;
  35592. this.updateColor4 = this._updateColor4ForUniform;
  35593. }
  35594. }
  35595. Object.defineProperty(UniformBuffer.prototype, "useUbo", {
  35596. // Properties
  35597. /**
  35598. * Indicates if the buffer is using the WebGL2 UBO implementation,
  35599. * or just falling back on setUniformXXX calls.
  35600. */
  35601. get: function () {
  35602. return !this._noUBO;
  35603. },
  35604. enumerable: true,
  35605. configurable: true
  35606. });
  35607. Object.defineProperty(UniformBuffer.prototype, "isSync", {
  35608. /**
  35609. * Indicates if the WebGL underlying uniform buffer is in sync
  35610. * with the javascript cache data.
  35611. */
  35612. get: function () {
  35613. return !this._needSync;
  35614. },
  35615. enumerable: true,
  35616. configurable: true
  35617. });
  35618. /**
  35619. * Indicates if the WebGL underlying uniform buffer is dynamic.
  35620. * Also, a dynamic UniformBuffer will disable cache verification and always
  35621. * update the underlying WebGL uniform buffer to the GPU.
  35622. */
  35623. UniformBuffer.prototype.isDynamic = function () {
  35624. return this._dynamic !== undefined;
  35625. };
  35626. /**
  35627. * The data cache on JS side.
  35628. */
  35629. UniformBuffer.prototype.getData = function () {
  35630. return this._bufferData;
  35631. };
  35632. /**
  35633. * The underlying WebGL Uniform buffer.
  35634. */
  35635. UniformBuffer.prototype.getBuffer = function () {
  35636. return this._buffer;
  35637. };
  35638. /**
  35639. * std140 layout specifies how to align data within an UBO structure.
  35640. * See https://khronos.org/registry/OpenGL/specs/gl/glspec45.core.pdf#page=159
  35641. * for specs.
  35642. */
  35643. UniformBuffer.prototype._fillAlignment = function (size) {
  35644. // This code has been simplified because we only use floats, vectors of 1, 2, 3, 4 components
  35645. // and 4x4 matrices
  35646. // TODO : change if other types are used
  35647. var alignment;
  35648. if (size <= 2) {
  35649. alignment = size;
  35650. }
  35651. else {
  35652. alignment = 4;
  35653. }
  35654. if ((this._uniformLocationPointer % alignment) !== 0) {
  35655. var oldPointer = this._uniformLocationPointer;
  35656. this._uniformLocationPointer += alignment - (this._uniformLocationPointer % alignment);
  35657. var diff = this._uniformLocationPointer - oldPointer;
  35658. for (var i = 0; i < diff; i++) {
  35659. this._data.push(0);
  35660. }
  35661. }
  35662. };
  35663. /**
  35664. * Adds an uniform in the buffer.
  35665. * Warning : the subsequents calls of this function must be in the same order as declared in the shader
  35666. * for the layout to be correct !
  35667. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  35668. * @param {number|number[]} size Data size, or data directly.
  35669. */
  35670. UniformBuffer.prototype.addUniform = function (name, size) {
  35671. if (this._noUBO) {
  35672. return;
  35673. }
  35674. if (this._uniformLocations[name] !== undefined) {
  35675. // Already existing uniform
  35676. return;
  35677. }
  35678. // This function must be called in the order of the shader layout !
  35679. // size can be the size of the uniform, or data directly
  35680. var data;
  35681. if (size instanceof Array) {
  35682. data = size;
  35683. size = data.length;
  35684. }
  35685. else {
  35686. size = size;
  35687. data = [];
  35688. // Fill with zeros
  35689. for (var i = 0; i < size; i++) {
  35690. data.push(0);
  35691. }
  35692. }
  35693. this._fillAlignment(size);
  35694. this._uniformSizes[name] = size;
  35695. this._uniformLocations[name] = this._uniformLocationPointer;
  35696. this._uniformLocationPointer += size;
  35697. for (var i = 0; i < size; i++) {
  35698. this._data.push(data[i]);
  35699. }
  35700. this._needSync = true;
  35701. };
  35702. /**
  35703. * Wrapper for addUniform.
  35704. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  35705. * @param {Matrix} mat A 4x4 matrix.
  35706. */
  35707. UniformBuffer.prototype.addMatrix = function (name, mat) {
  35708. this.addUniform(name, Array.prototype.slice.call(mat.toArray()));
  35709. };
  35710. /**
  35711. * Wrapper for addUniform.
  35712. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  35713. * @param {number} x
  35714. * @param {number} y
  35715. */
  35716. UniformBuffer.prototype.addFloat2 = function (name, x, y) {
  35717. var temp = [x, y];
  35718. this.addUniform(name, temp);
  35719. };
  35720. /**
  35721. * Wrapper for addUniform.
  35722. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  35723. * @param {number} x
  35724. * @param {number} y
  35725. * @param {number} z
  35726. */
  35727. UniformBuffer.prototype.addFloat3 = function (name, x, y, z) {
  35728. var temp = [x, y, z];
  35729. this.addUniform(name, temp);
  35730. };
  35731. /**
  35732. * Wrapper for addUniform.
  35733. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  35734. * @param {Color3} color
  35735. */
  35736. UniformBuffer.prototype.addColor3 = function (name, color) {
  35737. var temp = new Array();
  35738. color.toArray(temp);
  35739. this.addUniform(name, temp);
  35740. };
  35741. /**
  35742. * Wrapper for addUniform.
  35743. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  35744. * @param {Color3} color
  35745. * @param {number} alpha
  35746. */
  35747. UniformBuffer.prototype.addColor4 = function (name, color, alpha) {
  35748. var temp = new Array();
  35749. color.toArray(temp);
  35750. temp.push(alpha);
  35751. this.addUniform(name, temp);
  35752. };
  35753. /**
  35754. * Wrapper for addUniform.
  35755. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  35756. * @param {Vector3} vector
  35757. */
  35758. UniformBuffer.prototype.addVector3 = function (name, vector) {
  35759. var temp = new Array();
  35760. vector.toArray(temp);
  35761. this.addUniform(name, temp);
  35762. };
  35763. /**
  35764. * Wrapper for addUniform.
  35765. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  35766. */
  35767. UniformBuffer.prototype.addMatrix3x3 = function (name) {
  35768. this.addUniform(name, 12);
  35769. };
  35770. /**
  35771. * Wrapper for addUniform.
  35772. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  35773. */
  35774. UniformBuffer.prototype.addMatrix2x2 = function (name) {
  35775. this.addUniform(name, 8);
  35776. };
  35777. /**
  35778. * Effectively creates the WebGL Uniform Buffer, once layout is completed with `addUniform`.
  35779. */
  35780. UniformBuffer.prototype.create = function () {
  35781. if (this._noUBO) {
  35782. return;
  35783. }
  35784. if (this._buffer) {
  35785. return; // nothing to do
  35786. }
  35787. // See spec, alignment must be filled as a vec4
  35788. this._fillAlignment(4);
  35789. this._bufferData = new Float32Array(this._data);
  35790. this._rebuild();
  35791. this._needSync = true;
  35792. };
  35793. UniformBuffer.prototype._rebuild = function () {
  35794. if (this._noUBO) {
  35795. return;
  35796. }
  35797. if (this._dynamic) {
  35798. this._buffer = this._engine.createDynamicUniformBuffer(this._bufferData);
  35799. }
  35800. else {
  35801. this._buffer = this._engine.createUniformBuffer(this._bufferData);
  35802. }
  35803. };
  35804. /**
  35805. * Updates the WebGL Uniform Buffer on the GPU.
  35806. * If the `dynamic` flag is set to true, no cache comparison is done.
  35807. * Otherwise, the buffer will be updated only if the cache differs.
  35808. */
  35809. UniformBuffer.prototype.update = function () {
  35810. if (!this._buffer) {
  35811. this.create();
  35812. return;
  35813. }
  35814. if (!this._dynamic && !this._needSync) {
  35815. return;
  35816. }
  35817. this._engine.updateUniformBuffer(this._buffer, this._bufferData);
  35818. this._needSync = false;
  35819. };
  35820. /**
  35821. * Updates the value of an uniform. The `update` method must be called afterwards to make it effective in the GPU.
  35822. * @param {string} uniformName Name of the uniform, as used in the uniform block in the shader.
  35823. * @param {number[]|Float32Array} data Flattened data
  35824. * @param {number} size Size of the data.
  35825. */
  35826. UniformBuffer.prototype.updateUniform = function (uniformName, data, size) {
  35827. var location = this._uniformLocations[uniformName];
  35828. if (location === undefined) {
  35829. if (this._buffer) {
  35830. // Cannot add an uniform if the buffer is already created
  35831. BABYLON.Tools.Error("Cannot add an uniform after UBO has been created.");
  35832. return;
  35833. }
  35834. this.addUniform(uniformName, size);
  35835. location = this._uniformLocations[uniformName];
  35836. }
  35837. if (!this._buffer) {
  35838. this.create();
  35839. }
  35840. if (!this._dynamic) {
  35841. // Cache for static uniform buffers
  35842. var changed = false;
  35843. for (var i = 0; i < size; i++) {
  35844. if (this._bufferData[location + i] !== data[i]) {
  35845. changed = true;
  35846. this._bufferData[location + i] = data[i];
  35847. }
  35848. }
  35849. this._needSync = this._needSync || changed;
  35850. }
  35851. else {
  35852. // No cache for dynamic
  35853. for (var i = 0; i < size; i++) {
  35854. this._bufferData[location + i] = data[i];
  35855. }
  35856. }
  35857. };
  35858. // Update methods
  35859. UniformBuffer.prototype._updateMatrix3x3ForUniform = function (name, matrix) {
  35860. // To match std140, matrix must be realigned
  35861. for (var i = 0; i < 3; i++) {
  35862. UniformBuffer._tempBuffer[i * 4] = matrix[i * 3];
  35863. UniformBuffer._tempBuffer[i * 4 + 1] = matrix[i * 3 + 1];
  35864. UniformBuffer._tempBuffer[i * 4 + 2] = matrix[i * 3 + 2];
  35865. UniformBuffer._tempBuffer[i * 4 + 3] = 0.0;
  35866. }
  35867. this.updateUniform(name, UniformBuffer._tempBuffer, 12);
  35868. };
  35869. UniformBuffer.prototype._updateMatrix3x3ForEffect = function (name, matrix) {
  35870. this._currentEffect.setMatrix3x3(name, matrix);
  35871. };
  35872. UniformBuffer.prototype._updateMatrix2x2ForEffect = function (name, matrix) {
  35873. this._currentEffect.setMatrix2x2(name, matrix);
  35874. };
  35875. UniformBuffer.prototype._updateMatrix2x2ForUniform = function (name, matrix) {
  35876. // To match std140, matrix must be realigned
  35877. for (var i = 0; i < 2; i++) {
  35878. UniformBuffer._tempBuffer[i * 4] = matrix[i * 2];
  35879. UniformBuffer._tempBuffer[i * 4 + 1] = matrix[i * 2 + 1];
  35880. UniformBuffer._tempBuffer[i * 4 + 2] = 0.0;
  35881. UniformBuffer._tempBuffer[i * 4 + 3] = 0.0;
  35882. }
  35883. this.updateUniform(name, UniformBuffer._tempBuffer, 8);
  35884. };
  35885. UniformBuffer.prototype._updateFloatForEffect = function (name, x) {
  35886. this._currentEffect.setFloat(name, x);
  35887. };
  35888. UniformBuffer.prototype._updateFloatForUniform = function (name, x) {
  35889. UniformBuffer._tempBuffer[0] = x;
  35890. this.updateUniform(name, UniformBuffer._tempBuffer, 1);
  35891. };
  35892. UniformBuffer.prototype._updateFloat2ForEffect = function (name, x, y, suffix) {
  35893. if (suffix === void 0) { suffix = ""; }
  35894. this._currentEffect.setFloat2(name + suffix, x, y);
  35895. };
  35896. UniformBuffer.prototype._updateFloat2ForUniform = function (name, x, y, suffix) {
  35897. if (suffix === void 0) { suffix = ""; }
  35898. UniformBuffer._tempBuffer[0] = x;
  35899. UniformBuffer._tempBuffer[1] = y;
  35900. this.updateUniform(name, UniformBuffer._tempBuffer, 2);
  35901. };
  35902. UniformBuffer.prototype._updateFloat3ForEffect = function (name, x, y, z, suffix) {
  35903. if (suffix === void 0) { suffix = ""; }
  35904. this._currentEffect.setFloat3(name + suffix, x, y, z);
  35905. };
  35906. UniformBuffer.prototype._updateFloat3ForUniform = function (name, x, y, z, suffix) {
  35907. if (suffix === void 0) { suffix = ""; }
  35908. UniformBuffer._tempBuffer[0] = x;
  35909. UniformBuffer._tempBuffer[1] = y;
  35910. UniformBuffer._tempBuffer[2] = z;
  35911. this.updateUniform(name, UniformBuffer._tempBuffer, 3);
  35912. };
  35913. UniformBuffer.prototype._updateFloat4ForEffect = function (name, x, y, z, w, suffix) {
  35914. if (suffix === void 0) { suffix = ""; }
  35915. this._currentEffect.setFloat4(name + suffix, x, y, z, w);
  35916. };
  35917. UniformBuffer.prototype._updateFloat4ForUniform = function (name, x, y, z, w, suffix) {
  35918. if (suffix === void 0) { suffix = ""; }
  35919. UniformBuffer._tempBuffer[0] = x;
  35920. UniformBuffer._tempBuffer[1] = y;
  35921. UniformBuffer._tempBuffer[2] = z;
  35922. UniformBuffer._tempBuffer[3] = w;
  35923. this.updateUniform(name, UniformBuffer._tempBuffer, 4);
  35924. };
  35925. UniformBuffer.prototype._updateMatrixForEffect = function (name, mat) {
  35926. this._currentEffect.setMatrix(name, mat);
  35927. };
  35928. UniformBuffer.prototype._updateMatrixForUniform = function (name, mat) {
  35929. this.updateUniform(name, mat.toArray(), 16);
  35930. };
  35931. UniformBuffer.prototype._updateVector3ForEffect = function (name, vector) {
  35932. this._currentEffect.setVector3(name, vector);
  35933. };
  35934. UniformBuffer.prototype._updateVector3ForUniform = function (name, vector) {
  35935. vector.toArray(UniformBuffer._tempBuffer);
  35936. this.updateUniform(name, UniformBuffer._tempBuffer, 3);
  35937. };
  35938. UniformBuffer.prototype._updateVector4ForEffect = function (name, vector) {
  35939. this._currentEffect.setVector4(name, vector);
  35940. };
  35941. UniformBuffer.prototype._updateVector4ForUniform = function (name, vector) {
  35942. vector.toArray(UniformBuffer._tempBuffer);
  35943. this.updateUniform(name, UniformBuffer._tempBuffer, 4);
  35944. };
  35945. UniformBuffer.prototype._updateColor3ForEffect = function (name, color, suffix) {
  35946. if (suffix === void 0) { suffix = ""; }
  35947. this._currentEffect.setColor3(name + suffix, color);
  35948. };
  35949. UniformBuffer.prototype._updateColor3ForUniform = function (name, color, suffix) {
  35950. if (suffix === void 0) { suffix = ""; }
  35951. color.toArray(UniformBuffer._tempBuffer);
  35952. this.updateUniform(name, UniformBuffer._tempBuffer, 3);
  35953. };
  35954. UniformBuffer.prototype._updateColor4ForEffect = function (name, color, alpha, suffix) {
  35955. if (suffix === void 0) { suffix = ""; }
  35956. this._currentEffect.setColor4(name + suffix, color, alpha);
  35957. };
  35958. UniformBuffer.prototype._updateColor4ForUniform = function (name, color, alpha, suffix) {
  35959. if (suffix === void 0) { suffix = ""; }
  35960. color.toArray(UniformBuffer._tempBuffer);
  35961. UniformBuffer._tempBuffer[3] = alpha;
  35962. this.updateUniform(name, UniformBuffer._tempBuffer, 4);
  35963. };
  35964. /**
  35965. * Sets a sampler uniform on the effect.
  35966. * @param {string} name Name of the sampler.
  35967. * @param {Texture} texture
  35968. */
  35969. UniformBuffer.prototype.setTexture = function (name, texture) {
  35970. this._currentEffect.setTexture(name, texture);
  35971. };
  35972. /**
  35973. * Directly updates the value of the uniform in the cache AND on the GPU.
  35974. * @param {string} uniformName Name of the uniform, as used in the uniform block in the shader.
  35975. * @param {number[]|Float32Array} data Flattened data
  35976. */
  35977. UniformBuffer.prototype.updateUniformDirectly = function (uniformName, data) {
  35978. this.updateUniform(uniformName, data, data.length);
  35979. this.update();
  35980. };
  35981. /**
  35982. * Binds this uniform buffer to an effect.
  35983. * @param {Effect} effect
  35984. * @param {string} name Name of the uniform block in the shader.
  35985. */
  35986. UniformBuffer.prototype.bindToEffect = function (effect, name) {
  35987. this._currentEffect = effect;
  35988. if (this._noUBO || !this._buffer) {
  35989. return;
  35990. }
  35991. effect.bindUniformBuffer(this._buffer, name);
  35992. };
  35993. /**
  35994. * Disposes the uniform buffer.
  35995. */
  35996. UniformBuffer.prototype.dispose = function () {
  35997. if (this._noUBO) {
  35998. return;
  35999. }
  36000. var index = this._engine._uniformBuffers.indexOf(this);
  36001. if (index !== -1) {
  36002. this._engine._uniformBuffers.splice(index, 1);
  36003. }
  36004. if (!this._buffer) {
  36005. return;
  36006. }
  36007. if (this._engine._releaseBuffer(this._buffer)) {
  36008. this._buffer = null;
  36009. }
  36010. };
  36011. // Pool for avoiding memory leaks
  36012. UniformBuffer._MAX_UNIFORM_SIZE = 256;
  36013. UniformBuffer._tempBuffer = new Float32Array(UniformBuffer._MAX_UNIFORM_SIZE);
  36014. return UniformBuffer;
  36015. }());
  36016. BABYLON.UniformBuffer = UniformBuffer;
  36017. })(BABYLON || (BABYLON = {}));
  36018. //# sourceMappingURL=babylon.uniformBuffer.js.map
  36019. var BABYLON;
  36020. (function (BABYLON) {
  36021. /**
  36022. * This class contains the various kinds of data on every vertex of a mesh used in determining its shape and appearance
  36023. */
  36024. var VertexData = /** @class */ (function () {
  36025. function VertexData() {
  36026. }
  36027. /**
  36028. * Uses the passed data array to set the set the values for the specified kind of data
  36029. * @param data a linear array of floating numbers
  36030. * @param kind the type of data that is being set, eg positions, colors etc
  36031. */
  36032. VertexData.prototype.set = function (data, kind) {
  36033. switch (kind) {
  36034. case BABYLON.VertexBuffer.PositionKind:
  36035. this.positions = data;
  36036. break;
  36037. case BABYLON.VertexBuffer.NormalKind:
  36038. this.normals = data;
  36039. break;
  36040. case BABYLON.VertexBuffer.TangentKind:
  36041. this.tangents = data;
  36042. break;
  36043. case BABYLON.VertexBuffer.UVKind:
  36044. this.uvs = data;
  36045. break;
  36046. case BABYLON.VertexBuffer.UV2Kind:
  36047. this.uvs2 = data;
  36048. break;
  36049. case BABYLON.VertexBuffer.UV3Kind:
  36050. this.uvs3 = data;
  36051. break;
  36052. case BABYLON.VertexBuffer.UV4Kind:
  36053. this.uvs4 = data;
  36054. break;
  36055. case BABYLON.VertexBuffer.UV5Kind:
  36056. this.uvs5 = data;
  36057. break;
  36058. case BABYLON.VertexBuffer.UV6Kind:
  36059. this.uvs6 = data;
  36060. break;
  36061. case BABYLON.VertexBuffer.ColorKind:
  36062. this.colors = data;
  36063. break;
  36064. case BABYLON.VertexBuffer.MatricesIndicesKind:
  36065. this.matricesIndices = data;
  36066. break;
  36067. case BABYLON.VertexBuffer.MatricesWeightsKind:
  36068. this.matricesWeights = data;
  36069. break;
  36070. case BABYLON.VertexBuffer.MatricesIndicesExtraKind:
  36071. this.matricesIndicesExtra = data;
  36072. break;
  36073. case BABYLON.VertexBuffer.MatricesWeightsExtraKind:
  36074. this.matricesWeightsExtra = data;
  36075. break;
  36076. }
  36077. };
  36078. /**
  36079. * Associates the vertexData to the passed Mesh.
  36080. * Sets it as updatable or not (default `false`)
  36081. * @param mesh the mesh the vertexData is applied to
  36082. * @param updatable when used and having the value true allows new data to update the vertexData
  36083. * @returns the VertexData
  36084. */
  36085. VertexData.prototype.applyToMesh = function (mesh, updatable) {
  36086. this._applyTo(mesh, updatable);
  36087. return this;
  36088. };
  36089. /**
  36090. * Associates the vertexData to the passed Geometry.
  36091. * Sets it as updatable or not (default `false`)
  36092. * @param geometry the geometry the vertexData is applied to
  36093. * @param updatable when used and having the value true allows new data to update the vertexData
  36094. * @returns VertexData
  36095. */
  36096. VertexData.prototype.applyToGeometry = function (geometry, updatable) {
  36097. this._applyTo(geometry, updatable);
  36098. return this;
  36099. };
  36100. /**
  36101. * Updates the associated mesh
  36102. * @param mesh the mesh to be updated
  36103. * @param updateExtends when true the mesh BoundingInfo will be renewed when and if position kind is updated, optional with default false
  36104. * @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
  36105. * @returns VertexData
  36106. */
  36107. VertexData.prototype.updateMesh = function (mesh, updateExtends, makeItUnique) {
  36108. this._update(mesh);
  36109. return this;
  36110. };
  36111. /**
  36112. * Updates the associated geometry
  36113. * @param geometry the geometry to be updated
  36114. * @param updateExtends when true BoundingInfo will be renewed when and if position kind is updated, optional with default false
  36115. * @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
  36116. * @returns VertexData.
  36117. */
  36118. VertexData.prototype.updateGeometry = function (geometry, updateExtends, makeItUnique) {
  36119. this._update(geometry);
  36120. return this;
  36121. };
  36122. VertexData.prototype._applyTo = function (meshOrGeometry, updatable) {
  36123. if (updatable === void 0) { updatable = false; }
  36124. if (this.positions) {
  36125. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.PositionKind, this.positions, updatable);
  36126. }
  36127. if (this.normals) {
  36128. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.NormalKind, this.normals, updatable);
  36129. }
  36130. if (this.tangents) {
  36131. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.TangentKind, this.tangents, updatable);
  36132. }
  36133. if (this.uvs) {
  36134. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UVKind, this.uvs, updatable);
  36135. }
  36136. if (this.uvs2) {
  36137. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV2Kind, this.uvs2, updatable);
  36138. }
  36139. if (this.uvs3) {
  36140. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV3Kind, this.uvs3, updatable);
  36141. }
  36142. if (this.uvs4) {
  36143. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV4Kind, this.uvs4, updatable);
  36144. }
  36145. if (this.uvs5) {
  36146. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV5Kind, this.uvs5, updatable);
  36147. }
  36148. if (this.uvs6) {
  36149. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV6Kind, this.uvs6, updatable);
  36150. }
  36151. if (this.colors) {
  36152. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.ColorKind, this.colors, updatable);
  36153. }
  36154. if (this.matricesIndices) {
  36155. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, this.matricesIndices, updatable);
  36156. }
  36157. if (this.matricesWeights) {
  36158. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, this.matricesWeights, updatable);
  36159. }
  36160. if (this.matricesIndicesExtra) {
  36161. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, this.matricesIndicesExtra, updatable);
  36162. }
  36163. if (this.matricesWeightsExtra) {
  36164. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, this.matricesWeightsExtra, updatable);
  36165. }
  36166. if (this.indices) {
  36167. meshOrGeometry.setIndices(this.indices, null, updatable);
  36168. }
  36169. return this;
  36170. };
  36171. VertexData.prototype._update = function (meshOrGeometry, updateExtends, makeItUnique) {
  36172. if (this.positions) {
  36173. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.PositionKind, this.positions, updateExtends, makeItUnique);
  36174. }
  36175. if (this.normals) {
  36176. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.NormalKind, this.normals, updateExtends, makeItUnique);
  36177. }
  36178. if (this.tangents) {
  36179. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.TangentKind, this.tangents, updateExtends, makeItUnique);
  36180. }
  36181. if (this.uvs) {
  36182. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UVKind, this.uvs, updateExtends, makeItUnique);
  36183. }
  36184. if (this.uvs2) {
  36185. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV2Kind, this.uvs2, updateExtends, makeItUnique);
  36186. }
  36187. if (this.uvs3) {
  36188. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV3Kind, this.uvs3, updateExtends, makeItUnique);
  36189. }
  36190. if (this.uvs4) {
  36191. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV4Kind, this.uvs4, updateExtends, makeItUnique);
  36192. }
  36193. if (this.uvs5) {
  36194. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV5Kind, this.uvs5, updateExtends, makeItUnique);
  36195. }
  36196. if (this.uvs6) {
  36197. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV6Kind, this.uvs6, updateExtends, makeItUnique);
  36198. }
  36199. if (this.colors) {
  36200. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.ColorKind, this.colors, updateExtends, makeItUnique);
  36201. }
  36202. if (this.matricesIndices) {
  36203. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, this.matricesIndices, updateExtends, makeItUnique);
  36204. }
  36205. if (this.matricesWeights) {
  36206. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, this.matricesWeights, updateExtends, makeItUnique);
  36207. }
  36208. if (this.matricesIndicesExtra) {
  36209. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, this.matricesIndicesExtra, updateExtends, makeItUnique);
  36210. }
  36211. if (this.matricesWeightsExtra) {
  36212. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, this.matricesWeightsExtra, updateExtends, makeItUnique);
  36213. }
  36214. if (this.indices) {
  36215. meshOrGeometry.setIndices(this.indices, null);
  36216. }
  36217. return this;
  36218. };
  36219. /**
  36220. * Transforms each position and each normal of the vertexData according to the passed Matrix
  36221. * @param matrix the transforming matrix
  36222. * @returns the VertexData
  36223. */
  36224. VertexData.prototype.transform = function (matrix) {
  36225. var transformed = BABYLON.Vector3.Zero();
  36226. var index;
  36227. if (this.positions) {
  36228. var position = BABYLON.Vector3.Zero();
  36229. for (index = 0; index < this.positions.length; index += 3) {
  36230. BABYLON.Vector3.FromArrayToRef(this.positions, index, position);
  36231. BABYLON.Vector3.TransformCoordinatesToRef(position, matrix, transformed);
  36232. this.positions[index] = transformed.x;
  36233. this.positions[index + 1] = transformed.y;
  36234. this.positions[index + 2] = transformed.z;
  36235. }
  36236. }
  36237. if (this.normals) {
  36238. var normal = BABYLON.Vector3.Zero();
  36239. for (index = 0; index < this.normals.length; index += 3) {
  36240. BABYLON.Vector3.FromArrayToRef(this.normals, index, normal);
  36241. BABYLON.Vector3.TransformNormalToRef(normal, matrix, transformed);
  36242. this.normals[index] = transformed.x;
  36243. this.normals[index + 1] = transformed.y;
  36244. this.normals[index + 2] = transformed.z;
  36245. }
  36246. }
  36247. if (this.tangents) {
  36248. var tangent = BABYLON.Vector4.Zero();
  36249. var tangentTransformed = BABYLON.Vector4.Zero();
  36250. for (index = 0; index < this.tangents.length; index += 4) {
  36251. BABYLON.Vector4.FromArrayToRef(this.tangents, index, tangent);
  36252. BABYLON.Vector4.TransformNormalToRef(tangent, matrix, tangentTransformed);
  36253. this.tangents[index] = tangentTransformed.x;
  36254. this.tangents[index + 1] = tangentTransformed.y;
  36255. this.tangents[index + 2] = tangentTransformed.z;
  36256. this.tangents[index + 3] = tangentTransformed.w;
  36257. }
  36258. }
  36259. return this;
  36260. };
  36261. /**
  36262. * Merges the passed VertexData into the current one
  36263. * @param other the VertexData to be merged into the current one
  36264. * @returns the modified VertexData
  36265. */
  36266. VertexData.prototype.merge = function (other) {
  36267. this._validate();
  36268. other._validate();
  36269. if (!this.normals !== !other.normals ||
  36270. !this.tangents !== !other.tangents ||
  36271. !this.uvs !== !other.uvs ||
  36272. !this.uvs2 !== !other.uvs2 ||
  36273. !this.uvs3 !== !other.uvs3 ||
  36274. !this.uvs4 !== !other.uvs4 ||
  36275. !this.uvs5 !== !other.uvs5 ||
  36276. !this.uvs6 !== !other.uvs6 ||
  36277. !this.colors !== !other.colors ||
  36278. !this.matricesIndices !== !other.matricesIndices ||
  36279. !this.matricesWeights !== !other.matricesWeights ||
  36280. !this.matricesIndicesExtra !== !other.matricesIndicesExtra ||
  36281. !this.matricesWeightsExtra !== !other.matricesWeightsExtra) {
  36282. throw new Error("Cannot merge vertex data that do not have the same set of attributes");
  36283. }
  36284. if (other.indices) {
  36285. if (!this.indices) {
  36286. this.indices = [];
  36287. }
  36288. var offset = this.positions ? this.positions.length / 3 : 0;
  36289. for (var index = 0; index < other.indices.length; index++) {
  36290. //TODO check type - if Int32Array | Uint32Array | Uint16Array!
  36291. this.indices.push(other.indices[index] + offset);
  36292. }
  36293. }
  36294. this.positions = this._mergeElement(this.positions, other.positions);
  36295. this.normals = this._mergeElement(this.normals, other.normals);
  36296. this.tangents = this._mergeElement(this.tangents, other.tangents);
  36297. this.uvs = this._mergeElement(this.uvs, other.uvs);
  36298. this.uvs2 = this._mergeElement(this.uvs2, other.uvs2);
  36299. this.uvs3 = this._mergeElement(this.uvs3, other.uvs3);
  36300. this.uvs4 = this._mergeElement(this.uvs4, other.uvs4);
  36301. this.uvs5 = this._mergeElement(this.uvs5, other.uvs5);
  36302. this.uvs6 = this._mergeElement(this.uvs6, other.uvs6);
  36303. this.colors = this._mergeElement(this.colors, other.colors);
  36304. this.matricesIndices = this._mergeElement(this.matricesIndices, other.matricesIndices);
  36305. this.matricesWeights = this._mergeElement(this.matricesWeights, other.matricesWeights);
  36306. this.matricesIndicesExtra = this._mergeElement(this.matricesIndicesExtra, other.matricesIndicesExtra);
  36307. this.matricesWeightsExtra = this._mergeElement(this.matricesWeightsExtra, other.matricesWeightsExtra);
  36308. return this;
  36309. };
  36310. VertexData.prototype._mergeElement = function (source, other) {
  36311. if (!source) {
  36312. return other;
  36313. }
  36314. if (!other) {
  36315. return source;
  36316. }
  36317. var len = other.length + source.length;
  36318. var isSrcTypedArray = source instanceof Float32Array;
  36319. var isOthTypedArray = other instanceof Float32Array;
  36320. // use non-loop method when the source is Float32Array
  36321. if (isSrcTypedArray) {
  36322. var ret32 = new Float32Array(len);
  36323. ret32.set(source);
  36324. ret32.set(other, source.length);
  36325. return ret32;
  36326. // source is number[], when other is also use concat
  36327. }
  36328. else if (!isOthTypedArray) {
  36329. return source.concat(other);
  36330. // source is a number[], but other is a Float32Array, loop required
  36331. }
  36332. else {
  36333. var ret = source.slice(0); // copy source to a separate array
  36334. for (var i = 0, len = other.length; i < len; i++) {
  36335. ret.push(other[i]);
  36336. }
  36337. return ret;
  36338. }
  36339. };
  36340. VertexData.prototype._validate = function () {
  36341. if (!this.positions) {
  36342. throw new Error("Positions are required");
  36343. }
  36344. var getElementCount = function (kind, values) {
  36345. var stride = BABYLON.VertexBuffer.DeduceStride(kind);
  36346. if ((values.length % stride) !== 0) {
  36347. throw new Error("The " + kind + "s array count must be a multiple of " + stride);
  36348. }
  36349. return values.length / stride;
  36350. };
  36351. var positionsElementCount = getElementCount(BABYLON.VertexBuffer.PositionKind, this.positions);
  36352. var validateElementCount = function (kind, values) {
  36353. var elementCount = getElementCount(kind, values);
  36354. if (elementCount !== positionsElementCount) {
  36355. throw new Error("The " + kind + "s element count (" + elementCount + ") does not match the positions count (" + positionsElementCount + ")");
  36356. }
  36357. };
  36358. if (this.normals)
  36359. validateElementCount(BABYLON.VertexBuffer.NormalKind, this.normals);
  36360. if (this.tangents)
  36361. validateElementCount(BABYLON.VertexBuffer.TangentKind, this.tangents);
  36362. if (this.uvs)
  36363. validateElementCount(BABYLON.VertexBuffer.UVKind, this.uvs);
  36364. if (this.uvs2)
  36365. validateElementCount(BABYLON.VertexBuffer.UV2Kind, this.uvs2);
  36366. if (this.uvs3)
  36367. validateElementCount(BABYLON.VertexBuffer.UV3Kind, this.uvs3);
  36368. if (this.uvs4)
  36369. validateElementCount(BABYLON.VertexBuffer.UV4Kind, this.uvs4);
  36370. if (this.uvs5)
  36371. validateElementCount(BABYLON.VertexBuffer.UV5Kind, this.uvs5);
  36372. if (this.uvs6)
  36373. validateElementCount(BABYLON.VertexBuffer.UV6Kind, this.uvs6);
  36374. if (this.colors)
  36375. validateElementCount(BABYLON.VertexBuffer.ColorKind, this.colors);
  36376. if (this.matricesIndices)
  36377. validateElementCount(BABYLON.VertexBuffer.MatricesIndicesKind, this.matricesIndices);
  36378. if (this.matricesWeights)
  36379. validateElementCount(BABYLON.VertexBuffer.MatricesWeightsKind, this.matricesWeights);
  36380. if (this.matricesIndicesExtra)
  36381. validateElementCount(BABYLON.VertexBuffer.MatricesIndicesExtraKind, this.matricesIndicesExtra);
  36382. if (this.matricesWeightsExtra)
  36383. validateElementCount(BABYLON.VertexBuffer.MatricesWeightsExtraKind, this.matricesWeightsExtra);
  36384. };
  36385. /**
  36386. * Serializes the VertexData
  36387. * @returns a serialized object
  36388. */
  36389. VertexData.prototype.serialize = function () {
  36390. var serializationObject = this.serialize();
  36391. if (this.positions) {
  36392. serializationObject.positions = this.positions;
  36393. }
  36394. if (this.normals) {
  36395. serializationObject.normals = this.normals;
  36396. }
  36397. if (this.tangents) {
  36398. serializationObject.tangents = this.tangents;
  36399. }
  36400. if (this.uvs) {
  36401. serializationObject.uvs = this.uvs;
  36402. }
  36403. if (this.uvs2) {
  36404. serializationObject.uvs2 = this.uvs2;
  36405. }
  36406. if (this.uvs3) {
  36407. serializationObject.uvs3 = this.uvs3;
  36408. }
  36409. if (this.uvs4) {
  36410. serializationObject.uvs4 = this.uvs4;
  36411. }
  36412. if (this.uvs5) {
  36413. serializationObject.uvs5 = this.uvs5;
  36414. }
  36415. if (this.uvs6) {
  36416. serializationObject.uvs6 = this.uvs6;
  36417. }
  36418. if (this.colors) {
  36419. serializationObject.colors = this.colors;
  36420. }
  36421. if (this.matricesIndices) {
  36422. serializationObject.matricesIndices = this.matricesIndices;
  36423. serializationObject.matricesIndices._isExpanded = true;
  36424. }
  36425. if (this.matricesWeights) {
  36426. serializationObject.matricesWeights = this.matricesWeights;
  36427. }
  36428. if (this.matricesIndicesExtra) {
  36429. serializationObject.matricesIndicesExtra = this.matricesIndicesExtra;
  36430. serializationObject.matricesIndicesExtra._isExpanded = true;
  36431. }
  36432. if (this.matricesWeightsExtra) {
  36433. serializationObject.matricesWeightsExtra = this.matricesWeightsExtra;
  36434. }
  36435. serializationObject.indices = this.indices;
  36436. return serializationObject;
  36437. };
  36438. // Statics
  36439. /**
  36440. * Extracts the vertexData from a mesh
  36441. * @param mesh the mesh from which to extract the VertexData
  36442. * @param copyWhenShared defines if the VertexData must be cloned when shared between multiple meshes, optional, default false
  36443. * @param forceCopy indicating that the VertexData must be cloned, optional, default false
  36444. * @returns the object VertexData associated to the passed mesh
  36445. */
  36446. VertexData.ExtractFromMesh = function (mesh, copyWhenShared, forceCopy) {
  36447. return VertexData._ExtractFrom(mesh, copyWhenShared, forceCopy);
  36448. };
  36449. /**
  36450. * Extracts the vertexData from the geometry
  36451. * @param geometry the geometry from which to extract the VertexData
  36452. * @param copyWhenShared defines if the VertexData must be cloned when the geometrty is shared between multiple meshes, optional, default false
  36453. * @param forceCopy indicating that the VertexData must be cloned, optional, default false
  36454. * @returns the object VertexData associated to the passed mesh
  36455. */
  36456. VertexData.ExtractFromGeometry = function (geometry, copyWhenShared, forceCopy) {
  36457. return VertexData._ExtractFrom(geometry, copyWhenShared, forceCopy);
  36458. };
  36459. VertexData._ExtractFrom = function (meshOrGeometry, copyWhenShared, forceCopy) {
  36460. var result = new VertexData();
  36461. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  36462. result.positions = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.PositionKind, copyWhenShared, forceCopy);
  36463. }
  36464. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  36465. result.normals = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.NormalKind, copyWhenShared, forceCopy);
  36466. }
  36467. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind)) {
  36468. result.tangents = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.TangentKind, copyWhenShared, forceCopy);
  36469. }
  36470. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  36471. result.uvs = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UVKind, copyWhenShared, forceCopy);
  36472. }
  36473. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  36474. result.uvs2 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV2Kind, copyWhenShared, forceCopy);
  36475. }
  36476. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV3Kind)) {
  36477. result.uvs3 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV3Kind, copyWhenShared, forceCopy);
  36478. }
  36479. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV4Kind)) {
  36480. result.uvs4 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV4Kind, copyWhenShared, forceCopy);
  36481. }
  36482. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV5Kind)) {
  36483. result.uvs5 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV5Kind, copyWhenShared, forceCopy);
  36484. }
  36485. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV6Kind)) {
  36486. result.uvs6 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV6Kind, copyWhenShared, forceCopy);
  36487. }
  36488. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  36489. result.colors = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.ColorKind, copyWhenShared, forceCopy);
  36490. }
  36491. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  36492. result.matricesIndices = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, copyWhenShared, forceCopy);
  36493. }
  36494. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  36495. result.matricesWeights = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, copyWhenShared, forceCopy);
  36496. }
  36497. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesExtraKind)) {
  36498. result.matricesIndicesExtra = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, copyWhenShared, forceCopy);
  36499. }
  36500. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsExtraKind)) {
  36501. result.matricesWeightsExtra = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, copyWhenShared, forceCopy);
  36502. }
  36503. result.indices = meshOrGeometry.getIndices(copyWhenShared);
  36504. return result;
  36505. };
  36506. /**
  36507. * Creates the VertexData for a Ribbon
  36508. * @param options an object used to set the following optional parameters for the ribbon, required but can be empty
  36509. * * pathArray array of paths, each of which an array of successive Vector3
  36510. * * closeArray creates a seam between the first and the last paths of the pathArray, optional, default false
  36511. * * closePath creates a seam between the first and the last points of each path of the path array, optional, default false
  36512. * * 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
  36513. * * sideOrientation optional and takes the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  36514. * * 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)
  36515. * * 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)
  36516. * * invertUV swaps in the U and V coordinates when applying a texture, optional, default false
  36517. * * uvs a linear array, of length 2 * number of vertices, of custom UV values, optional
  36518. * * colors a linear array, of length 4 * number of vertices, of custom color values, optional
  36519. * @returns the VertexData of the ribbon
  36520. */
  36521. VertexData.CreateRibbon = function (options) {
  36522. var pathArray = options.pathArray;
  36523. var closeArray = options.closeArray || false;
  36524. var closePath = options.closePath || false;
  36525. var invertUV = options.invertUV || false;
  36526. var defaultOffset = Math.floor(pathArray[0].length / 2);
  36527. var offset = options.offset || defaultOffset;
  36528. offset = offset > defaultOffset ? defaultOffset : Math.floor(offset); // offset max allowed : defaultOffset
  36529. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  36530. var customUV = options.uvs;
  36531. var customColors = options.colors;
  36532. var positions = [];
  36533. var indices = [];
  36534. var normals = [];
  36535. var uvs = [];
  36536. var us = []; // us[path_id] = [uDist1, uDist2, uDist3 ... ] distances between points on path path_id
  36537. var vs = []; // vs[i] = [vDist1, vDist2, vDist3, ... ] distances between points i of consecutives paths from pathArray
  36538. var uTotalDistance = []; // uTotalDistance[p] : total distance of path p
  36539. var vTotalDistance = []; // vTotalDistance[i] : total distance between points i of first and last path from pathArray
  36540. var minlg; // minimal length among all paths from pathArray
  36541. var lg = []; // array of path lengths : nb of vertex per path
  36542. var idx = []; // array of path indexes : index of each path (first vertex) in the total vertex number
  36543. var p; // path iterator
  36544. var i; // point iterator
  36545. var j; // point iterator
  36546. // if single path in pathArray
  36547. if (pathArray.length < 2) {
  36548. var ar1 = [];
  36549. var ar2 = [];
  36550. for (i = 0; i < pathArray[0].length - offset; i++) {
  36551. ar1.push(pathArray[0][i]);
  36552. ar2.push(pathArray[0][i + offset]);
  36553. }
  36554. pathArray = [ar1, ar2];
  36555. }
  36556. // positions and horizontal distances (u)
  36557. var idc = 0;
  36558. var closePathCorr = (closePath) ? 1 : 0; // the final index will be +1 if closePath
  36559. var path;
  36560. var l;
  36561. minlg = pathArray[0].length;
  36562. var vectlg;
  36563. var dist;
  36564. for (p = 0; p < pathArray.length; p++) {
  36565. uTotalDistance[p] = 0;
  36566. us[p] = [0];
  36567. path = pathArray[p];
  36568. l = path.length;
  36569. minlg = (minlg < l) ? minlg : l;
  36570. j = 0;
  36571. while (j < l) {
  36572. positions.push(path[j].x, path[j].y, path[j].z);
  36573. if (j > 0) {
  36574. vectlg = path[j].subtract(path[j - 1]).length();
  36575. dist = vectlg + uTotalDistance[p];
  36576. us[p].push(dist);
  36577. uTotalDistance[p] = dist;
  36578. }
  36579. j++;
  36580. }
  36581. if (closePath) { // an extra hidden vertex is added in the "positions" array
  36582. j--;
  36583. positions.push(path[0].x, path[0].y, path[0].z);
  36584. vectlg = path[j].subtract(path[0]).length();
  36585. dist = vectlg + uTotalDistance[p];
  36586. us[p].push(dist);
  36587. uTotalDistance[p] = dist;
  36588. }
  36589. lg[p] = l + closePathCorr;
  36590. idx[p] = idc;
  36591. idc += (l + closePathCorr);
  36592. }
  36593. // vertical distances (v)
  36594. var path1;
  36595. var path2;
  36596. var vertex1 = null;
  36597. var vertex2 = null;
  36598. for (i = 0; i < minlg + closePathCorr; i++) {
  36599. vTotalDistance[i] = 0;
  36600. vs[i] = [0];
  36601. for (p = 0; p < pathArray.length - 1; p++) {
  36602. path1 = pathArray[p];
  36603. path2 = pathArray[p + 1];
  36604. if (i === minlg) { // closePath
  36605. vertex1 = path1[0];
  36606. vertex2 = path2[0];
  36607. }
  36608. else {
  36609. vertex1 = path1[i];
  36610. vertex2 = path2[i];
  36611. }
  36612. vectlg = vertex2.subtract(vertex1).length();
  36613. dist = vectlg + vTotalDistance[i];
  36614. vs[i].push(dist);
  36615. vTotalDistance[i] = dist;
  36616. }
  36617. if (closeArray && vertex2 && vertex1) {
  36618. path1 = pathArray[p];
  36619. path2 = pathArray[0];
  36620. if (i === minlg) { // closePath
  36621. vertex2 = path2[0];
  36622. }
  36623. vectlg = vertex2.subtract(vertex1).length();
  36624. dist = vectlg + vTotalDistance[i];
  36625. vTotalDistance[i] = dist;
  36626. }
  36627. }
  36628. // uvs
  36629. var u;
  36630. var v;
  36631. if (customUV) {
  36632. for (p = 0; p < customUV.length; p++) {
  36633. uvs.push(customUV[p].x, customUV[p].y);
  36634. }
  36635. }
  36636. else {
  36637. for (p = 0; p < pathArray.length; p++) {
  36638. for (i = 0; i < minlg + closePathCorr; i++) {
  36639. u = (uTotalDistance[p] != 0.0) ? us[p][i] / uTotalDistance[p] : 0.0;
  36640. v = (vTotalDistance[i] != 0.0) ? vs[i][p] / vTotalDistance[i] : 0.0;
  36641. if (invertUV) {
  36642. uvs.push(v, u);
  36643. }
  36644. else {
  36645. uvs.push(u, v);
  36646. }
  36647. }
  36648. }
  36649. }
  36650. // indices
  36651. p = 0; // path index
  36652. var pi = 0; // positions array index
  36653. var l1 = lg[p] - 1; // path1 length
  36654. var l2 = lg[p + 1] - 1; // path2 length
  36655. var min = (l1 < l2) ? l1 : l2; // current path stop index
  36656. var shft = idx[1] - idx[0]; // shift
  36657. var path1nb = closeArray ? lg.length : lg.length - 1; // number of path1 to iterate on
  36658. while (pi <= min && p < path1nb) { // stay under min and don't go over next to last path
  36659. // 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
  36660. indices.push(pi, pi + shft, pi + 1);
  36661. indices.push(pi + shft + 1, pi + 1, pi + shft);
  36662. pi += 1;
  36663. if (pi === min) { // if end of one of two consecutive paths reached, go to next existing path
  36664. p++;
  36665. if (p === lg.length - 1) { // last path of pathArray reached <=> closeArray == true
  36666. shft = idx[0] - idx[p];
  36667. l1 = lg[p] - 1;
  36668. l2 = lg[0] - 1;
  36669. }
  36670. else {
  36671. shft = idx[p + 1] - idx[p];
  36672. l1 = lg[p] - 1;
  36673. l2 = lg[p + 1] - 1;
  36674. }
  36675. pi = idx[p];
  36676. min = (l1 < l2) ? l1 + pi : l2 + pi;
  36677. }
  36678. }
  36679. // normals
  36680. VertexData.ComputeNormals(positions, indices, normals);
  36681. if (closePath) { // update both the first and last vertex normals to their average value
  36682. var indexFirst = 0;
  36683. var indexLast = 0;
  36684. for (p = 0; p < pathArray.length; p++) {
  36685. indexFirst = idx[p] * 3;
  36686. if (p + 1 < pathArray.length) {
  36687. indexLast = (idx[p + 1] - 1) * 3;
  36688. }
  36689. else {
  36690. indexLast = normals.length - 3;
  36691. }
  36692. normals[indexFirst] = (normals[indexFirst] + normals[indexLast]) * 0.5;
  36693. normals[indexFirst + 1] = (normals[indexFirst + 1] + normals[indexLast + 1]) * 0.5;
  36694. normals[indexFirst + 2] = (normals[indexFirst + 2] + normals[indexLast + 2]) * 0.5;
  36695. normals[indexLast] = normals[indexFirst];
  36696. normals[indexLast + 1] = normals[indexFirst + 1];
  36697. normals[indexLast + 2] = normals[indexFirst + 2];
  36698. }
  36699. }
  36700. // sides
  36701. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  36702. // Colors
  36703. var colors = null;
  36704. if (customColors) {
  36705. colors = new Float32Array(customColors.length * 4);
  36706. for (var c = 0; c < customColors.length; c++) {
  36707. colors[c * 4] = customColors[c].r;
  36708. colors[c * 4 + 1] = customColors[c].g;
  36709. colors[c * 4 + 2] = customColors[c].b;
  36710. colors[c * 4 + 3] = customColors[c].a;
  36711. }
  36712. }
  36713. // Result
  36714. var vertexData = new VertexData();
  36715. var positions32 = new Float32Array(positions);
  36716. var normals32 = new Float32Array(normals);
  36717. var uvs32 = new Float32Array(uvs);
  36718. vertexData.indices = indices;
  36719. vertexData.positions = positions32;
  36720. vertexData.normals = normals32;
  36721. vertexData.uvs = uvs32;
  36722. if (colors) {
  36723. vertexData.set(colors, BABYLON.VertexBuffer.ColorKind);
  36724. }
  36725. if (closePath) {
  36726. vertexData._idx = idx;
  36727. }
  36728. return vertexData;
  36729. };
  36730. /**
  36731. * Creates the VertexData for a box
  36732. * @param options an object used to set the following optional parameters for the box, required but can be empty
  36733. * * size sets the width, height and depth of the box to the value of size, optional default 1
  36734. * * width sets the width (x direction) of the box, overwrites the width set by size, optional, default size
  36735. * * height sets the height (y direction) of the box, overwrites the height set by size, optional, default size
  36736. * * depth sets the depth (z direction) of the box, overwrites the depth set by size, optional, default size
  36737. * * faceUV an array of 6 Vector4 elements used to set different images to each box side
  36738. * * faceColors an array of 6 Color3 elements used to set different colors to each box side
  36739. * * sideOrientation optional and takes the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  36740. * * 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)
  36741. * * 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)
  36742. * @returns the VertexData of the box
  36743. */
  36744. VertexData.CreateBox = function (options) {
  36745. var normalsSource = [
  36746. new BABYLON.Vector3(0, 0, 1),
  36747. new BABYLON.Vector3(0, 0, -1),
  36748. new BABYLON.Vector3(1, 0, 0),
  36749. new BABYLON.Vector3(-1, 0, 0),
  36750. new BABYLON.Vector3(0, 1, 0),
  36751. new BABYLON.Vector3(0, -1, 0)
  36752. ];
  36753. var indices = [];
  36754. var positions = [];
  36755. var normals = [];
  36756. var uvs = [];
  36757. var width = options.width || options.size || 1;
  36758. var height = options.height || options.size || 1;
  36759. var depth = options.depth || options.size || 1;
  36760. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  36761. var faceUV = options.faceUV || new Array(6);
  36762. var faceColors = options.faceColors;
  36763. var colors = [];
  36764. // default face colors and UV if undefined
  36765. for (var f = 0; f < 6; f++) {
  36766. if (faceUV[f] === undefined) {
  36767. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  36768. }
  36769. if (faceColors && faceColors[f] === undefined) {
  36770. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  36771. }
  36772. }
  36773. var scaleVector = new BABYLON.Vector3(width / 2, height / 2, depth / 2);
  36774. // Create each face in turn.
  36775. for (var index = 0; index < normalsSource.length; index++) {
  36776. var normal = normalsSource[index];
  36777. // Get two vectors perpendicular to the face normal and to each other.
  36778. var side1 = new BABYLON.Vector3(normal.y, normal.z, normal.x);
  36779. var side2 = BABYLON.Vector3.Cross(normal, side1);
  36780. // Six indices (two triangles) per face.
  36781. var verticesLength = positions.length / 3;
  36782. indices.push(verticesLength);
  36783. indices.push(verticesLength + 1);
  36784. indices.push(verticesLength + 2);
  36785. indices.push(verticesLength);
  36786. indices.push(verticesLength + 2);
  36787. indices.push(verticesLength + 3);
  36788. // Four vertices per face.
  36789. var vertex = normal.subtract(side1).subtract(side2).multiply(scaleVector);
  36790. positions.push(vertex.x, vertex.y, vertex.z);
  36791. normals.push(normal.x, normal.y, normal.z);
  36792. uvs.push(faceUV[index].z, faceUV[index].w);
  36793. if (faceColors) {
  36794. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  36795. }
  36796. vertex = normal.subtract(side1).add(side2).multiply(scaleVector);
  36797. positions.push(vertex.x, vertex.y, vertex.z);
  36798. normals.push(normal.x, normal.y, normal.z);
  36799. uvs.push(faceUV[index].x, faceUV[index].w);
  36800. if (faceColors) {
  36801. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  36802. }
  36803. vertex = normal.add(side1).add(side2).multiply(scaleVector);
  36804. positions.push(vertex.x, vertex.y, vertex.z);
  36805. normals.push(normal.x, normal.y, normal.z);
  36806. uvs.push(faceUV[index].x, faceUV[index].y);
  36807. if (faceColors) {
  36808. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  36809. }
  36810. vertex = normal.add(side1).subtract(side2).multiply(scaleVector);
  36811. positions.push(vertex.x, vertex.y, vertex.z);
  36812. normals.push(normal.x, normal.y, normal.z);
  36813. uvs.push(faceUV[index].z, faceUV[index].y);
  36814. if (faceColors) {
  36815. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  36816. }
  36817. }
  36818. // sides
  36819. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  36820. // Result
  36821. var vertexData = new VertexData();
  36822. vertexData.indices = indices;
  36823. vertexData.positions = positions;
  36824. vertexData.normals = normals;
  36825. vertexData.uvs = uvs;
  36826. if (faceColors) {
  36827. var totalColors = (sideOrientation === BABYLON.Mesh.DOUBLESIDE) ? colors.concat(colors) : colors;
  36828. vertexData.colors = totalColors;
  36829. }
  36830. return vertexData;
  36831. };
  36832. /**
  36833. * Creates the VertexData for an ellipsoid, defaults to a sphere
  36834. * @param options an object used to set the following optional parameters for the box, required but can be empty
  36835. * * segments sets the number of horizontal strips optional, default 32
  36836. * * diameter sets the axes dimensions, diameterX, diameterY and diameterZ to the value of diameter, optional default 1
  36837. * * diameterX sets the diameterX (x direction) of the ellipsoid, overwrites the diameterX set by diameter, optional, default diameter
  36838. * * diameterY sets the diameterY (y direction) of the ellipsoid, overwrites the diameterY set by diameter, optional, default diameter
  36839. * * diameterZ sets the diameterZ (z direction) of the ellipsoid, overwrites the diameterZ set by diameter, optional, default diameter
  36840. * * 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
  36841. * * 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
  36842. * * sideOrientation optional and takes the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  36843. * * 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)
  36844. * * 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)
  36845. * @returns the VertexData of the ellipsoid
  36846. */
  36847. VertexData.CreateSphere = function (options) {
  36848. var segments = options.segments || 32;
  36849. var diameterX = options.diameterX || options.diameter || 1;
  36850. var diameterY = options.diameterY || options.diameter || 1;
  36851. var diameterZ = options.diameterZ || options.diameter || 1;
  36852. var arc = options.arc && (options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc || 1.0;
  36853. var slice = options.slice && (options.slice <= 0) ? 1.0 : options.slice || 1.0;
  36854. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  36855. var radius = new BABYLON.Vector3(diameterX / 2, diameterY / 2, diameterZ / 2);
  36856. var totalZRotationSteps = 2 + segments;
  36857. var totalYRotationSteps = 2 * totalZRotationSteps;
  36858. var indices = [];
  36859. var positions = [];
  36860. var normals = [];
  36861. var uvs = [];
  36862. for (var zRotationStep = 0; zRotationStep <= totalZRotationSteps; zRotationStep++) {
  36863. var normalizedZ = zRotationStep / totalZRotationSteps;
  36864. var angleZ = normalizedZ * Math.PI * slice;
  36865. for (var yRotationStep = 0; yRotationStep <= totalYRotationSteps; yRotationStep++) {
  36866. var normalizedY = yRotationStep / totalYRotationSteps;
  36867. var angleY = normalizedY * Math.PI * 2 * arc;
  36868. var rotationZ = BABYLON.Matrix.RotationZ(-angleZ);
  36869. var rotationY = BABYLON.Matrix.RotationY(angleY);
  36870. var afterRotZ = BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.Up(), rotationZ);
  36871. var complete = BABYLON.Vector3.TransformCoordinates(afterRotZ, rotationY);
  36872. var vertex = complete.multiply(radius);
  36873. var normal = complete.divide(radius).normalize();
  36874. positions.push(vertex.x, vertex.y, vertex.z);
  36875. normals.push(normal.x, normal.y, normal.z);
  36876. uvs.push(normalizedY, normalizedZ);
  36877. }
  36878. if (zRotationStep > 0) {
  36879. var verticesCount = positions.length / 3;
  36880. for (var firstIndex = verticesCount - 2 * (totalYRotationSteps + 1); (firstIndex + totalYRotationSteps + 2) < verticesCount; firstIndex++) {
  36881. indices.push((firstIndex));
  36882. indices.push((firstIndex + 1));
  36883. indices.push(firstIndex + totalYRotationSteps + 1);
  36884. indices.push((firstIndex + totalYRotationSteps + 1));
  36885. indices.push((firstIndex + 1));
  36886. indices.push((firstIndex + totalYRotationSteps + 2));
  36887. }
  36888. }
  36889. }
  36890. // Sides
  36891. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  36892. // Result
  36893. var vertexData = new VertexData();
  36894. vertexData.indices = indices;
  36895. vertexData.positions = positions;
  36896. vertexData.normals = normals;
  36897. vertexData.uvs = uvs;
  36898. return vertexData;
  36899. };
  36900. /**
  36901. * Creates the VertexData for a cylinder, cone or prism
  36902. * @param options an object used to set the following optional parameters for the box, required but can be empty
  36903. * * height sets the height (y direction) of the cylinder, optional, default 2
  36904. * * diameterTop sets the diameter of the top of the cone, overwrites diameter, optional, default diameter
  36905. * * diameterBottom sets the diameter of the bottom of the cone, overwrites diameter, optional, default diameter
  36906. * * diameter sets the diameter of the top and bottom of the cone, optional default 1
  36907. * * tessellation the number of prism sides, 3 for a triangular prism, optional, default 24
  36908. * * subdivisions` the number of rings along the cylinder height, optional, default 1
  36909. * * 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
  36910. * * faceColors an array of Color3 elements used to set different colors to the top, rings and bottom respectively
  36911. * * faceUV an array of Vector4 elements used to set different images to the top, rings and bottom respectively
  36912. * * hasRings when true makes each subdivision independantly treated as a face for faceUV and faceColors, optional, default false
  36913. * * enclose when true closes an open cylinder by adding extra flat faces between the height axis and vertical edges, think cut cake
  36914. * * sideOrientation optional and takes the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  36915. * * 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)
  36916. * * 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)
  36917. * @returns the VertexData of the cylinder, cone or prism
  36918. */
  36919. VertexData.CreateCylinder = function (options) {
  36920. var height = options.height || 2;
  36921. var diameterTop = (options.diameterTop === 0) ? 0 : options.diameterTop || options.diameter || 1;
  36922. var diameterBottom = (options.diameterBottom === 0) ? 0 : options.diameterBottom || options.diameter || 1;
  36923. var tessellation = options.tessellation || 24;
  36924. var subdivisions = options.subdivisions || 1;
  36925. var hasRings = options.hasRings ? true : false;
  36926. var enclose = options.enclose ? true : false;
  36927. var arc = options.arc && (options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc || 1.0;
  36928. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  36929. var faceUV = options.faceUV || new Array(3);
  36930. var faceColors = options.faceColors;
  36931. // default face colors and UV if undefined
  36932. var quadNb = (arc !== 1 && enclose) ? 2 : 0;
  36933. var ringNb = (hasRings) ? subdivisions : 1;
  36934. var surfaceNb = 2 + (1 + quadNb) * ringNb;
  36935. var f;
  36936. for (f = 0; f < surfaceNb; f++) {
  36937. if (faceColors && faceColors[f] === undefined) {
  36938. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  36939. }
  36940. }
  36941. for (f = 0; f < surfaceNb; f++) {
  36942. if (faceUV && faceUV[f] === undefined) {
  36943. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  36944. }
  36945. }
  36946. var indices = new Array();
  36947. var positions = new Array();
  36948. var normals = new Array();
  36949. var uvs = new Array();
  36950. var colors = new Array();
  36951. var angle_step = Math.PI * 2 * arc / tessellation;
  36952. var angle;
  36953. var h;
  36954. var radius;
  36955. var tan = (diameterBottom - diameterTop) / 2 / height;
  36956. var ringVertex = BABYLON.Vector3.Zero();
  36957. var ringNormal = BABYLON.Vector3.Zero();
  36958. var ringFirstVertex = BABYLON.Vector3.Zero();
  36959. var ringFirstNormal = BABYLON.Vector3.Zero();
  36960. var quadNormal = BABYLON.Vector3.Zero();
  36961. var Y = BABYLON.Axis.Y;
  36962. // positions, normals, uvs
  36963. var i;
  36964. var j;
  36965. var r;
  36966. var ringIdx = 1;
  36967. var s = 1; // surface index
  36968. var cs = 0;
  36969. var v = 0;
  36970. for (i = 0; i <= subdivisions; i++) {
  36971. h = i / subdivisions;
  36972. radius = (h * (diameterTop - diameterBottom) + diameterBottom) / 2;
  36973. ringIdx = (hasRings && i !== 0 && i !== subdivisions) ? 2 : 1;
  36974. for (r = 0; r < ringIdx; r++) {
  36975. if (hasRings) {
  36976. s += r;
  36977. }
  36978. if (enclose) {
  36979. s += 2 * r;
  36980. }
  36981. for (j = 0; j <= tessellation; j++) {
  36982. angle = j * angle_step;
  36983. // position
  36984. ringVertex.x = Math.cos(-angle) * radius;
  36985. ringVertex.y = -height / 2 + h * height;
  36986. ringVertex.z = Math.sin(-angle) * radius;
  36987. // normal
  36988. if (diameterTop === 0 && i === subdivisions) {
  36989. // if no top cap, reuse former normals
  36990. ringNormal.x = normals[normals.length - (tessellation + 1) * 3];
  36991. ringNormal.y = normals[normals.length - (tessellation + 1) * 3 + 1];
  36992. ringNormal.z = normals[normals.length - (tessellation + 1) * 3 + 2];
  36993. }
  36994. else {
  36995. ringNormal.x = ringVertex.x;
  36996. ringNormal.z = ringVertex.z;
  36997. ringNormal.y = Math.sqrt(ringNormal.x * ringNormal.x + ringNormal.z * ringNormal.z) * tan;
  36998. ringNormal.normalize();
  36999. }
  37000. // keep first ring vertex values for enclose
  37001. if (j === 0) {
  37002. ringFirstVertex.copyFrom(ringVertex);
  37003. ringFirstNormal.copyFrom(ringNormal);
  37004. }
  37005. positions.push(ringVertex.x, ringVertex.y, ringVertex.z);
  37006. normals.push(ringNormal.x, ringNormal.y, ringNormal.z);
  37007. if (hasRings) {
  37008. v = (cs !== s) ? faceUV[s].y : faceUV[s].w;
  37009. }
  37010. else {
  37011. v = faceUV[s].y + (faceUV[s].w - faceUV[s].y) * h;
  37012. }
  37013. uvs.push(faceUV[s].x + (faceUV[s].z - faceUV[s].x) * j / tessellation, v);
  37014. if (faceColors) {
  37015. colors.push(faceColors[s].r, faceColors[s].g, faceColors[s].b, faceColors[s].a);
  37016. }
  37017. }
  37018. // if enclose, add four vertices and their dedicated normals
  37019. if (arc !== 1 && enclose) {
  37020. positions.push(ringVertex.x, ringVertex.y, ringVertex.z);
  37021. positions.push(0, ringVertex.y, 0);
  37022. positions.push(0, ringVertex.y, 0);
  37023. positions.push(ringFirstVertex.x, ringFirstVertex.y, ringFirstVertex.z);
  37024. BABYLON.Vector3.CrossToRef(Y, ringNormal, quadNormal);
  37025. quadNormal.normalize();
  37026. normals.push(quadNormal.x, quadNormal.y, quadNormal.z, quadNormal.x, quadNormal.y, quadNormal.z);
  37027. BABYLON.Vector3.CrossToRef(ringFirstNormal, Y, quadNormal);
  37028. quadNormal.normalize();
  37029. normals.push(quadNormal.x, quadNormal.y, quadNormal.z, quadNormal.x, quadNormal.y, quadNormal.z);
  37030. if (hasRings) {
  37031. v = (cs !== s) ? faceUV[s + 1].y : faceUV[s + 1].w;
  37032. }
  37033. else {
  37034. v = faceUV[s + 1].y + (faceUV[s + 1].w - faceUV[s + 1].y) * h;
  37035. }
  37036. uvs.push(faceUV[s + 1].x, v);
  37037. uvs.push(faceUV[s + 1].z, v);
  37038. if (hasRings) {
  37039. v = (cs !== s) ? faceUV[s + 2].y : faceUV[s + 2].w;
  37040. }
  37041. else {
  37042. v = faceUV[s + 2].y + (faceUV[s + 2].w - faceUV[s + 2].y) * h;
  37043. }
  37044. uvs.push(faceUV[s + 2].x, v);
  37045. uvs.push(faceUV[s + 2].z, v);
  37046. if (faceColors) {
  37047. colors.push(faceColors[s + 1].r, faceColors[s + 1].g, faceColors[s + 1].b, faceColors[s + 1].a);
  37048. colors.push(faceColors[s + 1].r, faceColors[s + 1].g, faceColors[s + 1].b, faceColors[s + 1].a);
  37049. colors.push(faceColors[s + 2].r, faceColors[s + 2].g, faceColors[s + 2].b, faceColors[s + 2].a);
  37050. colors.push(faceColors[s + 2].r, faceColors[s + 2].g, faceColors[s + 2].b, faceColors[s + 2].a);
  37051. }
  37052. }
  37053. if (cs !== s) {
  37054. cs = s;
  37055. }
  37056. }
  37057. }
  37058. // indices
  37059. var e = (arc !== 1 && enclose) ? tessellation + 4 : tessellation; // correction of number of iteration if enclose
  37060. var s;
  37061. i = 0;
  37062. for (s = 0; s < subdivisions; s++) {
  37063. var i0 = 0;
  37064. var i1 = 0;
  37065. var i2 = 0;
  37066. var i3 = 0;
  37067. for (j = 0; j < tessellation; j++) {
  37068. i0 = i * (e + 1) + j;
  37069. i1 = (i + 1) * (e + 1) + j;
  37070. i2 = i * (e + 1) + (j + 1);
  37071. i3 = (i + 1) * (e + 1) + (j + 1);
  37072. indices.push(i0, i1, i2);
  37073. indices.push(i3, i2, i1);
  37074. }
  37075. if (arc !== 1 && enclose) { // if enclose, add two quads
  37076. indices.push(i0 + 2, i1 + 2, i2 + 2);
  37077. indices.push(i3 + 2, i2 + 2, i1 + 2);
  37078. indices.push(i0 + 4, i1 + 4, i2 + 4);
  37079. indices.push(i3 + 4, i2 + 4, i1 + 4);
  37080. }
  37081. i = (hasRings) ? (i + 2) : (i + 1);
  37082. }
  37083. // Caps
  37084. var createCylinderCap = function (isTop) {
  37085. var radius = isTop ? diameterTop / 2 : diameterBottom / 2;
  37086. if (radius === 0) {
  37087. return;
  37088. }
  37089. // Cap positions, normals & uvs
  37090. var angle;
  37091. var circleVector;
  37092. var i;
  37093. var u = (isTop) ? faceUV[surfaceNb - 1] : faceUV[0];
  37094. var c = null;
  37095. if (faceColors) {
  37096. c = (isTop) ? faceColors[surfaceNb - 1] : faceColors[0];
  37097. }
  37098. // cap center
  37099. var vbase = positions.length / 3;
  37100. var offset = isTop ? height / 2 : -height / 2;
  37101. var center = new BABYLON.Vector3(0, offset, 0);
  37102. positions.push(center.x, center.y, center.z);
  37103. normals.push(0, isTop ? 1 : -1, 0);
  37104. uvs.push(u.x + (u.z - u.x) * 0.5, u.y + (u.w - u.y) * 0.5);
  37105. if (c) {
  37106. colors.push(c.r, c.g, c.b, c.a);
  37107. }
  37108. var textureScale = new BABYLON.Vector2(0.5, 0.5);
  37109. for (i = 0; i <= tessellation; i++) {
  37110. angle = Math.PI * 2 * i * arc / tessellation;
  37111. var cos = Math.cos(-angle);
  37112. var sin = Math.sin(-angle);
  37113. circleVector = new BABYLON.Vector3(cos * radius, offset, sin * radius);
  37114. var textureCoordinate = new BABYLON.Vector2(cos * textureScale.x + 0.5, sin * textureScale.y + 0.5);
  37115. positions.push(circleVector.x, circleVector.y, circleVector.z);
  37116. normals.push(0, isTop ? 1 : -1, 0);
  37117. uvs.push(u.x + (u.z - u.x) * textureCoordinate.x, u.y + (u.w - u.y) * textureCoordinate.y);
  37118. if (c) {
  37119. colors.push(c.r, c.g, c.b, c.a);
  37120. }
  37121. }
  37122. // Cap indices
  37123. for (i = 0; i < tessellation; i++) {
  37124. if (!isTop) {
  37125. indices.push(vbase);
  37126. indices.push(vbase + (i + 1));
  37127. indices.push(vbase + (i + 2));
  37128. }
  37129. else {
  37130. indices.push(vbase);
  37131. indices.push(vbase + (i + 2));
  37132. indices.push(vbase + (i + 1));
  37133. }
  37134. }
  37135. };
  37136. // add caps to geometry
  37137. createCylinderCap(false);
  37138. createCylinderCap(true);
  37139. // Sides
  37140. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  37141. var vertexData = new VertexData();
  37142. vertexData.indices = indices;
  37143. vertexData.positions = positions;
  37144. vertexData.normals = normals;
  37145. vertexData.uvs = uvs;
  37146. if (faceColors) {
  37147. vertexData.colors = colors;
  37148. }
  37149. return vertexData;
  37150. };
  37151. /**
  37152. * Creates the VertexData for a torus
  37153. * @param options an object used to set the following optional parameters for the box, required but can be empty
  37154. * * diameter the diameter of the torus, optional default 1
  37155. * * thickness the diameter of the tube forming the torus, optional default 0.5
  37156. * * tessellation the number of prism sides, 3 for a triangular prism, optional, default 24
  37157. * * sideOrientation optional and takes the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  37158. * * 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)
  37159. * * 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)
  37160. * @returns the VertexData of the torus
  37161. */
  37162. VertexData.CreateTorus = function (options) {
  37163. var indices = [];
  37164. var positions = [];
  37165. var normals = [];
  37166. var uvs = [];
  37167. var diameter = options.diameter || 1;
  37168. var thickness = options.thickness || 0.5;
  37169. var tessellation = options.tessellation || 16;
  37170. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  37171. var stride = tessellation + 1;
  37172. for (var i = 0; i <= tessellation; i++) {
  37173. var u = i / tessellation;
  37174. var outerAngle = i * Math.PI * 2.0 / tessellation - Math.PI / 2.0;
  37175. var transform = BABYLON.Matrix.Translation(diameter / 2.0, 0, 0).multiply(BABYLON.Matrix.RotationY(outerAngle));
  37176. for (var j = 0; j <= tessellation; j++) {
  37177. var v = 1 - j / tessellation;
  37178. var innerAngle = j * Math.PI * 2.0 / tessellation + Math.PI;
  37179. var dx = Math.cos(innerAngle);
  37180. var dy = Math.sin(innerAngle);
  37181. // Create a vertex.
  37182. var normal = new BABYLON.Vector3(dx, dy, 0);
  37183. var position = normal.scale(thickness / 2);
  37184. var textureCoordinate = new BABYLON.Vector2(u, v);
  37185. position = BABYLON.Vector3.TransformCoordinates(position, transform);
  37186. normal = BABYLON.Vector3.TransformNormal(normal, transform);
  37187. positions.push(position.x, position.y, position.z);
  37188. normals.push(normal.x, normal.y, normal.z);
  37189. uvs.push(textureCoordinate.x, textureCoordinate.y);
  37190. // And create indices for two triangles.
  37191. var nextI = (i + 1) % stride;
  37192. var nextJ = (j + 1) % stride;
  37193. indices.push(i * stride + j);
  37194. indices.push(i * stride + nextJ);
  37195. indices.push(nextI * stride + j);
  37196. indices.push(i * stride + nextJ);
  37197. indices.push(nextI * stride + nextJ);
  37198. indices.push(nextI * stride + j);
  37199. }
  37200. }
  37201. // Sides
  37202. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  37203. // Result
  37204. var vertexData = new VertexData();
  37205. vertexData.indices = indices;
  37206. vertexData.positions = positions;
  37207. vertexData.normals = normals;
  37208. vertexData.uvs = uvs;
  37209. return vertexData;
  37210. };
  37211. /**
  37212. * Creates the VertexData of the LineSystem
  37213. * @param options an object used to set the following optional parameters for the LineSystem, required but can be empty
  37214. * - lines an array of lines, each line being an array of successive Vector3
  37215. * - colors an array of line colors, each of the line colors being an array of successive Color4, one per line point
  37216. * @returns the VertexData of the LineSystem
  37217. */
  37218. VertexData.CreateLineSystem = function (options) {
  37219. var indices = [];
  37220. var positions = [];
  37221. var lines = options.lines;
  37222. var colors = options.colors;
  37223. var vertexColors = [];
  37224. var idx = 0;
  37225. for (var l = 0; l < lines.length; l++) {
  37226. var points = lines[l];
  37227. for (var index = 0; index < points.length; index++) {
  37228. positions.push(points[index].x, points[index].y, points[index].z);
  37229. if (colors) {
  37230. var color = colors[l];
  37231. vertexColors.push(color[index].r, color[index].g, color[index].b, color[index].a);
  37232. }
  37233. if (index > 0) {
  37234. indices.push(idx - 1);
  37235. indices.push(idx);
  37236. }
  37237. idx++;
  37238. }
  37239. }
  37240. var vertexData = new VertexData();
  37241. vertexData.indices = indices;
  37242. vertexData.positions = positions;
  37243. if (colors) {
  37244. vertexData.colors = vertexColors;
  37245. }
  37246. return vertexData;
  37247. };
  37248. /**
  37249. * Create the VertexData for a DashedLines
  37250. * @param options an object used to set the following optional parameters for the DashedLines, required but can be empty
  37251. * - points an array successive Vector3
  37252. * - dashSize the size of the dashes relative to the dash number, optional, default 3
  37253. * - gapSize the size of the gap between two successive dashes relative to the dash number, optional, default 1
  37254. * - dashNb the intended total number of dashes, optional, default 200
  37255. * @returns the VertexData for the DashedLines
  37256. */
  37257. VertexData.CreateDashedLines = function (options) {
  37258. var dashSize = options.dashSize || 3;
  37259. var gapSize = options.gapSize || 1;
  37260. var dashNb = options.dashNb || 200;
  37261. var points = options.points;
  37262. var positions = new Array();
  37263. var indices = new Array();
  37264. var curvect = BABYLON.Vector3.Zero();
  37265. var lg = 0;
  37266. var nb = 0;
  37267. var shft = 0;
  37268. var dashshft = 0;
  37269. var curshft = 0;
  37270. var idx = 0;
  37271. var i = 0;
  37272. for (i = 0; i < points.length - 1; i++) {
  37273. points[i + 1].subtractToRef(points[i], curvect);
  37274. lg += curvect.length();
  37275. }
  37276. shft = lg / dashNb;
  37277. dashshft = dashSize * shft / (dashSize + gapSize);
  37278. for (i = 0; i < points.length - 1; i++) {
  37279. points[i + 1].subtractToRef(points[i], curvect);
  37280. nb = Math.floor(curvect.length() / shft);
  37281. curvect.normalize();
  37282. for (var j = 0; j < nb; j++) {
  37283. curshft = shft * j;
  37284. positions.push(points[i].x + curshft * curvect.x, points[i].y + curshft * curvect.y, points[i].z + curshft * curvect.z);
  37285. positions.push(points[i].x + (curshft + dashshft) * curvect.x, points[i].y + (curshft + dashshft) * curvect.y, points[i].z + (curshft + dashshft) * curvect.z);
  37286. indices.push(idx, idx + 1);
  37287. idx += 2;
  37288. }
  37289. }
  37290. // Result
  37291. var vertexData = new VertexData();
  37292. vertexData.positions = positions;
  37293. vertexData.indices = indices;
  37294. return vertexData;
  37295. };
  37296. /**
  37297. * Creates the VertexData for a Ground
  37298. * @param options an object used to set the following optional parameters for the Ground, required but can be empty
  37299. * - width the width (x direction) of the ground, optional, default 1
  37300. * - height the height (z direction) of the ground, optional, default 1
  37301. * - subdivisions the number of subdivisions per side, optional, default 1
  37302. * @returns the VertexData of the Ground
  37303. */
  37304. VertexData.CreateGround = function (options) {
  37305. var indices = [];
  37306. var positions = [];
  37307. var normals = [];
  37308. var uvs = [];
  37309. var row, col;
  37310. var width = options.width || 1;
  37311. var height = options.height || 1;
  37312. var subdivisionsX = options.subdivisionsX || options.subdivisions || 1;
  37313. var subdivisionsY = options.subdivisionsY || options.subdivisions || 1;
  37314. for (row = 0; row <= subdivisionsY; row++) {
  37315. for (col = 0; col <= subdivisionsX; col++) {
  37316. var position = new BABYLON.Vector3((col * width) / subdivisionsX - (width / 2.0), 0, ((subdivisionsY - row) * height) / subdivisionsY - (height / 2.0));
  37317. var normal = new BABYLON.Vector3(0, 1.0, 0);
  37318. positions.push(position.x, position.y, position.z);
  37319. normals.push(normal.x, normal.y, normal.z);
  37320. uvs.push(col / subdivisionsX, 1.0 - row / subdivisionsY);
  37321. }
  37322. }
  37323. for (row = 0; row < subdivisionsY; row++) {
  37324. for (col = 0; col < subdivisionsX; col++) {
  37325. indices.push(col + 1 + (row + 1) * (subdivisionsX + 1));
  37326. indices.push(col + 1 + row * (subdivisionsX + 1));
  37327. indices.push(col + row * (subdivisionsX + 1));
  37328. indices.push(col + (row + 1) * (subdivisionsX + 1));
  37329. indices.push(col + 1 + (row + 1) * (subdivisionsX + 1));
  37330. indices.push(col + row * (subdivisionsX + 1));
  37331. }
  37332. }
  37333. // Result
  37334. var vertexData = new VertexData();
  37335. vertexData.indices = indices;
  37336. vertexData.positions = positions;
  37337. vertexData.normals = normals;
  37338. vertexData.uvs = uvs;
  37339. return vertexData;
  37340. };
  37341. /**
  37342. * Creates the VertexData for a TiledGround by subdividing the ground into tiles
  37343. * @param options an object used to set the following optional parameters for the Ground, required but can be empty
  37344. * * xmin the ground minimum X coordinate, optional, default -1
  37345. * * zmin the ground minimum Z coordinate, optional, default -1
  37346. * * xmax the ground maximum X coordinate, optional, default 1
  37347. * * zmax the ground maximum Z coordinate, optional, default 1
  37348. * * 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}
  37349. * * 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}
  37350. * @returns the VertexData of the TiledGround
  37351. */
  37352. VertexData.CreateTiledGround = function (options) {
  37353. var xmin = (options.xmin !== undefined && options.xmin !== null) ? options.xmin : -1.0;
  37354. var zmin = (options.zmin !== undefined && options.zmin !== null) ? options.zmin : -1.0;
  37355. var xmax = (options.xmax !== undefined && options.xmax !== null) ? options.xmax : 1.0;
  37356. var zmax = (options.zmax !== undefined && options.zmax !== null) ? options.zmax : 1.0;
  37357. var subdivisions = options.subdivisions || { w: 1, h: 1 };
  37358. var precision = options.precision || { w: 1, h: 1 };
  37359. var indices = new Array();
  37360. var positions = new Array();
  37361. var normals = new Array();
  37362. var uvs = new Array();
  37363. var row, col, tileRow, tileCol;
  37364. subdivisions.h = (subdivisions.h < 1) ? 1 : subdivisions.h;
  37365. subdivisions.w = (subdivisions.w < 1) ? 1 : subdivisions.w;
  37366. precision.w = (precision.w < 1) ? 1 : precision.w;
  37367. precision.h = (precision.h < 1) ? 1 : precision.h;
  37368. var tileSize = {
  37369. 'w': (xmax - xmin) / subdivisions.w,
  37370. 'h': (zmax - zmin) / subdivisions.h
  37371. };
  37372. function applyTile(xTileMin, zTileMin, xTileMax, zTileMax) {
  37373. // Indices
  37374. var base = positions.length / 3;
  37375. var rowLength = precision.w + 1;
  37376. for (row = 0; row < precision.h; row++) {
  37377. for (col = 0; col < precision.w; col++) {
  37378. var square = [
  37379. base + col + row * rowLength,
  37380. base + (col + 1) + row * rowLength,
  37381. base + (col + 1) + (row + 1) * rowLength,
  37382. base + col + (row + 1) * rowLength
  37383. ];
  37384. indices.push(square[1]);
  37385. indices.push(square[2]);
  37386. indices.push(square[3]);
  37387. indices.push(square[0]);
  37388. indices.push(square[1]);
  37389. indices.push(square[3]);
  37390. }
  37391. }
  37392. // Position, normals and uvs
  37393. var position = BABYLON.Vector3.Zero();
  37394. var normal = new BABYLON.Vector3(0, 1.0, 0);
  37395. for (row = 0; row <= precision.h; row++) {
  37396. position.z = (row * (zTileMax - zTileMin)) / precision.h + zTileMin;
  37397. for (col = 0; col <= precision.w; col++) {
  37398. position.x = (col * (xTileMax - xTileMin)) / precision.w + xTileMin;
  37399. position.y = 0;
  37400. positions.push(position.x, position.y, position.z);
  37401. normals.push(normal.x, normal.y, normal.z);
  37402. uvs.push(col / precision.w, row / precision.h);
  37403. }
  37404. }
  37405. }
  37406. for (tileRow = 0; tileRow < subdivisions.h; tileRow++) {
  37407. for (tileCol = 0; tileCol < subdivisions.w; tileCol++) {
  37408. applyTile(xmin + tileCol * tileSize.w, zmin + tileRow * tileSize.h, xmin + (tileCol + 1) * tileSize.w, zmin + (tileRow + 1) * tileSize.h);
  37409. }
  37410. }
  37411. // Result
  37412. var vertexData = new VertexData();
  37413. vertexData.indices = indices;
  37414. vertexData.positions = positions;
  37415. vertexData.normals = normals;
  37416. vertexData.uvs = uvs;
  37417. return vertexData;
  37418. };
  37419. /**
  37420. * Creates the VertexData of the Ground designed from a heightmap
  37421. * @param options an object used to set the following parameters for the Ground, required and provided by MeshBuilder.CreateGroundFromHeightMap
  37422. * * width the width (x direction) of the ground
  37423. * * height the height (z direction) of the ground
  37424. * * subdivisions the number of subdivisions per side
  37425. * * minHeight the minimum altitude on the ground, optional, default 0
  37426. * * maxHeight the maximum altitude on the ground, optional default 1
  37427. * * colorFilter the filter to apply to the image pixel colors to compute the height, optional Color3, default (0.3, 0.59, 0.11)
  37428. * * buffer the array holding the image color data
  37429. * * bufferWidth the width of image
  37430. * * bufferHeight the height of image
  37431. * @returns the VertexData of the Ground designed from a heightmap
  37432. */
  37433. VertexData.CreateGroundFromHeightMap = function (options) {
  37434. var indices = [];
  37435. var positions = [];
  37436. var normals = [];
  37437. var uvs = [];
  37438. var row, col;
  37439. var filter = options.colorFilter || new BABYLON.Color3(0.3, 0.59, 0.11);
  37440. // Vertices
  37441. for (row = 0; row <= options.subdivisions; row++) {
  37442. for (col = 0; col <= options.subdivisions; col++) {
  37443. 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));
  37444. // Compute height
  37445. var heightMapX = (((position.x + options.width / 2) / options.width) * (options.bufferWidth - 1)) | 0;
  37446. var heightMapY = ((1.0 - (position.z + options.height / 2) / options.height) * (options.bufferHeight - 1)) | 0;
  37447. var pos = (heightMapX + heightMapY * options.bufferWidth) * 4;
  37448. var r = options.buffer[pos] / 255.0;
  37449. var g = options.buffer[pos + 1] / 255.0;
  37450. var b = options.buffer[pos + 2] / 255.0;
  37451. var gradient = r * filter.r + g * filter.g + b * filter.b;
  37452. position.y = options.minHeight + (options.maxHeight - options.minHeight) * gradient;
  37453. // Add vertex
  37454. positions.push(position.x, position.y, position.z);
  37455. normals.push(0, 0, 0);
  37456. uvs.push(col / options.subdivisions, 1.0 - row / options.subdivisions);
  37457. }
  37458. }
  37459. // Indices
  37460. for (row = 0; row < options.subdivisions; row++) {
  37461. for (col = 0; col < options.subdivisions; col++) {
  37462. indices.push(col + 1 + (row + 1) * (options.subdivisions + 1));
  37463. indices.push(col + 1 + row * (options.subdivisions + 1));
  37464. indices.push(col + row * (options.subdivisions + 1));
  37465. indices.push(col + (row + 1) * (options.subdivisions + 1));
  37466. indices.push(col + 1 + (row + 1) * (options.subdivisions + 1));
  37467. indices.push(col + row * (options.subdivisions + 1));
  37468. }
  37469. }
  37470. // Normals
  37471. VertexData.ComputeNormals(positions, indices, normals);
  37472. // Result
  37473. var vertexData = new VertexData();
  37474. vertexData.indices = indices;
  37475. vertexData.positions = positions;
  37476. vertexData.normals = normals;
  37477. vertexData.uvs = uvs;
  37478. return vertexData;
  37479. };
  37480. /**
  37481. * Creates the VertexData for a Plane
  37482. * @param options an object used to set the following optional parameters for the plane, required but can be empty
  37483. * * size sets the width and height of the plane to the value of size, optional default 1
  37484. * * width sets the width (x direction) of the plane, overwrites the width set by size, optional, default size
  37485. * * height sets the height (y direction) of the plane, overwrites the height set by size, optional, default size
  37486. * * sideOrientation optional and takes the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  37487. * * 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)
  37488. * * 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)
  37489. * @returns the VertexData of the box
  37490. */
  37491. VertexData.CreatePlane = function (options) {
  37492. var indices = [];
  37493. var positions = [];
  37494. var normals = [];
  37495. var uvs = [];
  37496. var width = options.width || options.size || 1;
  37497. var height = options.height || options.size || 1;
  37498. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  37499. // Vertices
  37500. var halfWidth = width / 2.0;
  37501. var halfHeight = height / 2.0;
  37502. positions.push(-halfWidth, -halfHeight, 0);
  37503. normals.push(0, 0, -1.0);
  37504. uvs.push(0.0, 0.0);
  37505. positions.push(halfWidth, -halfHeight, 0);
  37506. normals.push(0, 0, -1.0);
  37507. uvs.push(1.0, 0.0);
  37508. positions.push(halfWidth, halfHeight, 0);
  37509. normals.push(0, 0, -1.0);
  37510. uvs.push(1.0, 1.0);
  37511. positions.push(-halfWidth, halfHeight, 0);
  37512. normals.push(0, 0, -1.0);
  37513. uvs.push(0.0, 1.0);
  37514. // Indices
  37515. indices.push(0);
  37516. indices.push(1);
  37517. indices.push(2);
  37518. indices.push(0);
  37519. indices.push(2);
  37520. indices.push(3);
  37521. // Sides
  37522. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  37523. // Result
  37524. var vertexData = new VertexData();
  37525. vertexData.indices = indices;
  37526. vertexData.positions = positions;
  37527. vertexData.normals = normals;
  37528. vertexData.uvs = uvs;
  37529. return vertexData;
  37530. };
  37531. /**
  37532. * Creates the VertexData of the Disc or regular Polygon
  37533. * @param options an object used to set the following optional parameters for the disc, required but can be empty
  37534. * * radius the radius of the disc, optional default 0.5
  37535. * * tessellation the number of polygon sides, optional, default 64
  37536. * * 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
  37537. * * sideOrientation optional and takes the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  37538. * * 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)
  37539. * * 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)
  37540. * @returns the VertexData of the box
  37541. */
  37542. VertexData.CreateDisc = function (options) {
  37543. var positions = new Array();
  37544. var indices = new Array();
  37545. var normals = new Array();
  37546. var uvs = new Array();
  37547. var radius = options.radius || 0.5;
  37548. var tessellation = options.tessellation || 64;
  37549. var arc = options.arc && (options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc || 1.0;
  37550. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  37551. // positions and uvs
  37552. positions.push(0, 0, 0); // disc center first
  37553. uvs.push(0.5, 0.5);
  37554. var theta = Math.PI * 2 * arc;
  37555. var step = theta / tessellation;
  37556. for (var a = 0; a < theta; a += step) {
  37557. var x = Math.cos(a);
  37558. var y = Math.sin(a);
  37559. var u = (x + 1) / 2;
  37560. var v = (1 - y) / 2;
  37561. positions.push(radius * x, radius * y, 0);
  37562. uvs.push(u, v);
  37563. }
  37564. if (arc === 1) {
  37565. positions.push(positions[3], positions[4], positions[5]); // close the circle
  37566. uvs.push(uvs[2], uvs[3]);
  37567. }
  37568. //indices
  37569. var vertexNb = positions.length / 3;
  37570. for (var i = 1; i < vertexNb - 1; i++) {
  37571. indices.push(i + 1, 0, i);
  37572. }
  37573. // result
  37574. VertexData.ComputeNormals(positions, indices, normals);
  37575. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  37576. var vertexData = new VertexData();
  37577. vertexData.indices = indices;
  37578. vertexData.positions = positions;
  37579. vertexData.normals = normals;
  37580. vertexData.uvs = uvs;
  37581. return vertexData;
  37582. };
  37583. /**
  37584. * Creates the VertexData for an irregular Polygon in the XoZ plane using a mesh built by polygonTriangulation.build()
  37585. * All parameters are provided by MeshBuilder.CreatePolygon as needed
  37586. * @param polygon a mesh built from polygonTriangulation.build()
  37587. * @param sideOrientation takes the values BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  37588. * @param fUV an array of Vector4 elements used to set different images to the top, rings and bottom respectively
  37589. * @param fColors an array of Color3 elements used to set different colors to the top, rings and bottom respectively
  37590. * @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)
  37591. * @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)
  37592. * @returns the VertexData of the Polygon
  37593. */
  37594. VertexData.CreatePolygon = function (polygon, sideOrientation, fUV, fColors, frontUVs, backUVs) {
  37595. var faceUV = fUV || new Array(3);
  37596. var faceColors = fColors;
  37597. var colors = [];
  37598. // default face colors and UV if undefined
  37599. for (var f = 0; f < 3; f++) {
  37600. if (faceUV[f] === undefined) {
  37601. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  37602. }
  37603. if (faceColors && faceColors[f] === undefined) {
  37604. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  37605. }
  37606. }
  37607. var positions = polygon.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  37608. var normals = polygon.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  37609. var uvs = polygon.getVerticesData(BABYLON.VertexBuffer.UVKind);
  37610. var indices = polygon.getIndices();
  37611. // set face colours and textures
  37612. var idx = 0;
  37613. var face = 0;
  37614. for (var index = 0; index < normals.length; index += 3) {
  37615. //Edge Face no. 1
  37616. if (Math.abs(normals[index + 1]) < 0.001) {
  37617. face = 1;
  37618. }
  37619. //Top Face no. 0
  37620. if (Math.abs(normals[index + 1] - 1) < 0.001) {
  37621. face = 0;
  37622. }
  37623. //Bottom Face no. 2
  37624. if (Math.abs(normals[index + 1] + 1) < 0.001) {
  37625. face = 2;
  37626. }
  37627. idx = index / 3;
  37628. uvs[2 * idx] = (1 - uvs[2 * idx]) * faceUV[face].x + uvs[2 * idx] * faceUV[face].z;
  37629. uvs[2 * idx + 1] = (1 - uvs[2 * idx + 1]) * faceUV[face].y + uvs[2 * idx + 1] * faceUV[face].w;
  37630. if (faceColors) {
  37631. colors.push(faceColors[face].r, faceColors[face].g, faceColors[face].b, faceColors[face].a);
  37632. }
  37633. }
  37634. // sides
  37635. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, frontUVs, backUVs);
  37636. // Result
  37637. var vertexData = new VertexData();
  37638. vertexData.indices = indices;
  37639. vertexData.positions = positions;
  37640. vertexData.normals = normals;
  37641. vertexData.uvs = uvs;
  37642. if (faceColors) {
  37643. var totalColors = (sideOrientation === BABYLON.Mesh.DOUBLESIDE) ? colors.concat(colors) : colors;
  37644. vertexData.colors = totalColors;
  37645. }
  37646. return vertexData;
  37647. };
  37648. /**
  37649. * Creates the VertexData of the IcoSphere
  37650. * @param options an object used to set the following optional parameters for the IcoSphere, required but can be empty
  37651. * * radius the radius of the IcoSphere, optional default 1
  37652. * * radiusX allows stretching in the x direction, optional, default radius
  37653. * * radiusY allows stretching in the y direction, optional, default radius
  37654. * * radiusZ allows stretching in the z direction, optional, default radius
  37655. * * flat when true creates a flat shaded mesh, optional, default true
  37656. * * subdivisions increasing the subdivisions increases the number of faces, optional, default 4
  37657. * * sideOrientation optional and takes the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  37658. * * 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)
  37659. * * 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)
  37660. * @returns the VertexData of the IcoSphere
  37661. */
  37662. VertexData.CreateIcoSphere = function (options) {
  37663. var sideOrientation = options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  37664. var radius = options.radius || 1;
  37665. var flat = (options.flat === undefined) ? true : options.flat;
  37666. var subdivisions = options.subdivisions || 4;
  37667. var radiusX = options.radiusX || radius;
  37668. var radiusY = options.radiusY || radius;
  37669. var radiusZ = options.radiusZ || radius;
  37670. var t = (1 + Math.sqrt(5)) / 2;
  37671. // 12 vertex x,y,z
  37672. var ico_vertices = [
  37673. -1, t, -0, 1, t, 0, -1, -t, 0, 1, -t, 0,
  37674. 0, -1, -t, 0, 1, -t, 0, -1, t, 0, 1, t,
  37675. t, 0, 1, t, 0, -1, -t, 0, 1, -t, 0, -1 // v8-11
  37676. ];
  37677. // index of 3 vertex makes a face of icopshere
  37678. var ico_indices = [
  37679. 0, 11, 5, 0, 5, 1, 0, 1, 7, 0, 7, 10, 12, 22, 23,
  37680. 1, 5, 20, 5, 11, 4, 23, 22, 13, 22, 18, 6, 7, 1, 8,
  37681. 14, 21, 4, 14, 4, 2, 16, 13, 6, 15, 6, 19, 3, 8, 9,
  37682. 4, 21, 5, 13, 17, 23, 6, 13, 22, 19, 6, 18, 9, 8, 1
  37683. ];
  37684. // vertex for uv have aliased position, not for UV
  37685. var vertices_unalias_id = [
  37686. 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11,
  37687. // vertex alias
  37688. 0,
  37689. 2,
  37690. 3,
  37691. 3,
  37692. 3,
  37693. 4,
  37694. 7,
  37695. 8,
  37696. 9,
  37697. 9,
  37698. 10,
  37699. 11 // 23: B + 12
  37700. ];
  37701. // uv as integer step (not pixels !)
  37702. var ico_vertexuv = [
  37703. 5, 1, 3, 1, 6, 4, 0, 0,
  37704. 5, 3, 4, 2, 2, 2, 4, 0,
  37705. 2, 0, 1, 1, 6, 0, 6, 2,
  37706. // vertex alias (for same vertex on different faces)
  37707. 0, 4,
  37708. 3, 3,
  37709. 4, 4,
  37710. 3, 1,
  37711. 4, 2,
  37712. 4, 4,
  37713. 0, 2,
  37714. 1, 1,
  37715. 2, 2,
  37716. 3, 3,
  37717. 1, 3,
  37718. 2, 4 // 23: B + 12
  37719. ];
  37720. // Vertices[0, 1, ...9, A, B] : position on UV plane
  37721. // '+' indicate duplicate position to be fixed (3,9:0,2,3,4,7,8,A,B)
  37722. // First island of uv mapping
  37723. // v = 4h 3+ 2
  37724. // v = 3h 9+ 4
  37725. // v = 2h 9+ 5 B
  37726. // v = 1h 9 1 0
  37727. // v = 0h 3 8 7 A
  37728. // u = 0 1 2 3 4 5 6 *a
  37729. // Second island of uv mapping
  37730. // v = 4h 0+ B+ 4+
  37731. // v = 3h A+ 2+
  37732. // v = 2h 7+ 6 3+
  37733. // v = 1h 8+ 3+
  37734. // v = 0h
  37735. // u = 0 1 2 3 4 5 6 *a
  37736. // Face layout on texture UV mapping
  37737. // ============
  37738. // \ 4 /\ 16 / ======
  37739. // \ / \ / /\ 11 /
  37740. // \/ 7 \/ / \ /
  37741. // ======= / 10 \/
  37742. // /\ 17 /\ =======
  37743. // / \ / \ \ 15 /\
  37744. // / 8 \/ 12 \ \ / \
  37745. // ============ \/ 6 \
  37746. // \ 18 /\ ============
  37747. // \ / \ \ 5 /\ 0 /
  37748. // \/ 13 \ \ / \ /
  37749. // ======= \/ 1 \/
  37750. // =============
  37751. // /\ 19 /\ 2 /\
  37752. // / \ / \ / \
  37753. // / 14 \/ 9 \/ 3 \
  37754. // ===================
  37755. // uv step is u:1 or 0.5, v:cos(30)=sqrt(3)/2, ratio approx is 84/97
  37756. var ustep = 138 / 1024;
  37757. var vstep = 239 / 1024;
  37758. var uoffset = 60 / 1024;
  37759. var voffset = 26 / 1024;
  37760. // Second island should have margin, not to touch the first island
  37761. // avoid any borderline artefact in pixel rounding
  37762. var island_u_offset = -40 / 1024;
  37763. var island_v_offset = +20 / 1024;
  37764. // face is either island 0 or 1 :
  37765. // second island is for faces : [4, 7, 8, 12, 13, 16, 17, 18]
  37766. var island = [
  37767. 0, 0, 0, 0, 1,
  37768. 0, 0, 1, 1, 0,
  37769. 0, 0, 1, 1, 0,
  37770. 0, 1, 1, 1, 0 // 15 - 19
  37771. ];
  37772. var indices = new Array();
  37773. var positions = new Array();
  37774. var normals = new Array();
  37775. var uvs = new Array();
  37776. var current_indice = 0;
  37777. // prepare array of 3 vector (empty) (to be worked in place, shared for each face)
  37778. var face_vertex_pos = new Array(3);
  37779. var face_vertex_uv = new Array(3);
  37780. var v012;
  37781. for (v012 = 0; v012 < 3; v012++) {
  37782. face_vertex_pos[v012] = BABYLON.Vector3.Zero();
  37783. face_vertex_uv[v012] = BABYLON.Vector2.Zero();
  37784. }
  37785. // create all with normals
  37786. for (var face = 0; face < 20; face++) {
  37787. // 3 vertex per face
  37788. for (v012 = 0; v012 < 3; v012++) {
  37789. // look up vertex 0,1,2 to its index in 0 to 11 (or 23 including alias)
  37790. var v_id = ico_indices[3 * face + v012];
  37791. // vertex have 3D position (x,y,z)
  37792. 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]);
  37793. // Normalize to get normal, then scale to radius
  37794. face_vertex_pos[v012].normalize().scaleInPlace(radius);
  37795. // uv Coordinates from vertex ID
  37796. 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);
  37797. }
  37798. // Subdivide the face (interpolate pos, norm, uv)
  37799. // - pos is linear interpolation, then projected to sphere (converge polyhedron to sphere)
  37800. // - norm is linear interpolation of vertex corner normal
  37801. // (to be checked if better to re-calc from face vertex, or if approximation is OK ??? )
  37802. // - uv is linear interpolation
  37803. //
  37804. // Topology is as below for sub-divide by 2
  37805. // vertex shown as v0,v1,v2
  37806. // interp index is i1 to progress in range [v0,v1[
  37807. // interp index is i2 to progress in range [v0,v2[
  37808. // face index as (i1,i2) for /\ : (i1,i2),(i1+1,i2),(i1,i2+1)
  37809. // and (i1,i2)' for \/ : (i1+1,i2),(i1+1,i2+1),(i1,i2+1)
  37810. //
  37811. //
  37812. // i2 v2
  37813. // ^ ^
  37814. // / / \
  37815. // / / \
  37816. // / / \
  37817. // / / (0,1) \
  37818. // / #---------\
  37819. // / / \ (0,0)'/ \
  37820. // / / \ / \
  37821. // / / \ / \
  37822. // / / (0,0) \ / (1,0) \
  37823. // / #---------#---------\
  37824. // v0 v1
  37825. //
  37826. // --------------------> i1
  37827. //
  37828. // interp of (i1,i2):
  37829. // along i2 : x0=lerp(v0,v2, i2/S) <---> x1=lerp(v1,v2, i2/S)
  37830. // along i1 : lerp(x0,x1, i1/(S-i2))
  37831. //
  37832. // centroid of triangle is needed to get help normal computation
  37833. // (c1,c2) are used for centroid location
  37834. var interp_vertex = function (i1, i2, c1, c2) {
  37835. // vertex is interpolated from
  37836. // - face_vertex_pos[0..2]
  37837. // - face_vertex_uv[0..2]
  37838. var pos_x0 = BABYLON.Vector3.Lerp(face_vertex_pos[0], face_vertex_pos[2], i2 / subdivisions);
  37839. var pos_x1 = BABYLON.Vector3.Lerp(face_vertex_pos[1], face_vertex_pos[2], i2 / subdivisions);
  37840. var pos_interp = (subdivisions === i2) ? face_vertex_pos[2] : BABYLON.Vector3.Lerp(pos_x0, pos_x1, i1 / (subdivisions - i2));
  37841. pos_interp.normalize();
  37842. var vertex_normal;
  37843. if (flat) {
  37844. // in flat mode, recalculate normal as face centroid normal
  37845. var centroid_x0 = BABYLON.Vector3.Lerp(face_vertex_pos[0], face_vertex_pos[2], c2 / subdivisions);
  37846. var centroid_x1 = BABYLON.Vector3.Lerp(face_vertex_pos[1], face_vertex_pos[2], c2 / subdivisions);
  37847. vertex_normal = BABYLON.Vector3.Lerp(centroid_x0, centroid_x1, c1 / (subdivisions - c2));
  37848. }
  37849. else {
  37850. // in smooth mode, recalculate normal from each single vertex position
  37851. vertex_normal = new BABYLON.Vector3(pos_interp.x, pos_interp.y, pos_interp.z);
  37852. }
  37853. // Vertex normal need correction due to X,Y,Z radius scaling
  37854. vertex_normal.x /= radiusX;
  37855. vertex_normal.y /= radiusY;
  37856. vertex_normal.z /= radiusZ;
  37857. vertex_normal.normalize();
  37858. var uv_x0 = BABYLON.Vector2.Lerp(face_vertex_uv[0], face_vertex_uv[2], i2 / subdivisions);
  37859. var uv_x1 = BABYLON.Vector2.Lerp(face_vertex_uv[1], face_vertex_uv[2], i2 / subdivisions);
  37860. var uv_interp = (subdivisions === i2) ? face_vertex_uv[2] : BABYLON.Vector2.Lerp(uv_x0, uv_x1, i1 / (subdivisions - i2));
  37861. positions.push(pos_interp.x * radiusX, pos_interp.y * radiusY, pos_interp.z * radiusZ);
  37862. normals.push(vertex_normal.x, vertex_normal.y, vertex_normal.z);
  37863. uvs.push(uv_interp.x, uv_interp.y);
  37864. // push each vertex has member of a face
  37865. // Same vertex can bleong to multiple face, it is pushed multiple time (duplicate vertex are present)
  37866. indices.push(current_indice);
  37867. current_indice++;
  37868. };
  37869. for (var i2 = 0; i2 < subdivisions; i2++) {
  37870. for (var i1 = 0; i1 + i2 < subdivisions; i1++) {
  37871. // face : (i1,i2) for /\ :
  37872. // interp for : (i1,i2),(i1+1,i2),(i1,i2+1)
  37873. interp_vertex(i1, i2, i1 + 1.0 / 3, i2 + 1.0 / 3);
  37874. interp_vertex(i1 + 1, i2, i1 + 1.0 / 3, i2 + 1.0 / 3);
  37875. interp_vertex(i1, i2 + 1, i1 + 1.0 / 3, i2 + 1.0 / 3);
  37876. if (i1 + i2 + 1 < subdivisions) {
  37877. // face : (i1,i2)' for \/ :
  37878. // interp for (i1+1,i2),(i1+1,i2+1),(i1,i2+1)
  37879. interp_vertex(i1 + 1, i2, i1 + 2.0 / 3, i2 + 2.0 / 3);
  37880. interp_vertex(i1 + 1, i2 + 1, i1 + 2.0 / 3, i2 + 2.0 / 3);
  37881. interp_vertex(i1, i2 + 1, i1 + 2.0 / 3, i2 + 2.0 / 3);
  37882. }
  37883. }
  37884. }
  37885. }
  37886. // Sides
  37887. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  37888. // Result
  37889. var vertexData = new VertexData();
  37890. vertexData.indices = indices;
  37891. vertexData.positions = positions;
  37892. vertexData.normals = normals;
  37893. vertexData.uvs = uvs;
  37894. return vertexData;
  37895. };
  37896. // inspired from // http://stemkoski.github.io/Three.js/Polyhedra.html
  37897. /**
  37898. * Creates the VertexData for a Polyhedron
  37899. * @param options an object used to set the following optional parameters for the polyhedron, required but can be empty
  37900. * * type provided types are:
  37901. * * 0 : Tetrahedron, 1 : Octahedron, 2 : Dodecahedron, 3 : Icosahedron, 4 : Rhombicuboctahedron, 5 : Triangular Prism, 6 : Pentagonal Prism, 7 : Hexagonal Prism, 8 : Square Pyramid (J1)
  37902. * * 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)
  37903. * * size the size of the IcoSphere, optional default 1
  37904. * * sizeX allows stretching in the x direction, optional, default size
  37905. * * sizeY allows stretching in the y direction, optional, default size
  37906. * * sizeZ allows stretching in the z direction, optional, default size
  37907. * * 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
  37908. * * faceUV an array of Vector4 elements used to set different images to the top, rings and bottom respectively
  37909. * * faceColors an array of Color3 elements used to set different colors to the top, rings and bottom respectively
  37910. * * flat when true creates a flat shaded mesh, optional, default true
  37911. * * subdivisions increasing the subdivisions increases the number of faces, optional, default 4
  37912. * * sideOrientation optional and takes the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  37913. * * 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)
  37914. * * 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)
  37915. * @returns the VertexData of the Polyhedron
  37916. */
  37917. VertexData.CreatePolyhedron = function (options) {
  37918. // provided polyhedron types :
  37919. // 0 : Tetrahedron, 1 : Octahedron, 2 : Dodecahedron, 3 : Icosahedron, 4 : Rhombicuboctahedron, 5 : Triangular Prism, 6 : Pentagonal Prism, 7 : Hexagonal Prism, 8 : Square Pyramid (J1)
  37920. // 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)
  37921. var polyhedra = [];
  37922. 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]] };
  37923. 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]] };
  37924. polyhedra[2] = {
  37925. 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]],
  37926. 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]]
  37927. };
  37928. polyhedra[3] = {
  37929. 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]],
  37930. 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]]
  37931. };
  37932. polyhedra[4] = {
  37933. 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]],
  37934. 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]]
  37935. };
  37936. 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]] };
  37937. 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]] };
  37938. 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]] };
  37939. 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]] };
  37940. 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]] };
  37941. 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]] };
  37942. 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]] };
  37943. 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]] };
  37944. 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]] };
  37945. polyhedra[14] = {
  37946. 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]],
  37947. 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]]
  37948. };
  37949. var type = options.type && (options.type < 0 || options.type >= polyhedra.length) ? 0 : options.type || 0;
  37950. var size = options.size;
  37951. var sizeX = options.sizeX || size || 1;
  37952. var sizeY = options.sizeY || size || 1;
  37953. var sizeZ = options.sizeZ || size || 1;
  37954. var data = options.custom || polyhedra[type];
  37955. var nbfaces = data.face.length;
  37956. var faceUV = options.faceUV || new Array(nbfaces);
  37957. var faceColors = options.faceColors;
  37958. var flat = (options.flat === undefined) ? true : options.flat;
  37959. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  37960. var positions = new Array();
  37961. var indices = new Array();
  37962. var normals = new Array();
  37963. var uvs = new Array();
  37964. var colors = new Array();
  37965. var index = 0;
  37966. var faceIdx = 0; // face cursor in the array "indexes"
  37967. var indexes = new Array();
  37968. var i = 0;
  37969. var f = 0;
  37970. var u, v, ang, x, y, tmp;
  37971. // default face colors and UV if undefined
  37972. if (flat) {
  37973. for (f = 0; f < nbfaces; f++) {
  37974. if (faceColors && faceColors[f] === undefined) {
  37975. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  37976. }
  37977. if (faceUV && faceUV[f] === undefined) {
  37978. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  37979. }
  37980. }
  37981. }
  37982. if (!flat) {
  37983. for (i = 0; i < data.vertex.length; i++) {
  37984. positions.push(data.vertex[i][0] * sizeX, data.vertex[i][1] * sizeY, data.vertex[i][2] * sizeZ);
  37985. uvs.push(0, 0);
  37986. }
  37987. for (f = 0; f < nbfaces; f++) {
  37988. for (i = 0; i < data.face[f].length - 2; i++) {
  37989. indices.push(data.face[f][0], data.face[f][i + 2], data.face[f][i + 1]);
  37990. }
  37991. }
  37992. }
  37993. else {
  37994. for (f = 0; f < nbfaces; f++) {
  37995. var fl = data.face[f].length; // number of vertices of the current face
  37996. ang = 2 * Math.PI / fl;
  37997. x = 0.5 * Math.tan(ang / 2);
  37998. y = 0.5;
  37999. // positions, uvs, colors
  38000. for (i = 0; i < fl; i++) {
  38001. // positions
  38002. 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);
  38003. indexes.push(index);
  38004. index++;
  38005. // uvs
  38006. u = faceUV[f].x + (faceUV[f].z - faceUV[f].x) * (0.5 + x);
  38007. v = faceUV[f].y + (faceUV[f].w - faceUV[f].y) * (y - 0.5);
  38008. uvs.push(u, v);
  38009. tmp = x * Math.cos(ang) - y * Math.sin(ang);
  38010. y = x * Math.sin(ang) + y * Math.cos(ang);
  38011. x = tmp;
  38012. // colors
  38013. if (faceColors) {
  38014. colors.push(faceColors[f].r, faceColors[f].g, faceColors[f].b, faceColors[f].a);
  38015. }
  38016. }
  38017. // indices from indexes
  38018. for (i = 0; i < fl - 2; i++) {
  38019. indices.push(indexes[0 + faceIdx], indexes[i + 2 + faceIdx], indexes[i + 1 + faceIdx]);
  38020. }
  38021. faceIdx += fl;
  38022. }
  38023. }
  38024. VertexData.ComputeNormals(positions, indices, normals);
  38025. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  38026. var vertexData = new VertexData();
  38027. vertexData.positions = positions;
  38028. vertexData.indices = indices;
  38029. vertexData.normals = normals;
  38030. vertexData.uvs = uvs;
  38031. if (faceColors && flat) {
  38032. vertexData.colors = colors;
  38033. }
  38034. return vertexData;
  38035. };
  38036. // based on http://code.google.com/p/away3d/source/browse/trunk/fp10/Away3D/src/away3d/primitives/TorusKnot.as?spec=svn2473&r=2473
  38037. /**
  38038. * Creates the VertexData for a TorusKnot
  38039. * @param options an object used to set the following optional parameters for the TorusKnot, required but can be empty
  38040. * * radius the radius of the torus knot, optional, default 2
  38041. * * tube the thickness of the tube, optional, default 0.5
  38042. * * radialSegments the number of sides on each tube segments, optional, default 32
  38043. * * tubularSegments the number of tubes to decompose the knot into, optional, default 32
  38044. * * p the number of windings around the z axis, optional, default 2
  38045. * * q the number of windings around the x axis, optional, default 3
  38046. * * sideOrientation optional and takes the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  38047. * * 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)
  38048. * * 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)
  38049. * @returns the VertexData of the Torus Knot
  38050. */
  38051. VertexData.CreateTorusKnot = function (options) {
  38052. var indices = new Array();
  38053. var positions = new Array();
  38054. var normals = new Array();
  38055. var uvs = new Array();
  38056. var radius = options.radius || 2;
  38057. var tube = options.tube || 0.5;
  38058. var radialSegments = options.radialSegments || 32;
  38059. var tubularSegments = options.tubularSegments || 32;
  38060. var p = options.p || 2;
  38061. var q = options.q || 3;
  38062. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  38063. // Helper
  38064. var getPos = function (angle) {
  38065. var cu = Math.cos(angle);
  38066. var su = Math.sin(angle);
  38067. var quOverP = q / p * angle;
  38068. var cs = Math.cos(quOverP);
  38069. var tx = radius * (2 + cs) * 0.5 * cu;
  38070. var ty = radius * (2 + cs) * su * 0.5;
  38071. var tz = radius * Math.sin(quOverP) * 0.5;
  38072. return new BABYLON.Vector3(tx, ty, tz);
  38073. };
  38074. // Vertices
  38075. var i;
  38076. var j;
  38077. for (i = 0; i <= radialSegments; i++) {
  38078. var modI = i % radialSegments;
  38079. var u = modI / radialSegments * 2 * p * Math.PI;
  38080. var p1 = getPos(u);
  38081. var p2 = getPos(u + 0.01);
  38082. var tang = p2.subtract(p1);
  38083. var n = p2.add(p1);
  38084. var bitan = BABYLON.Vector3.Cross(tang, n);
  38085. n = BABYLON.Vector3.Cross(bitan, tang);
  38086. bitan.normalize();
  38087. n.normalize();
  38088. for (j = 0; j < tubularSegments; j++) {
  38089. var modJ = j % tubularSegments;
  38090. var v = modJ / tubularSegments * 2 * Math.PI;
  38091. var cx = -tube * Math.cos(v);
  38092. var cy = tube * Math.sin(v);
  38093. positions.push(p1.x + cx * n.x + cy * bitan.x);
  38094. positions.push(p1.y + cx * n.y + cy * bitan.y);
  38095. positions.push(p1.z + cx * n.z + cy * bitan.z);
  38096. uvs.push(i / radialSegments);
  38097. uvs.push(j / tubularSegments);
  38098. }
  38099. }
  38100. for (i = 0; i < radialSegments; i++) {
  38101. for (j = 0; j < tubularSegments; j++) {
  38102. var jNext = (j + 1) % tubularSegments;
  38103. var a = i * tubularSegments + j;
  38104. var b = (i + 1) * tubularSegments + j;
  38105. var c = (i + 1) * tubularSegments + jNext;
  38106. var d = i * tubularSegments + jNext;
  38107. indices.push(d);
  38108. indices.push(b);
  38109. indices.push(a);
  38110. indices.push(d);
  38111. indices.push(c);
  38112. indices.push(b);
  38113. }
  38114. }
  38115. // Normals
  38116. VertexData.ComputeNormals(positions, indices, normals);
  38117. // Sides
  38118. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  38119. // Result
  38120. var vertexData = new VertexData();
  38121. vertexData.indices = indices;
  38122. vertexData.positions = positions;
  38123. vertexData.normals = normals;
  38124. vertexData.uvs = uvs;
  38125. return vertexData;
  38126. };
  38127. // Tools
  38128. /**
  38129. * Compute normals for given positions and indices
  38130. * @param positions an array of vertex positions, [...., x, y, z, ......]
  38131. * @param indices an array of indices in groups of three for each triangular facet, [...., i, j, k, ......]
  38132. * @param normals an array of vertex normals, [...., x, y, z, ......]
  38133. * @param options an object used to set the following optional parameters for the TorusKnot, optional
  38134. * * facetNormals : optional array of facet normals (vector3)
  38135. * * facetPositions : optional array of facet positions (vector3)
  38136. * * facetPartitioning : optional partitioning array. facetPositions is required for facetPartitioning computation
  38137. * * ratio : optional partitioning ratio / bounding box, required for facetPartitioning computation
  38138. * * bInfo : optional bounding info, required for facetPartitioning computation
  38139. * * bbSize : optional bounding box size data, required for facetPartitioning computation
  38140. * * subDiv : optional partitioning data about subdivsions on each axis (int), required for facetPartitioning computation
  38141. * * useRightHandedSystem: optional boolean to for right handed system computation
  38142. * * depthSort : optional boolean to enable the facet depth sort computation
  38143. * * distanceTo : optional Vector3 to compute the facet depth from this location
  38144. * * depthSortedFacets : optional array of depthSortedFacets to store the facet distances from the reference location
  38145. */
  38146. VertexData.ComputeNormals = function (positions, indices, normals, options) {
  38147. // temporary scalar variables
  38148. var index = 0; // facet index
  38149. var p1p2x = 0.0; // p1p2 vector x coordinate
  38150. var p1p2y = 0.0; // p1p2 vector y coordinate
  38151. var p1p2z = 0.0; // p1p2 vector z coordinate
  38152. var p3p2x = 0.0; // p3p2 vector x coordinate
  38153. var p3p2y = 0.0; // p3p2 vector y coordinate
  38154. var p3p2z = 0.0; // p3p2 vector z coordinate
  38155. var faceNormalx = 0.0; // facet normal x coordinate
  38156. var faceNormaly = 0.0; // facet normal y coordinate
  38157. var faceNormalz = 0.0; // facet normal z coordinate
  38158. var length = 0.0; // facet normal length before normalization
  38159. var v1x = 0; // vector1 x index in the positions array
  38160. var v1y = 0; // vector1 y index in the positions array
  38161. var v1z = 0; // vector1 z index in the positions array
  38162. var v2x = 0; // vector2 x index in the positions array
  38163. var v2y = 0; // vector2 y index in the positions array
  38164. var v2z = 0; // vector2 z index in the positions array
  38165. var v3x = 0; // vector3 x index in the positions array
  38166. var v3y = 0; // vector3 y index in the positions array
  38167. var v3z = 0; // vector3 z index in the positions array
  38168. var computeFacetNormals = false;
  38169. var computeFacetPositions = false;
  38170. var computeFacetPartitioning = false;
  38171. var computeDepthSort = false;
  38172. var faceNormalSign = 1;
  38173. var ratio = 0;
  38174. var distanceTo = null;
  38175. if (options) {
  38176. computeFacetNormals = (options.facetNormals) ? true : false;
  38177. computeFacetPositions = (options.facetPositions) ? true : false;
  38178. computeFacetPartitioning = (options.facetPartitioning) ? true : false;
  38179. faceNormalSign = (options.useRightHandedSystem === true) ? -1 : 1;
  38180. ratio = options.ratio || 0;
  38181. computeDepthSort = (options.depthSort) ? true : false;
  38182. distanceTo = (options.distanceTo);
  38183. if (computeDepthSort) {
  38184. if (distanceTo === undefined) {
  38185. distanceTo = BABYLON.Vector3.Zero();
  38186. }
  38187. var depthSortedFacets = options.depthSortedFacets;
  38188. }
  38189. }
  38190. // facetPartitioning reinit if needed
  38191. var xSubRatio = 0;
  38192. var ySubRatio = 0;
  38193. var zSubRatio = 0;
  38194. var subSq = 0;
  38195. if (computeFacetPartitioning && options && options.bbSize) {
  38196. var ox = 0; // X partitioning index for facet position
  38197. var oy = 0; // Y partinioning index for facet position
  38198. var oz = 0; // Z partinioning index for facet position
  38199. var b1x = 0; // X partitioning index for facet v1 vertex
  38200. var b1y = 0; // Y partitioning index for facet v1 vertex
  38201. var b1z = 0; // z partitioning index for facet v1 vertex
  38202. var b2x = 0; // X partitioning index for facet v2 vertex
  38203. var b2y = 0; // Y partitioning index for facet v2 vertex
  38204. var b2z = 0; // Z partitioning index for facet v2 vertex
  38205. var b3x = 0; // X partitioning index for facet v3 vertex
  38206. var b3y = 0; // Y partitioning index for facet v3 vertex
  38207. var b3z = 0; // Z partitioning index for facet v3 vertex
  38208. var block_idx_o = 0; // facet barycenter block index
  38209. var block_idx_v1 = 0; // v1 vertex block index
  38210. var block_idx_v2 = 0; // v2 vertex block index
  38211. var block_idx_v3 = 0; // v3 vertex block index
  38212. var bbSizeMax = (options.bbSize.x > options.bbSize.y) ? options.bbSize.x : options.bbSize.y;
  38213. bbSizeMax = (bbSizeMax > options.bbSize.z) ? bbSizeMax : options.bbSize.z;
  38214. xSubRatio = options.subDiv.X * ratio / options.bbSize.x;
  38215. ySubRatio = options.subDiv.Y * ratio / options.bbSize.y;
  38216. zSubRatio = options.subDiv.Z * ratio / options.bbSize.z;
  38217. subSq = options.subDiv.max * options.subDiv.max;
  38218. options.facetPartitioning.length = 0;
  38219. }
  38220. // reset the normals
  38221. for (index = 0; index < positions.length; index++) {
  38222. normals[index] = 0.0;
  38223. }
  38224. // Loop : 1 indice triplet = 1 facet
  38225. var nbFaces = (indices.length / 3) | 0;
  38226. for (index = 0; index < nbFaces; index++) {
  38227. // get the indexes of the coordinates of each vertex of the facet
  38228. v1x = indices[index * 3] * 3;
  38229. v1y = v1x + 1;
  38230. v1z = v1x + 2;
  38231. v2x = indices[index * 3 + 1] * 3;
  38232. v2y = v2x + 1;
  38233. v2z = v2x + 2;
  38234. v3x = indices[index * 3 + 2] * 3;
  38235. v3y = v3x + 1;
  38236. v3z = v3x + 2;
  38237. p1p2x = positions[v1x] - positions[v2x]; // compute two vectors per facet : p1p2 and p3p2
  38238. p1p2y = positions[v1y] - positions[v2y];
  38239. p1p2z = positions[v1z] - positions[v2z];
  38240. p3p2x = positions[v3x] - positions[v2x];
  38241. p3p2y = positions[v3y] - positions[v2y];
  38242. p3p2z = positions[v3z] - positions[v2z];
  38243. // compute the face normal with the cross product
  38244. faceNormalx = faceNormalSign * (p1p2y * p3p2z - p1p2z * p3p2y);
  38245. faceNormaly = faceNormalSign * (p1p2z * p3p2x - p1p2x * p3p2z);
  38246. faceNormalz = faceNormalSign * (p1p2x * p3p2y - p1p2y * p3p2x);
  38247. // normalize this normal and store it in the array facetData
  38248. length = Math.sqrt(faceNormalx * faceNormalx + faceNormaly * faceNormaly + faceNormalz * faceNormalz);
  38249. length = (length === 0) ? 1.0 : length;
  38250. faceNormalx /= length;
  38251. faceNormaly /= length;
  38252. faceNormalz /= length;
  38253. if (computeFacetNormals && options) {
  38254. options.facetNormals[index].x = faceNormalx;
  38255. options.facetNormals[index].y = faceNormaly;
  38256. options.facetNormals[index].z = faceNormalz;
  38257. }
  38258. if (computeFacetPositions && options) {
  38259. // compute and the facet barycenter coordinates in the array facetPositions
  38260. options.facetPositions[index].x = (positions[v1x] + positions[v2x] + positions[v3x]) / 3.0;
  38261. options.facetPositions[index].y = (positions[v1y] + positions[v2y] + positions[v3y]) / 3.0;
  38262. options.facetPositions[index].z = (positions[v1z] + positions[v2z] + positions[v3z]) / 3.0;
  38263. }
  38264. if (computeFacetPartitioning && options) {
  38265. // store the facet indexes in arrays in the main facetPartitioning array :
  38266. // compute each facet vertex (+ facet barycenter) index in the partiniong array
  38267. ox = Math.floor((options.facetPositions[index].x - options.bInfo.minimum.x * ratio) * xSubRatio);
  38268. oy = Math.floor((options.facetPositions[index].y - options.bInfo.minimum.y * ratio) * ySubRatio);
  38269. oz = Math.floor((options.facetPositions[index].z - options.bInfo.minimum.z * ratio) * zSubRatio);
  38270. b1x = Math.floor((positions[v1x] - options.bInfo.minimum.x * ratio) * xSubRatio);
  38271. b1y = Math.floor((positions[v1y] - options.bInfo.minimum.y * ratio) * ySubRatio);
  38272. b1z = Math.floor((positions[v1z] - options.bInfo.minimum.z * ratio) * zSubRatio);
  38273. b2x = Math.floor((positions[v2x] - options.bInfo.minimum.x * ratio) * xSubRatio);
  38274. b2y = Math.floor((positions[v2y] - options.bInfo.minimum.y * ratio) * ySubRatio);
  38275. b2z = Math.floor((positions[v2z] - options.bInfo.minimum.z * ratio) * zSubRatio);
  38276. b3x = Math.floor((positions[v3x] - options.bInfo.minimum.x * ratio) * xSubRatio);
  38277. b3y = Math.floor((positions[v3y] - options.bInfo.minimum.y * ratio) * ySubRatio);
  38278. b3z = Math.floor((positions[v3z] - options.bInfo.minimum.z * ratio) * zSubRatio);
  38279. block_idx_v1 = b1x + options.subDiv.max * b1y + subSq * b1z;
  38280. block_idx_v2 = b2x + options.subDiv.max * b2y + subSq * b2z;
  38281. block_idx_v3 = b3x + options.subDiv.max * b3y + subSq * b3z;
  38282. block_idx_o = ox + options.subDiv.max * oy + subSq * oz;
  38283. options.facetPartitioning[block_idx_o] = options.facetPartitioning[block_idx_o] ? options.facetPartitioning[block_idx_o] : new Array();
  38284. options.facetPartitioning[block_idx_v1] = options.facetPartitioning[block_idx_v1] ? options.facetPartitioning[block_idx_v1] : new Array();
  38285. options.facetPartitioning[block_idx_v2] = options.facetPartitioning[block_idx_v2] ? options.facetPartitioning[block_idx_v2] : new Array();
  38286. options.facetPartitioning[block_idx_v3] = options.facetPartitioning[block_idx_v3] ? options.facetPartitioning[block_idx_v3] : new Array();
  38287. // push each facet index in each block containing the vertex
  38288. options.facetPartitioning[block_idx_v1].push(index);
  38289. if (block_idx_v2 != block_idx_v1) {
  38290. options.facetPartitioning[block_idx_v2].push(index);
  38291. }
  38292. if (!(block_idx_v3 == block_idx_v2 || block_idx_v3 == block_idx_v1)) {
  38293. options.facetPartitioning[block_idx_v3].push(index);
  38294. }
  38295. if (!(block_idx_o == block_idx_v1 || block_idx_o == block_idx_v2 || block_idx_o == block_idx_v3)) {
  38296. options.facetPartitioning[block_idx_o].push(index);
  38297. }
  38298. }
  38299. if (computeDepthSort && options && options.facetPositions) {
  38300. var dsf = depthSortedFacets[index];
  38301. dsf.ind = index * 3;
  38302. dsf.sqDistance = BABYLON.Vector3.DistanceSquared(options.facetPositions[index], distanceTo);
  38303. }
  38304. // compute the normals anyway
  38305. normals[v1x] += faceNormalx; // accumulate all the normals per face
  38306. normals[v1y] += faceNormaly;
  38307. normals[v1z] += faceNormalz;
  38308. normals[v2x] += faceNormalx;
  38309. normals[v2y] += faceNormaly;
  38310. normals[v2z] += faceNormalz;
  38311. normals[v3x] += faceNormalx;
  38312. normals[v3y] += faceNormaly;
  38313. normals[v3z] += faceNormalz;
  38314. }
  38315. // last normalization of each normal
  38316. for (index = 0; index < normals.length / 3; index++) {
  38317. faceNormalx = normals[index * 3];
  38318. faceNormaly = normals[index * 3 + 1];
  38319. faceNormalz = normals[index * 3 + 2];
  38320. length = Math.sqrt(faceNormalx * faceNormalx + faceNormaly * faceNormaly + faceNormalz * faceNormalz);
  38321. length = (length === 0) ? 1.0 : length;
  38322. faceNormalx /= length;
  38323. faceNormaly /= length;
  38324. faceNormalz /= length;
  38325. normals[index * 3] = faceNormalx;
  38326. normals[index * 3 + 1] = faceNormaly;
  38327. normals[index * 3 + 2] = faceNormalz;
  38328. }
  38329. };
  38330. VertexData._ComputeSides = function (sideOrientation, positions, indices, normals, uvs, frontUVs, backUVs) {
  38331. var li = indices.length;
  38332. var ln = normals.length;
  38333. var i;
  38334. var n;
  38335. sideOrientation = sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  38336. switch (sideOrientation) {
  38337. case BABYLON.Mesh.FRONTSIDE:
  38338. // nothing changed
  38339. break;
  38340. case BABYLON.Mesh.BACKSIDE:
  38341. var tmp;
  38342. // indices
  38343. for (i = 0; i < li; i += 3) {
  38344. tmp = indices[i];
  38345. indices[i] = indices[i + 2];
  38346. indices[i + 2] = tmp;
  38347. }
  38348. // normals
  38349. for (n = 0; n < ln; n++) {
  38350. normals[n] = -normals[n];
  38351. }
  38352. break;
  38353. case BABYLON.Mesh.DOUBLESIDE:
  38354. // positions
  38355. var lp = positions.length;
  38356. var l = lp / 3;
  38357. for (var p = 0; p < lp; p++) {
  38358. positions[lp + p] = positions[p];
  38359. }
  38360. // indices
  38361. for (i = 0; i < li; i += 3) {
  38362. indices[i + li] = indices[i + 2] + l;
  38363. indices[i + 1 + li] = indices[i + 1] + l;
  38364. indices[i + 2 + li] = indices[i] + l;
  38365. }
  38366. // normals
  38367. for (n = 0; n < ln; n++) {
  38368. normals[ln + n] = -normals[n];
  38369. }
  38370. // uvs
  38371. var lu = uvs.length;
  38372. var u = 0;
  38373. for (u = 0; u < lu; u++) {
  38374. uvs[u + lu] = uvs[u];
  38375. }
  38376. frontUVs = frontUVs ? frontUVs : new BABYLON.Vector4(0.0, 0.0, 1.0, 1.0);
  38377. backUVs = backUVs ? backUVs : new BABYLON.Vector4(0.0, 0.0, 1.0, 1.0);
  38378. u = 0;
  38379. for (i = 0; i < lu / 2; i++) {
  38380. uvs[u] = frontUVs.x + (frontUVs.z - frontUVs.x) * uvs[u];
  38381. uvs[u + 1] = frontUVs.y + (frontUVs.w - frontUVs.y) * uvs[u + 1];
  38382. uvs[u + lu] = backUVs.x + (backUVs.z - backUVs.x) * uvs[u + lu];
  38383. uvs[u + lu + 1] = backUVs.y + (backUVs.w - backUVs.y) * uvs[u + lu + 1];
  38384. u += 2;
  38385. }
  38386. break;
  38387. }
  38388. };
  38389. /**
  38390. * Applies VertexData created from the imported parameters to the geometry
  38391. * @param parsedVertexData the parsed data from an imported file
  38392. * @param geometry the geometry to apply the VertexData to
  38393. */
  38394. VertexData.ImportVertexData = function (parsedVertexData, geometry) {
  38395. var vertexData = new VertexData();
  38396. // positions
  38397. var positions = parsedVertexData.positions;
  38398. if (positions) {
  38399. vertexData.set(positions, BABYLON.VertexBuffer.PositionKind);
  38400. }
  38401. // normals
  38402. var normals = parsedVertexData.normals;
  38403. if (normals) {
  38404. vertexData.set(normals, BABYLON.VertexBuffer.NormalKind);
  38405. }
  38406. // tangents
  38407. var tangents = parsedVertexData.tangents;
  38408. if (tangents) {
  38409. vertexData.set(tangents, BABYLON.VertexBuffer.TangentKind);
  38410. }
  38411. // uvs
  38412. var uvs = parsedVertexData.uvs;
  38413. if (uvs) {
  38414. vertexData.set(uvs, BABYLON.VertexBuffer.UVKind);
  38415. }
  38416. // uv2s
  38417. var uv2s = parsedVertexData.uv2s;
  38418. if (uv2s) {
  38419. vertexData.set(uv2s, BABYLON.VertexBuffer.UV2Kind);
  38420. }
  38421. // uv3s
  38422. var uv3s = parsedVertexData.uv3s;
  38423. if (uv3s) {
  38424. vertexData.set(uv3s, BABYLON.VertexBuffer.UV3Kind);
  38425. }
  38426. // uv4s
  38427. var uv4s = parsedVertexData.uv4s;
  38428. if (uv4s) {
  38429. vertexData.set(uv4s, BABYLON.VertexBuffer.UV4Kind);
  38430. }
  38431. // uv5s
  38432. var uv5s = parsedVertexData.uv5s;
  38433. if (uv5s) {
  38434. vertexData.set(uv5s, BABYLON.VertexBuffer.UV5Kind);
  38435. }
  38436. // uv6s
  38437. var uv6s = parsedVertexData.uv6s;
  38438. if (uv6s) {
  38439. vertexData.set(uv6s, BABYLON.VertexBuffer.UV6Kind);
  38440. }
  38441. // colors
  38442. var colors = parsedVertexData.colors;
  38443. if (colors) {
  38444. vertexData.set(BABYLON.Color4.CheckColors4(colors, positions.length / 3), BABYLON.VertexBuffer.ColorKind);
  38445. }
  38446. // matricesIndices
  38447. var matricesIndices = parsedVertexData.matricesIndices;
  38448. if (matricesIndices) {
  38449. vertexData.set(matricesIndices, BABYLON.VertexBuffer.MatricesIndicesKind);
  38450. }
  38451. // matricesWeights
  38452. var matricesWeights = parsedVertexData.matricesWeights;
  38453. if (matricesWeights) {
  38454. vertexData.set(matricesWeights, BABYLON.VertexBuffer.MatricesWeightsKind);
  38455. }
  38456. // indices
  38457. var indices = parsedVertexData.indices;
  38458. if (indices) {
  38459. vertexData.indices = indices;
  38460. }
  38461. geometry.setAllVerticesData(vertexData, parsedVertexData.updatable);
  38462. };
  38463. return VertexData;
  38464. }());
  38465. BABYLON.VertexData = VertexData;
  38466. })(BABYLON || (BABYLON = {}));
  38467. //# sourceMappingURL=babylon.mesh.vertexData.js.map
  38468. var BABYLON;
  38469. (function (BABYLON) {
  38470. /**
  38471. * Class used to store geometry data (vertex buffers + index buffer)
  38472. */
  38473. var Geometry = /** @class */ (function () {
  38474. /**
  38475. * Creates a new geometry
  38476. * @param id defines the unique ID
  38477. * @param scene defines the hosting scene
  38478. * @param vertexData defines the {BABYLON.VertexData} used to get geometry data
  38479. * @param updatable defines if geometry must be updatable (false by default)
  38480. * @param mesh defines the mesh that will be associated with the geometry
  38481. */
  38482. function Geometry(id, scene, vertexData, updatable, mesh) {
  38483. if (updatable === void 0) { updatable = false; }
  38484. if (mesh === void 0) { mesh = null; }
  38485. /**
  38486. * Gets the delay loading state of the geometry (none by default which means not delayed)
  38487. */
  38488. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  38489. this._totalVertices = 0;
  38490. this._isDisposed = false;
  38491. this._indexBufferIsUpdatable = false;
  38492. this.id = id;
  38493. this._engine = scene.getEngine();
  38494. this._meshes = [];
  38495. this._scene = scene;
  38496. //Init vertex buffer cache
  38497. this._vertexBuffers = {};
  38498. this._indices = [];
  38499. this._updatable = updatable;
  38500. // vertexData
  38501. if (vertexData) {
  38502. this.setAllVerticesData(vertexData, updatable);
  38503. }
  38504. else {
  38505. this._totalVertices = 0;
  38506. this._indices = [];
  38507. }
  38508. if (this._engine.getCaps().vertexArrayObject) {
  38509. this._vertexArrayObjects = {};
  38510. }
  38511. // applyToMesh
  38512. if (mesh) {
  38513. if (mesh.getClassName() === "LinesMesh") {
  38514. this.boundingBias = new BABYLON.Vector2(0, mesh.intersectionThreshold);
  38515. this._updateExtend();
  38516. }
  38517. this.applyToMesh(mesh);
  38518. mesh.computeWorldMatrix(true);
  38519. }
  38520. }
  38521. Object.defineProperty(Geometry.prototype, "boundingBias", {
  38522. /**
  38523. * 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
  38524. */
  38525. get: function () {
  38526. return this._boundingBias;
  38527. },
  38528. /**
  38529. * 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
  38530. */
  38531. set: function (value) {
  38532. if (this._boundingBias && this._boundingBias.equals(value)) {
  38533. return;
  38534. }
  38535. this._boundingBias = value.clone();
  38536. this._updateBoundingInfo(true, null);
  38537. },
  38538. enumerable: true,
  38539. configurable: true
  38540. });
  38541. /**
  38542. * Static function used to attach a new empty geometry to a mesh
  38543. * @param mesh defines the mesh to attach the geometry to
  38544. * @returns the new {BABYLON.Geometry}
  38545. */
  38546. Geometry.CreateGeometryForMesh = function (mesh) {
  38547. var geometry = new Geometry(Geometry.RandomId(), mesh.getScene());
  38548. geometry.applyToMesh(mesh);
  38549. return geometry;
  38550. };
  38551. Object.defineProperty(Geometry.prototype, "extend", {
  38552. /**
  38553. * Gets the current extend of the geometry
  38554. */
  38555. get: function () {
  38556. return this._extend;
  38557. },
  38558. enumerable: true,
  38559. configurable: true
  38560. });
  38561. /**
  38562. * Gets the hosting scene
  38563. * @returns the hosting {BABYLON.Scene}
  38564. */
  38565. Geometry.prototype.getScene = function () {
  38566. return this._scene;
  38567. };
  38568. /**
  38569. * Gets the hosting engine
  38570. * @returns the hosting {BABYLON.Engine}
  38571. */
  38572. Geometry.prototype.getEngine = function () {
  38573. return this._engine;
  38574. };
  38575. /**
  38576. * Defines if the geometry is ready to use
  38577. * @returns true if the geometry is ready to be used
  38578. */
  38579. Geometry.prototype.isReady = function () {
  38580. return this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADED || this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NONE;
  38581. };
  38582. Object.defineProperty(Geometry.prototype, "doNotSerialize", {
  38583. /**
  38584. * Gets a value indicating that the geometry should not be serialized
  38585. */
  38586. get: function () {
  38587. for (var index = 0; index < this._meshes.length; index++) {
  38588. if (!this._meshes[index].doNotSerialize) {
  38589. return false;
  38590. }
  38591. }
  38592. return true;
  38593. },
  38594. enumerable: true,
  38595. configurable: true
  38596. });
  38597. /** @hidden */
  38598. Geometry.prototype._rebuild = function () {
  38599. if (this._vertexArrayObjects) {
  38600. this._vertexArrayObjects = {};
  38601. }
  38602. // Index buffer
  38603. if (this._meshes.length !== 0 && this._indices) {
  38604. this._indexBuffer = this._engine.createIndexBuffer(this._indices);
  38605. }
  38606. // Vertex buffers
  38607. for (var key in this._vertexBuffers) {
  38608. var vertexBuffer = this._vertexBuffers[key];
  38609. vertexBuffer._rebuild();
  38610. }
  38611. };
  38612. /**
  38613. * Affects all gemetry data in one call
  38614. * @param vertexData defines the geometry data
  38615. * @param updatable defines if the geometry must be flagged as updatable (false as default)
  38616. */
  38617. Geometry.prototype.setAllVerticesData = function (vertexData, updatable) {
  38618. vertexData.applyToGeometry(this, updatable);
  38619. this.notifyUpdate();
  38620. };
  38621. /**
  38622. * Set specific vertex data
  38623. * @param kind defines the data kind (Position, normal, etc...)
  38624. * @param data defines the vertex data to use
  38625. * @param updatable defines if the vertex must be flagged as updatable (false as default)
  38626. * @param stride defines the stride to use (0 by default). This value is deduced from the kind value if not specified
  38627. */
  38628. Geometry.prototype.setVerticesData = function (kind, data, updatable, stride) {
  38629. if (updatable === void 0) { updatable = false; }
  38630. var buffer = new BABYLON.VertexBuffer(this._engine, data, kind, updatable, this._meshes.length === 0, stride);
  38631. this.setVerticesBuffer(buffer);
  38632. };
  38633. /**
  38634. * Removes a specific vertex data
  38635. * @param kind defines the data kind (Position, normal, etc...)
  38636. */
  38637. Geometry.prototype.removeVerticesData = function (kind) {
  38638. if (this._vertexBuffers[kind]) {
  38639. this._vertexBuffers[kind].dispose();
  38640. delete this._vertexBuffers[kind];
  38641. }
  38642. };
  38643. /**
  38644. * Affect a vertex buffer to the geometry. the vertexBuffer.getKind() function is used to determine where to store the data
  38645. * @param buffer defines the vertex buffer to use
  38646. * @param totalVertices defines the total number of vertices for position kind (could be null)
  38647. */
  38648. Geometry.prototype.setVerticesBuffer = function (buffer, totalVertices) {
  38649. if (totalVertices === void 0) { totalVertices = null; }
  38650. var kind = buffer.getKind();
  38651. if (this._vertexBuffers[kind]) {
  38652. this._vertexBuffers[kind].dispose();
  38653. }
  38654. this._vertexBuffers[kind] = buffer;
  38655. if (kind === BABYLON.VertexBuffer.PositionKind) {
  38656. var data = buffer.getData();
  38657. if (totalVertices != null) {
  38658. this._totalVertices = totalVertices;
  38659. }
  38660. else {
  38661. if (data != null) {
  38662. this._totalVertices = data.length / (buffer.byteStride / 4);
  38663. }
  38664. }
  38665. this._updateExtend(data);
  38666. this._resetPointsArrayCache();
  38667. var meshes = this._meshes;
  38668. var numOfMeshes = meshes.length;
  38669. for (var index = 0; index < numOfMeshes; index++) {
  38670. var mesh = meshes[index];
  38671. mesh._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  38672. mesh._createGlobalSubMesh(false);
  38673. mesh.computeWorldMatrix(true);
  38674. }
  38675. }
  38676. this.notifyUpdate(kind);
  38677. if (this._vertexArrayObjects) {
  38678. this._disposeVertexArrayObjects();
  38679. this._vertexArrayObjects = {}; // Will trigger a rebuild of the VAO if supported
  38680. }
  38681. };
  38682. /**
  38683. * Update a specific vertex buffer
  38684. * This function will directly update the underlying WebGLBuffer according to the passed numeric array or Float32Array
  38685. * It will do nothing if the buffer is not updatable
  38686. * @param kind defines the data kind (Position, normal, etc...)
  38687. * @param data defines the data to use
  38688. * @param offset defines the offset in the target buffer where to store the data
  38689. * @param useBytes set to true if the offset is in bytes
  38690. */
  38691. Geometry.prototype.updateVerticesDataDirectly = function (kind, data, offset, useBytes) {
  38692. if (useBytes === void 0) { useBytes = false; }
  38693. var vertexBuffer = this.getVertexBuffer(kind);
  38694. if (!vertexBuffer) {
  38695. return;
  38696. }
  38697. vertexBuffer.updateDirectly(data, offset, useBytes);
  38698. this.notifyUpdate(kind);
  38699. };
  38700. /**
  38701. * Update a specific vertex buffer
  38702. * This function will create a new buffer if the current one is not updatable
  38703. * @param kind defines the data kind (Position, normal, etc...)
  38704. * @param data defines the data to use
  38705. * @param updateExtends defines if the geometry extends must be recomputed (false by default)
  38706. */
  38707. Geometry.prototype.updateVerticesData = function (kind, data, updateExtends) {
  38708. if (updateExtends === void 0) { updateExtends = false; }
  38709. var vertexBuffer = this.getVertexBuffer(kind);
  38710. if (!vertexBuffer) {
  38711. return;
  38712. }
  38713. vertexBuffer.update(data);
  38714. if (kind === BABYLON.VertexBuffer.PositionKind) {
  38715. this._updateBoundingInfo(updateExtends, data);
  38716. }
  38717. this.notifyUpdate(kind);
  38718. };
  38719. Geometry.prototype._updateBoundingInfo = function (updateExtends, data) {
  38720. if (updateExtends) {
  38721. this._updateExtend(data);
  38722. }
  38723. var meshes = this._meshes;
  38724. var numOfMeshes = meshes.length;
  38725. this._resetPointsArrayCache();
  38726. for (var index = 0; index < numOfMeshes; index++) {
  38727. var mesh = meshes[index];
  38728. if (updateExtends) {
  38729. mesh._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  38730. for (var subIndex = 0; subIndex < mesh.subMeshes.length; subIndex++) {
  38731. var subMesh = mesh.subMeshes[subIndex];
  38732. subMesh.refreshBoundingInfo();
  38733. }
  38734. }
  38735. }
  38736. };
  38737. /** @hidden */
  38738. Geometry.prototype._bind = function (effect, indexToBind) {
  38739. if (!effect) {
  38740. return;
  38741. }
  38742. if (indexToBind === undefined) {
  38743. indexToBind = this._indexBuffer;
  38744. }
  38745. var vbs = this.getVertexBuffers();
  38746. if (!vbs) {
  38747. return;
  38748. }
  38749. if (indexToBind != this._indexBuffer || !this._vertexArrayObjects) {
  38750. this._engine.bindBuffers(vbs, indexToBind, effect);
  38751. return;
  38752. }
  38753. // Using VAO
  38754. if (!this._vertexArrayObjects[effect.key]) {
  38755. this._vertexArrayObjects[effect.key] = this._engine.recordVertexArrayObject(vbs, indexToBind, effect);
  38756. }
  38757. this._engine.bindVertexArrayObject(this._vertexArrayObjects[effect.key], indexToBind);
  38758. };
  38759. /**
  38760. * Gets total number of vertices
  38761. * @returns the total number of vertices
  38762. */
  38763. Geometry.prototype.getTotalVertices = function () {
  38764. if (!this.isReady()) {
  38765. return 0;
  38766. }
  38767. return this._totalVertices;
  38768. };
  38769. /**
  38770. * Gets a specific vertex data attached to this geometry. Float data is constructed if the vertex buffer data cannot be returned directly.
  38771. * @param kind defines the data kind (Position, normal, etc...)
  38772. * @param copyWhenShared defines if the returned array must be cloned upon returning it if the current geometry is shared between multiple meshes
  38773. * @param forceCopy defines a boolean indicating that the returned array must be cloned upon returning it
  38774. * @returns a float array containing vertex data
  38775. */
  38776. Geometry.prototype.getVerticesData = function (kind, copyWhenShared, forceCopy) {
  38777. var vertexBuffer = this.getVertexBuffer(kind);
  38778. if (!vertexBuffer) {
  38779. return null;
  38780. }
  38781. var data = vertexBuffer.getData();
  38782. if (!data) {
  38783. return null;
  38784. }
  38785. var defaultStride = BABYLON.VertexBuffer.DeduceStride(vertexBuffer.getKind());
  38786. var defaultByteStride = defaultStride * BABYLON.VertexBuffer.GetTypeByteLength(vertexBuffer.type);
  38787. var count = this._totalVertices * defaultStride;
  38788. if (vertexBuffer.type !== BABYLON.VertexBuffer.FLOAT || vertexBuffer.byteStride !== defaultByteStride) {
  38789. var copy_1 = new Array(count);
  38790. vertexBuffer.forEach(count, function (value, index) {
  38791. copy_1[index] = value;
  38792. });
  38793. return copy_1;
  38794. }
  38795. if (!(data instanceof Array || data instanceof Float32Array) || vertexBuffer.byteOffset !== 0 || data.length !== count) {
  38796. if (data instanceof Array) {
  38797. var offset = vertexBuffer.byteOffset / 4;
  38798. return BABYLON.Tools.Slice(data, offset, offset + count);
  38799. }
  38800. else if (data instanceof ArrayBuffer) {
  38801. return new Float32Array(data, vertexBuffer.byteOffset, count);
  38802. }
  38803. else {
  38804. return new Float32Array(data.buffer, data.byteOffset + vertexBuffer.byteOffset, count);
  38805. }
  38806. }
  38807. if (forceCopy || (copyWhenShared && this._meshes.length !== 1)) {
  38808. return BABYLON.Tools.Slice(data);
  38809. }
  38810. return data;
  38811. };
  38812. /**
  38813. * Returns a boolean defining if the vertex data for the requested `kind` is updatable
  38814. * @param kind defines the data kind (Position, normal, etc...)
  38815. * @returns true if the vertex buffer with the specified kind is updatable
  38816. */
  38817. Geometry.prototype.isVertexBufferUpdatable = function (kind) {
  38818. var vb = this._vertexBuffers[kind];
  38819. if (!vb) {
  38820. return false;
  38821. }
  38822. return vb.isUpdatable();
  38823. };
  38824. /**
  38825. * Gets a specific vertex buffer
  38826. * @param kind defines the data kind (Position, normal, etc...)
  38827. * @returns a {BABYLON.VertexBuffer}
  38828. */
  38829. Geometry.prototype.getVertexBuffer = function (kind) {
  38830. if (!this.isReady()) {
  38831. return null;
  38832. }
  38833. return this._vertexBuffers[kind];
  38834. };
  38835. /**
  38836. * Returns all vertex buffers
  38837. * @return an object holding all vertex buffers indexed by kind
  38838. */
  38839. Geometry.prototype.getVertexBuffers = function () {
  38840. if (!this.isReady()) {
  38841. return null;
  38842. }
  38843. return this._vertexBuffers;
  38844. };
  38845. /**
  38846. * Gets a boolean indicating if specific vertex buffer is present
  38847. * @param kind defines the data kind (Position, normal, etc...)
  38848. * @returns true if data is present
  38849. */
  38850. Geometry.prototype.isVerticesDataPresent = function (kind) {
  38851. if (!this._vertexBuffers) {
  38852. if (this._delayInfo) {
  38853. return this._delayInfo.indexOf(kind) !== -1;
  38854. }
  38855. return false;
  38856. }
  38857. return this._vertexBuffers[kind] !== undefined;
  38858. };
  38859. /**
  38860. * Gets a list of all attached data kinds (Position, normal, etc...)
  38861. * @returns a list of string containing all kinds
  38862. */
  38863. Geometry.prototype.getVerticesDataKinds = function () {
  38864. var result = [];
  38865. var kind;
  38866. if (!this._vertexBuffers && this._delayInfo) {
  38867. for (kind in this._delayInfo) {
  38868. result.push(kind);
  38869. }
  38870. }
  38871. else {
  38872. for (kind in this._vertexBuffers) {
  38873. result.push(kind);
  38874. }
  38875. }
  38876. return result;
  38877. };
  38878. /**
  38879. * Update index buffer
  38880. * @param indices defines the indices to store in the index buffer
  38881. * @param offset defines the offset in the target buffer where to store the data
  38882. */
  38883. Geometry.prototype.updateIndices = function (indices, offset) {
  38884. if (!this._indexBuffer) {
  38885. return;
  38886. }
  38887. if (!this._indexBufferIsUpdatable) {
  38888. this.setIndices(indices, null, true);
  38889. }
  38890. else {
  38891. this._engine.updateDynamicIndexBuffer(this._indexBuffer, indices, offset);
  38892. }
  38893. };
  38894. /**
  38895. * Creates a new index buffer
  38896. * @param indices defines the indices to store in the index buffer
  38897. * @param totalVertices defines the total number of vertices (could be null)
  38898. * @param updatable defines if the index buffer must be flagged as updatable (false by default)
  38899. */
  38900. Geometry.prototype.setIndices = function (indices, totalVertices, updatable) {
  38901. if (totalVertices === void 0) { totalVertices = null; }
  38902. if (updatable === void 0) { updatable = false; }
  38903. if (this._indexBuffer) {
  38904. this._engine._releaseBuffer(this._indexBuffer);
  38905. }
  38906. this._disposeVertexArrayObjects();
  38907. this._indices = indices;
  38908. this._indexBufferIsUpdatable = updatable;
  38909. if (this._meshes.length !== 0 && this._indices) {
  38910. this._indexBuffer = this._engine.createIndexBuffer(this._indices, updatable);
  38911. }
  38912. if (totalVertices != undefined) { // including null and undefined
  38913. this._totalVertices = totalVertices;
  38914. }
  38915. var meshes = this._meshes;
  38916. var numOfMeshes = meshes.length;
  38917. for (var index = 0; index < numOfMeshes; index++) {
  38918. meshes[index]._createGlobalSubMesh(true);
  38919. }
  38920. this.notifyUpdate();
  38921. };
  38922. /**
  38923. * Return the total number of indices
  38924. * @returns the total number of indices
  38925. */
  38926. Geometry.prototype.getTotalIndices = function () {
  38927. if (!this.isReady()) {
  38928. return 0;
  38929. }
  38930. return this._indices.length;
  38931. };
  38932. /**
  38933. * Gets the index buffer array
  38934. * @param copyWhenShared defines if the returned array must be cloned upon returning it if the current geometry is shared between multiple meshes
  38935. * @returns the index buffer array
  38936. */
  38937. Geometry.prototype.getIndices = function (copyWhenShared) {
  38938. if (!this.isReady()) {
  38939. return null;
  38940. }
  38941. var orig = this._indices;
  38942. if (!copyWhenShared || this._meshes.length === 1) {
  38943. return orig;
  38944. }
  38945. else {
  38946. var len = orig.length;
  38947. var copy = [];
  38948. for (var i = 0; i < len; i++) {
  38949. copy.push(orig[i]);
  38950. }
  38951. return copy;
  38952. }
  38953. };
  38954. /**
  38955. * Gets the index buffer
  38956. * @return the index buffer
  38957. */
  38958. Geometry.prototype.getIndexBuffer = function () {
  38959. if (!this.isReady()) {
  38960. return null;
  38961. }
  38962. return this._indexBuffer;
  38963. };
  38964. /** @hidden */
  38965. Geometry.prototype._releaseVertexArrayObject = function (effect) {
  38966. if (effect === void 0) { effect = null; }
  38967. if (!effect || !this._vertexArrayObjects) {
  38968. return;
  38969. }
  38970. if (this._vertexArrayObjects[effect.key]) {
  38971. this._engine.releaseVertexArrayObject(this._vertexArrayObjects[effect.key]);
  38972. delete this._vertexArrayObjects[effect.key];
  38973. }
  38974. };
  38975. /**
  38976. * Release the associated resources for a specific mesh
  38977. * @param mesh defines the source mesh
  38978. * @param shouldDispose defines if the geometry must be disposed if there is no more mesh pointing to it
  38979. */
  38980. Geometry.prototype.releaseForMesh = function (mesh, shouldDispose) {
  38981. var meshes = this._meshes;
  38982. var index = meshes.indexOf(mesh);
  38983. if (index === -1) {
  38984. return;
  38985. }
  38986. meshes.splice(index, 1);
  38987. mesh._geometry = null;
  38988. if (meshes.length === 0 && shouldDispose) {
  38989. this.dispose();
  38990. }
  38991. };
  38992. /**
  38993. * Apply current geometry to a given mesh
  38994. * @param mesh defines the mesh to apply geometry to
  38995. */
  38996. Geometry.prototype.applyToMesh = function (mesh) {
  38997. if (mesh._geometry === this) {
  38998. return;
  38999. }
  39000. var previousGeometry = mesh._geometry;
  39001. if (previousGeometry) {
  39002. previousGeometry.releaseForMesh(mesh);
  39003. }
  39004. var meshes = this._meshes;
  39005. // must be done before setting vertexBuffers because of mesh._createGlobalSubMesh()
  39006. mesh._geometry = this;
  39007. this._scene.pushGeometry(this);
  39008. meshes.push(mesh);
  39009. if (this.isReady()) {
  39010. this._applyToMesh(mesh);
  39011. }
  39012. else {
  39013. mesh._boundingInfo = this._boundingInfo;
  39014. }
  39015. };
  39016. Geometry.prototype._updateExtend = function (data) {
  39017. if (data === void 0) { data = null; }
  39018. if (!data) {
  39019. data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  39020. }
  39021. this._extend = BABYLON.Tools.ExtractMinAndMax(data, 0, this._totalVertices, this.boundingBias, 3);
  39022. };
  39023. Geometry.prototype._applyToMesh = function (mesh) {
  39024. var numOfMeshes = this._meshes.length;
  39025. // vertexBuffers
  39026. for (var kind in this._vertexBuffers) {
  39027. if (numOfMeshes === 1) {
  39028. this._vertexBuffers[kind].create();
  39029. }
  39030. var buffer = this._vertexBuffers[kind].getBuffer();
  39031. if (buffer)
  39032. buffer.references = numOfMeshes;
  39033. if (kind === BABYLON.VertexBuffer.PositionKind) {
  39034. if (!this._extend) {
  39035. this._updateExtend();
  39036. }
  39037. mesh._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  39038. mesh._createGlobalSubMesh(false);
  39039. //bounding info was just created again, world matrix should be applied again.
  39040. mesh._updateBoundingInfo();
  39041. }
  39042. }
  39043. // indexBuffer
  39044. if (numOfMeshes === 1 && this._indices && this._indices.length > 0) {
  39045. this._indexBuffer = this._engine.createIndexBuffer(this._indices);
  39046. }
  39047. if (this._indexBuffer) {
  39048. this._indexBuffer.references = numOfMeshes;
  39049. }
  39050. };
  39051. Geometry.prototype.notifyUpdate = function (kind) {
  39052. if (this.onGeometryUpdated) {
  39053. this.onGeometryUpdated(this, kind);
  39054. }
  39055. for (var _i = 0, _a = this._meshes; _i < _a.length; _i++) {
  39056. var mesh = _a[_i];
  39057. mesh._markSubMeshesAsAttributesDirty();
  39058. }
  39059. };
  39060. /**
  39061. * Load the geometry if it was flagged as delay loaded
  39062. * @param scene defines the hosting scene
  39063. * @param onLoaded defines a callback called when the geometry is loaded
  39064. */
  39065. Geometry.prototype.load = function (scene, onLoaded) {
  39066. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  39067. return;
  39068. }
  39069. if (this.isReady()) {
  39070. if (onLoaded) {
  39071. onLoaded();
  39072. }
  39073. return;
  39074. }
  39075. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADING;
  39076. this._queueLoad(scene, onLoaded);
  39077. };
  39078. Geometry.prototype._queueLoad = function (scene, onLoaded) {
  39079. var _this = this;
  39080. if (!this.delayLoadingFile) {
  39081. return;
  39082. }
  39083. scene._addPendingData(this);
  39084. scene._loadFile(this.delayLoadingFile, function (data) {
  39085. if (!_this._delayLoadingFunction) {
  39086. return;
  39087. }
  39088. _this._delayLoadingFunction(JSON.parse(data), _this);
  39089. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  39090. _this._delayInfo = [];
  39091. scene._removePendingData(_this);
  39092. var meshes = _this._meshes;
  39093. var numOfMeshes = meshes.length;
  39094. for (var index = 0; index < numOfMeshes; index++) {
  39095. _this._applyToMesh(meshes[index]);
  39096. }
  39097. if (onLoaded) {
  39098. onLoaded();
  39099. }
  39100. }, undefined, true);
  39101. };
  39102. /**
  39103. * Invert the geometry to move from a right handed system to a left handed one.
  39104. */
  39105. Geometry.prototype.toLeftHanded = function () {
  39106. // Flip faces
  39107. var tIndices = this.getIndices(false);
  39108. if (tIndices != null && tIndices.length > 0) {
  39109. for (var i = 0; i < tIndices.length; i += 3) {
  39110. var tTemp = tIndices[i + 0];
  39111. tIndices[i + 0] = tIndices[i + 2];
  39112. tIndices[i + 2] = tTemp;
  39113. }
  39114. this.setIndices(tIndices);
  39115. }
  39116. // Negate position.z
  39117. var tPositions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind, false);
  39118. if (tPositions != null && tPositions.length > 0) {
  39119. for (var i = 0; i < tPositions.length; i += 3) {
  39120. tPositions[i + 2] = -tPositions[i + 2];
  39121. }
  39122. this.setVerticesData(BABYLON.VertexBuffer.PositionKind, tPositions, false);
  39123. }
  39124. // Negate normal.z
  39125. var tNormals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind, false);
  39126. if (tNormals != null && tNormals.length > 0) {
  39127. for (var i = 0; i < tNormals.length; i += 3) {
  39128. tNormals[i + 2] = -tNormals[i + 2];
  39129. }
  39130. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, tNormals, false);
  39131. }
  39132. };
  39133. // Cache
  39134. /** @hidden */
  39135. Geometry.prototype._resetPointsArrayCache = function () {
  39136. this._positions = null;
  39137. };
  39138. /** @hidden */
  39139. Geometry.prototype._generatePointsArray = function () {
  39140. if (this._positions)
  39141. return true;
  39142. this._positions = [];
  39143. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  39144. if (!data) {
  39145. return false;
  39146. }
  39147. for (var index = 0; index < data.length; index += 3) {
  39148. this._positions.push(BABYLON.Vector3.FromArray(data, index));
  39149. }
  39150. return true;
  39151. };
  39152. /**
  39153. * Gets a value indicating if the geometry is disposed
  39154. * @returns true if the geometry was disposed
  39155. */
  39156. Geometry.prototype.isDisposed = function () {
  39157. return this._isDisposed;
  39158. };
  39159. Geometry.prototype._disposeVertexArrayObjects = function () {
  39160. if (this._vertexArrayObjects) {
  39161. for (var kind in this._vertexArrayObjects) {
  39162. this._engine.releaseVertexArrayObject(this._vertexArrayObjects[kind]);
  39163. }
  39164. this._vertexArrayObjects = {};
  39165. }
  39166. };
  39167. /**
  39168. * Free all associated resources
  39169. */
  39170. Geometry.prototype.dispose = function () {
  39171. var meshes = this._meshes;
  39172. var numOfMeshes = meshes.length;
  39173. var index;
  39174. for (index = 0; index < numOfMeshes; index++) {
  39175. this.releaseForMesh(meshes[index]);
  39176. }
  39177. this._meshes = [];
  39178. this._disposeVertexArrayObjects();
  39179. for (var kind in this._vertexBuffers) {
  39180. this._vertexBuffers[kind].dispose();
  39181. }
  39182. this._vertexBuffers = {};
  39183. this._totalVertices = 0;
  39184. if (this._indexBuffer) {
  39185. this._engine._releaseBuffer(this._indexBuffer);
  39186. }
  39187. this._indexBuffer = null;
  39188. this._indices = [];
  39189. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  39190. this.delayLoadingFile = null;
  39191. this._delayLoadingFunction = null;
  39192. this._delayInfo = [];
  39193. this._boundingInfo = null;
  39194. this._scene.removeGeometry(this);
  39195. this._isDisposed = true;
  39196. };
  39197. /**
  39198. * Clone the current geometry into a new geometry
  39199. * @param id defines the unique ID of the new geometry
  39200. * @returns a new geometry object
  39201. */
  39202. Geometry.prototype.copy = function (id) {
  39203. var vertexData = new BABYLON.VertexData();
  39204. vertexData.indices = [];
  39205. var indices = this.getIndices();
  39206. if (indices) {
  39207. for (var index = 0; index < indices.length; index++) {
  39208. vertexData.indices.push(indices[index]);
  39209. }
  39210. }
  39211. var updatable = false;
  39212. var stopChecking = false;
  39213. var kind;
  39214. for (kind in this._vertexBuffers) {
  39215. // using slice() to make a copy of the array and not just reference it
  39216. var data = this.getVerticesData(kind);
  39217. if (data instanceof Float32Array) {
  39218. vertexData.set(new Float32Array(data), kind);
  39219. }
  39220. else {
  39221. vertexData.set(data.slice(0), kind);
  39222. }
  39223. if (!stopChecking) {
  39224. var vb = this.getVertexBuffer(kind);
  39225. if (vb) {
  39226. updatable = vb.isUpdatable();
  39227. stopChecking = !updatable;
  39228. }
  39229. }
  39230. }
  39231. var geometry = new Geometry(id, this._scene, vertexData, updatable);
  39232. geometry.delayLoadState = this.delayLoadState;
  39233. geometry.delayLoadingFile = this.delayLoadingFile;
  39234. geometry._delayLoadingFunction = this._delayLoadingFunction;
  39235. for (kind in this._delayInfo) {
  39236. geometry._delayInfo = geometry._delayInfo || [];
  39237. geometry._delayInfo.push(kind);
  39238. }
  39239. // Bounding info
  39240. geometry._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  39241. return geometry;
  39242. };
  39243. /**
  39244. * Serialize the current geometry info (and not the vertices data) into a JSON object
  39245. * @return a JSON representation of the current geometry data (without the vertices data)
  39246. */
  39247. Geometry.prototype.serialize = function () {
  39248. var serializationObject = {};
  39249. serializationObject.id = this.id;
  39250. serializationObject.updatable = this._updatable;
  39251. if (BABYLON.Tags && BABYLON.Tags.HasTags(this)) {
  39252. serializationObject.tags = BABYLON.Tags.GetTags(this);
  39253. }
  39254. return serializationObject;
  39255. };
  39256. Geometry.prototype.toNumberArray = function (origin) {
  39257. if (Array.isArray(origin)) {
  39258. return origin;
  39259. }
  39260. else {
  39261. return Array.prototype.slice.call(origin);
  39262. }
  39263. };
  39264. /**
  39265. * Serialize all vertices data into a JSON oject
  39266. * @returns a JSON representation of the current geometry data
  39267. */
  39268. Geometry.prototype.serializeVerticeData = function () {
  39269. var serializationObject = this.serialize();
  39270. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  39271. serializationObject.positions = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.PositionKind));
  39272. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.PositionKind)) {
  39273. serializationObject.positions._updatable = true;
  39274. }
  39275. }
  39276. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  39277. serializationObject.normals = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.NormalKind));
  39278. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.NormalKind)) {
  39279. serializationObject.normals._updatable = true;
  39280. }
  39281. }
  39282. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind)) {
  39283. serializationObject.tangets = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.TangentKind));
  39284. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.TangentKind)) {
  39285. serializationObject.tangets._updatable = true;
  39286. }
  39287. }
  39288. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  39289. serializationObject.uvs = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UVKind));
  39290. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UVKind)) {
  39291. serializationObject.uvs._updatable = true;
  39292. }
  39293. }
  39294. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  39295. serializationObject.uv2s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV2Kind));
  39296. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UV2Kind)) {
  39297. serializationObject.uv2s._updatable = true;
  39298. }
  39299. }
  39300. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV3Kind)) {
  39301. serializationObject.uv3s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV3Kind));
  39302. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UV3Kind)) {
  39303. serializationObject.uv3s._updatable = true;
  39304. }
  39305. }
  39306. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV4Kind)) {
  39307. serializationObject.uv4s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV4Kind));
  39308. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UV4Kind)) {
  39309. serializationObject.uv4s._updatable = true;
  39310. }
  39311. }
  39312. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV5Kind)) {
  39313. serializationObject.uv5s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV5Kind));
  39314. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UV5Kind)) {
  39315. serializationObject.uv5s._updatable = true;
  39316. }
  39317. }
  39318. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV6Kind)) {
  39319. serializationObject.uv6s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV6Kind));
  39320. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UV6Kind)) {
  39321. serializationObject.uv6s._updatable = true;
  39322. }
  39323. }
  39324. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  39325. serializationObject.colors = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.ColorKind));
  39326. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.ColorKind)) {
  39327. serializationObject.colors._updatable = true;
  39328. }
  39329. }
  39330. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  39331. serializationObject.matricesIndices = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind));
  39332. serializationObject.matricesIndices._isExpanded = true;
  39333. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  39334. serializationObject.matricesIndices._updatable = true;
  39335. }
  39336. }
  39337. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  39338. serializationObject.matricesWeights = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind));
  39339. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  39340. serializationObject.matricesWeights._updatable = true;
  39341. }
  39342. }
  39343. serializationObject.indices = this.toNumberArray(this.getIndices());
  39344. return serializationObject;
  39345. };
  39346. // Statics
  39347. /**
  39348. * Extracts a clone of a mesh geometry
  39349. * @param mesh defines the source mesh
  39350. * @param id defines the unique ID of the new geometry object
  39351. * @returns the new geometry object
  39352. */
  39353. Geometry.ExtractFromMesh = function (mesh, id) {
  39354. var geometry = mesh._geometry;
  39355. if (!geometry) {
  39356. return null;
  39357. }
  39358. return geometry.copy(id);
  39359. };
  39360. /**
  39361. * You should now use Tools.RandomId(), this method is still here for legacy reasons.
  39362. * Implementation from http://stackoverflow.com/questions/105034/how-to-create-a-guid-uuid-in-javascript/2117523#answer-2117523
  39363. * Be aware Math.random() could cause collisions, but:
  39364. * "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"
  39365. * @returns a string containing a new GUID
  39366. */
  39367. Geometry.RandomId = function () {
  39368. return BABYLON.Tools.RandomId();
  39369. };
  39370. /** @hidden */
  39371. Geometry._ImportGeometry = function (parsedGeometry, mesh) {
  39372. var scene = mesh.getScene();
  39373. // Geometry
  39374. var geometryId = parsedGeometry.geometryId;
  39375. if (geometryId) {
  39376. var geometry = scene.getGeometryByID(geometryId);
  39377. if (geometry) {
  39378. geometry.applyToMesh(mesh);
  39379. }
  39380. }
  39381. else if (parsedGeometry instanceof ArrayBuffer) {
  39382. var binaryInfo = mesh._binaryInfo;
  39383. if (binaryInfo.positionsAttrDesc && binaryInfo.positionsAttrDesc.count > 0) {
  39384. var positionsData = new Float32Array(parsedGeometry, binaryInfo.positionsAttrDesc.offset, binaryInfo.positionsAttrDesc.count);
  39385. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, positionsData, false);
  39386. }
  39387. if (binaryInfo.normalsAttrDesc && binaryInfo.normalsAttrDesc.count > 0) {
  39388. var normalsData = new Float32Array(parsedGeometry, binaryInfo.normalsAttrDesc.offset, binaryInfo.normalsAttrDesc.count);
  39389. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, normalsData, false);
  39390. }
  39391. if (binaryInfo.tangetsAttrDesc && binaryInfo.tangetsAttrDesc.count > 0) {
  39392. var tangentsData = new Float32Array(parsedGeometry, binaryInfo.tangetsAttrDesc.offset, binaryInfo.tangetsAttrDesc.count);
  39393. mesh.setVerticesData(BABYLON.VertexBuffer.TangentKind, tangentsData, false);
  39394. }
  39395. if (binaryInfo.uvsAttrDesc && binaryInfo.uvsAttrDesc.count > 0) {
  39396. var uvsData = new Float32Array(parsedGeometry, binaryInfo.uvsAttrDesc.offset, binaryInfo.uvsAttrDesc.count);
  39397. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, uvsData, false);
  39398. }
  39399. if (binaryInfo.uvs2AttrDesc && binaryInfo.uvs2AttrDesc.count > 0) {
  39400. var uvs2Data = new Float32Array(parsedGeometry, binaryInfo.uvs2AttrDesc.offset, binaryInfo.uvs2AttrDesc.count);
  39401. mesh.setVerticesData(BABYLON.VertexBuffer.UV2Kind, uvs2Data, false);
  39402. }
  39403. if (binaryInfo.uvs3AttrDesc && binaryInfo.uvs3AttrDesc.count > 0) {
  39404. var uvs3Data = new Float32Array(parsedGeometry, binaryInfo.uvs3AttrDesc.offset, binaryInfo.uvs3AttrDesc.count);
  39405. mesh.setVerticesData(BABYLON.VertexBuffer.UV3Kind, uvs3Data, false);
  39406. }
  39407. if (binaryInfo.uvs4AttrDesc && binaryInfo.uvs4AttrDesc.count > 0) {
  39408. var uvs4Data = new Float32Array(parsedGeometry, binaryInfo.uvs4AttrDesc.offset, binaryInfo.uvs4AttrDesc.count);
  39409. mesh.setVerticesData(BABYLON.VertexBuffer.UV4Kind, uvs4Data, false);
  39410. }
  39411. if (binaryInfo.uvs5AttrDesc && binaryInfo.uvs5AttrDesc.count > 0) {
  39412. var uvs5Data = new Float32Array(parsedGeometry, binaryInfo.uvs5AttrDesc.offset, binaryInfo.uvs5AttrDesc.count);
  39413. mesh.setVerticesData(BABYLON.VertexBuffer.UV5Kind, uvs5Data, false);
  39414. }
  39415. if (binaryInfo.uvs6AttrDesc && binaryInfo.uvs6AttrDesc.count > 0) {
  39416. var uvs6Data = new Float32Array(parsedGeometry, binaryInfo.uvs6AttrDesc.offset, binaryInfo.uvs6AttrDesc.count);
  39417. mesh.setVerticesData(BABYLON.VertexBuffer.UV6Kind, uvs6Data, false);
  39418. }
  39419. if (binaryInfo.colorsAttrDesc && binaryInfo.colorsAttrDesc.count > 0) {
  39420. var colorsData = new Float32Array(parsedGeometry, binaryInfo.colorsAttrDesc.offset, binaryInfo.colorsAttrDesc.count);
  39421. mesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, colorsData, false, binaryInfo.colorsAttrDesc.stride);
  39422. }
  39423. if (binaryInfo.matricesIndicesAttrDesc && binaryInfo.matricesIndicesAttrDesc.count > 0) {
  39424. var matricesIndicesData = new Int32Array(parsedGeometry, binaryInfo.matricesIndicesAttrDesc.offset, binaryInfo.matricesIndicesAttrDesc.count);
  39425. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, matricesIndicesData, false);
  39426. }
  39427. if (binaryInfo.matricesWeightsAttrDesc && binaryInfo.matricesWeightsAttrDesc.count > 0) {
  39428. var matricesWeightsData = new Float32Array(parsedGeometry, binaryInfo.matricesWeightsAttrDesc.offset, binaryInfo.matricesWeightsAttrDesc.count);
  39429. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, matricesWeightsData, false);
  39430. }
  39431. if (binaryInfo.indicesAttrDesc && binaryInfo.indicesAttrDesc.count > 0) {
  39432. var indicesData = new Int32Array(parsedGeometry, binaryInfo.indicesAttrDesc.offset, binaryInfo.indicesAttrDesc.count);
  39433. mesh.setIndices(indicesData, null);
  39434. }
  39435. if (binaryInfo.subMeshesAttrDesc && binaryInfo.subMeshesAttrDesc.count > 0) {
  39436. var subMeshesData = new Int32Array(parsedGeometry, binaryInfo.subMeshesAttrDesc.offset, binaryInfo.subMeshesAttrDesc.count * 5);
  39437. mesh.subMeshes = [];
  39438. for (var i = 0; i < binaryInfo.subMeshesAttrDesc.count; i++) {
  39439. var materialIndex = subMeshesData[(i * 5) + 0];
  39440. var verticesStart = subMeshesData[(i * 5) + 1];
  39441. var verticesCount = subMeshesData[(i * 5) + 2];
  39442. var indexStart = subMeshesData[(i * 5) + 3];
  39443. var indexCount = subMeshesData[(i * 5) + 4];
  39444. BABYLON.SubMesh.AddToMesh(materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh);
  39445. }
  39446. }
  39447. }
  39448. else if (parsedGeometry.positions && parsedGeometry.normals && parsedGeometry.indices) {
  39449. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, parsedGeometry.positions, parsedGeometry.positions._updatable);
  39450. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, parsedGeometry.normals, parsedGeometry.normals._updatable);
  39451. if (parsedGeometry.tangents) {
  39452. mesh.setVerticesData(BABYLON.VertexBuffer.TangentKind, parsedGeometry.tangents, parsedGeometry.tangents._updatable);
  39453. }
  39454. if (parsedGeometry.uvs) {
  39455. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, parsedGeometry.uvs, parsedGeometry.uvs._updatable);
  39456. }
  39457. if (parsedGeometry.uvs2) {
  39458. mesh.setVerticesData(BABYLON.VertexBuffer.UV2Kind, parsedGeometry.uvs2, parsedGeometry.uvs2._updatable);
  39459. }
  39460. if (parsedGeometry.uvs3) {
  39461. mesh.setVerticesData(BABYLON.VertexBuffer.UV3Kind, parsedGeometry.uvs3, parsedGeometry.uvs3._updatable);
  39462. }
  39463. if (parsedGeometry.uvs4) {
  39464. mesh.setVerticesData(BABYLON.VertexBuffer.UV4Kind, parsedGeometry.uvs4, parsedGeometry.uvs4._updatable);
  39465. }
  39466. if (parsedGeometry.uvs5) {
  39467. mesh.setVerticesData(BABYLON.VertexBuffer.UV5Kind, parsedGeometry.uvs5, parsedGeometry.uvs5._updatable);
  39468. }
  39469. if (parsedGeometry.uvs6) {
  39470. mesh.setVerticesData(BABYLON.VertexBuffer.UV6Kind, parsedGeometry.uvs6, parsedGeometry.uvs6._updatable);
  39471. }
  39472. if (parsedGeometry.colors) {
  39473. mesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, BABYLON.Color4.CheckColors4(parsedGeometry.colors, parsedGeometry.positions.length / 3), parsedGeometry.colors._updatable);
  39474. }
  39475. if (parsedGeometry.matricesIndices) {
  39476. if (!parsedGeometry.matricesIndices._isExpanded) {
  39477. var floatIndices = [];
  39478. for (var i = 0; i < parsedGeometry.matricesIndices.length; i++) {
  39479. var matricesIndex = parsedGeometry.matricesIndices[i];
  39480. floatIndices.push(matricesIndex & 0x000000FF);
  39481. floatIndices.push((matricesIndex & 0x0000FF00) >> 8);
  39482. floatIndices.push((matricesIndex & 0x00FF0000) >> 16);
  39483. floatIndices.push(matricesIndex >> 24);
  39484. }
  39485. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, floatIndices, parsedGeometry.matricesIndices._updatable);
  39486. }
  39487. else {
  39488. delete parsedGeometry.matricesIndices._isExpanded;
  39489. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, parsedGeometry.matricesIndices, parsedGeometry.matricesIndices._updatable);
  39490. }
  39491. }
  39492. if (parsedGeometry.matricesIndicesExtra) {
  39493. if (!parsedGeometry.matricesIndicesExtra._isExpanded) {
  39494. var floatIndices = [];
  39495. for (var i = 0; i < parsedGeometry.matricesIndicesExtra.length; i++) {
  39496. var matricesIndex = parsedGeometry.matricesIndicesExtra[i];
  39497. floatIndices.push(matricesIndex & 0x000000FF);
  39498. floatIndices.push((matricesIndex & 0x0000FF00) >> 8);
  39499. floatIndices.push((matricesIndex & 0x00FF0000) >> 16);
  39500. floatIndices.push(matricesIndex >> 24);
  39501. }
  39502. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, floatIndices, parsedGeometry.matricesIndicesExtra._updatable);
  39503. }
  39504. else {
  39505. delete parsedGeometry.matricesIndices._isExpanded;
  39506. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, parsedGeometry.matricesIndicesExtra, parsedGeometry.matricesIndicesExtra._updatable);
  39507. }
  39508. }
  39509. if (parsedGeometry.matricesWeights) {
  39510. Geometry._CleanMatricesWeights(parsedGeometry, mesh);
  39511. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, parsedGeometry.matricesWeights, parsedGeometry.matricesWeights._updatable);
  39512. }
  39513. if (parsedGeometry.matricesWeightsExtra) {
  39514. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, parsedGeometry.matricesWeightsExtra, parsedGeometry.matricesWeights._updatable);
  39515. }
  39516. mesh.setIndices(parsedGeometry.indices, null);
  39517. }
  39518. // SubMeshes
  39519. if (parsedGeometry.subMeshes) {
  39520. mesh.subMeshes = [];
  39521. for (var subIndex = 0; subIndex < parsedGeometry.subMeshes.length; subIndex++) {
  39522. var parsedSubMesh = parsedGeometry.subMeshes[subIndex];
  39523. BABYLON.SubMesh.AddToMesh(parsedSubMesh.materialIndex, parsedSubMesh.verticesStart, parsedSubMesh.verticesCount, parsedSubMesh.indexStart, parsedSubMesh.indexCount, mesh);
  39524. }
  39525. }
  39526. // Flat shading
  39527. if (mesh._shouldGenerateFlatShading) {
  39528. mesh.convertToFlatShadedMesh();
  39529. delete mesh._shouldGenerateFlatShading;
  39530. }
  39531. // Update
  39532. mesh.computeWorldMatrix(true);
  39533. // Octree
  39534. var sceneOctree = scene.selectionOctree;
  39535. if (sceneOctree !== undefined && sceneOctree !== null) {
  39536. sceneOctree.addMesh(mesh);
  39537. }
  39538. };
  39539. Geometry._CleanMatricesWeights = function (parsedGeometry, mesh) {
  39540. var epsilon = 1e-3;
  39541. if (!BABYLON.SceneLoader.CleanBoneMatrixWeights) {
  39542. return;
  39543. }
  39544. var noInfluenceBoneIndex = 0.0;
  39545. if (parsedGeometry.skeletonId > -1) {
  39546. var skeleton = mesh.getScene().getLastSkeletonByID(parsedGeometry.skeletonId);
  39547. if (!skeleton) {
  39548. return;
  39549. }
  39550. noInfluenceBoneIndex = skeleton.bones.length;
  39551. }
  39552. else {
  39553. return;
  39554. }
  39555. var matricesIndices = mesh.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind);
  39556. var matricesIndicesExtra = mesh.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  39557. var matricesWeights = parsedGeometry.matricesWeights;
  39558. var matricesWeightsExtra = parsedGeometry.matricesWeightsExtra;
  39559. var influencers = parsedGeometry.numBoneInfluencer;
  39560. var size = matricesWeights.length;
  39561. for (var i = 0; i < size; i += 4) {
  39562. var weight = 0.0;
  39563. var firstZeroWeight = -1;
  39564. for (var j = 0; j < 4; j++) {
  39565. var w = matricesWeights[i + j];
  39566. weight += w;
  39567. if (w < epsilon && firstZeroWeight < 0) {
  39568. firstZeroWeight = j;
  39569. }
  39570. }
  39571. if (matricesWeightsExtra) {
  39572. for (var j = 0; j < 4; j++) {
  39573. var w = matricesWeightsExtra[i + j];
  39574. weight += w;
  39575. if (w < epsilon && firstZeroWeight < 0) {
  39576. firstZeroWeight = j + 4;
  39577. }
  39578. }
  39579. }
  39580. if (firstZeroWeight < 0 || firstZeroWeight > (influencers - 1)) {
  39581. firstZeroWeight = influencers - 1;
  39582. }
  39583. if (weight > epsilon) {
  39584. var mweight = 1.0 / weight;
  39585. for (var j = 0; j < 4; j++) {
  39586. matricesWeights[i + j] *= mweight;
  39587. }
  39588. if (matricesWeightsExtra) {
  39589. for (var j = 0; j < 4; j++) {
  39590. matricesWeightsExtra[i + j] *= mweight;
  39591. }
  39592. }
  39593. }
  39594. else {
  39595. if (firstZeroWeight >= 4) {
  39596. matricesWeightsExtra[i + firstZeroWeight - 4] = 1.0 - weight;
  39597. matricesIndicesExtra[i + firstZeroWeight - 4] = noInfluenceBoneIndex;
  39598. }
  39599. else {
  39600. matricesWeights[i + firstZeroWeight] = 1.0 - weight;
  39601. matricesIndices[i + firstZeroWeight] = noInfluenceBoneIndex;
  39602. }
  39603. }
  39604. }
  39605. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, matricesIndices);
  39606. if (parsedGeometry.matricesWeightsExtra) {
  39607. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, matricesIndicesExtra);
  39608. }
  39609. };
  39610. /**
  39611. * Create a new geometry from persisted data (Using .babylon file format)
  39612. * @param parsedVertexData defines the persisted data
  39613. * @param scene defines the hosting scene
  39614. * @param rootUrl defines the root url to use to load assets (like delayed data)
  39615. * @returns the new geometry object
  39616. */
  39617. Geometry.Parse = function (parsedVertexData, scene, rootUrl) {
  39618. if (scene.getGeometryByID(parsedVertexData.id)) {
  39619. return null; // null since geometry could be something else than a box...
  39620. }
  39621. var geometry = new Geometry(parsedVertexData.id, scene, undefined, parsedVertexData.updatable);
  39622. if (BABYLON.Tags) {
  39623. BABYLON.Tags.AddTagsTo(geometry, parsedVertexData.tags);
  39624. }
  39625. if (parsedVertexData.delayLoadingFile) {
  39626. geometry.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  39627. geometry.delayLoadingFile = rootUrl + parsedVertexData.delayLoadingFile;
  39628. geometry._boundingInfo = new BABYLON.BoundingInfo(BABYLON.Vector3.FromArray(parsedVertexData.boundingBoxMinimum), BABYLON.Vector3.FromArray(parsedVertexData.boundingBoxMaximum));
  39629. geometry._delayInfo = [];
  39630. if (parsedVertexData.hasUVs) {
  39631. geometry._delayInfo.push(BABYLON.VertexBuffer.UVKind);
  39632. }
  39633. if (parsedVertexData.hasUVs2) {
  39634. geometry._delayInfo.push(BABYLON.VertexBuffer.UV2Kind);
  39635. }
  39636. if (parsedVertexData.hasUVs3) {
  39637. geometry._delayInfo.push(BABYLON.VertexBuffer.UV3Kind);
  39638. }
  39639. if (parsedVertexData.hasUVs4) {
  39640. geometry._delayInfo.push(BABYLON.VertexBuffer.UV4Kind);
  39641. }
  39642. if (parsedVertexData.hasUVs5) {
  39643. geometry._delayInfo.push(BABYLON.VertexBuffer.UV5Kind);
  39644. }
  39645. if (parsedVertexData.hasUVs6) {
  39646. geometry._delayInfo.push(BABYLON.VertexBuffer.UV6Kind);
  39647. }
  39648. if (parsedVertexData.hasColors) {
  39649. geometry._delayInfo.push(BABYLON.VertexBuffer.ColorKind);
  39650. }
  39651. if (parsedVertexData.hasMatricesIndices) {
  39652. geometry._delayInfo.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  39653. }
  39654. if (parsedVertexData.hasMatricesWeights) {
  39655. geometry._delayInfo.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  39656. }
  39657. geometry._delayLoadingFunction = BABYLON.VertexData.ImportVertexData;
  39658. }
  39659. else {
  39660. BABYLON.VertexData.ImportVertexData(parsedVertexData, geometry);
  39661. }
  39662. scene.pushGeometry(geometry, true);
  39663. return geometry;
  39664. };
  39665. return Geometry;
  39666. }());
  39667. BABYLON.Geometry = Geometry;
  39668. // Primitives
  39669. /// Abstract class
  39670. /**
  39671. * Abstract class used to provide common services for all typed geometries
  39672. * @hidden
  39673. */
  39674. var _PrimitiveGeometry = /** @class */ (function (_super) {
  39675. __extends(_PrimitiveGeometry, _super);
  39676. /**
  39677. * Creates a new typed geometry
  39678. * @param id defines the unique ID of the geometry
  39679. * @param scene defines the hosting scene
  39680. * @param _canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  39681. * @param mesh defines the hosting mesh (can be null)
  39682. */
  39683. function _PrimitiveGeometry(id, scene, _canBeRegenerated, mesh) {
  39684. if (_canBeRegenerated === void 0) { _canBeRegenerated = false; }
  39685. if (mesh === void 0) { mesh = null; }
  39686. var _this = _super.call(this, id, scene, undefined, false, mesh) || this;
  39687. _this._canBeRegenerated = _canBeRegenerated;
  39688. _this._beingRegenerated = true;
  39689. _this.regenerate();
  39690. _this._beingRegenerated = false;
  39691. return _this;
  39692. }
  39693. /**
  39694. * Gets a value indicating if the geometry supports being regenerated with new parameters (false by default)
  39695. * @returns true if the geometry can be regenerated
  39696. */
  39697. _PrimitiveGeometry.prototype.canBeRegenerated = function () {
  39698. return this._canBeRegenerated;
  39699. };
  39700. /**
  39701. * If the geometry supports regeneration, the function will recreates the geometry with updated parameter values
  39702. */
  39703. _PrimitiveGeometry.prototype.regenerate = function () {
  39704. if (!this._canBeRegenerated) {
  39705. return;
  39706. }
  39707. this._beingRegenerated = true;
  39708. this.setAllVerticesData(this._regenerateVertexData(), false);
  39709. this._beingRegenerated = false;
  39710. };
  39711. /**
  39712. * Clone the geometry
  39713. * @param id defines the unique ID of the new geometry
  39714. * @returns the new geometry
  39715. */
  39716. _PrimitiveGeometry.prototype.asNewGeometry = function (id) {
  39717. return _super.prototype.copy.call(this, id);
  39718. };
  39719. // overrides
  39720. _PrimitiveGeometry.prototype.setAllVerticesData = function (vertexData, updatable) {
  39721. if (!this._beingRegenerated) {
  39722. return;
  39723. }
  39724. _super.prototype.setAllVerticesData.call(this, vertexData, false);
  39725. };
  39726. _PrimitiveGeometry.prototype.setVerticesData = function (kind, data, updatable) {
  39727. if (!this._beingRegenerated) {
  39728. return;
  39729. }
  39730. _super.prototype.setVerticesData.call(this, kind, data, false);
  39731. };
  39732. // to override
  39733. /** @hidden */
  39734. _PrimitiveGeometry.prototype._regenerateVertexData = function () {
  39735. throw new Error("Abstract method");
  39736. };
  39737. _PrimitiveGeometry.prototype.copy = function (id) {
  39738. throw new Error("Must be overriden in sub-classes.");
  39739. };
  39740. _PrimitiveGeometry.prototype.serialize = function () {
  39741. var serializationObject = _super.prototype.serialize.call(this);
  39742. serializationObject.canBeRegenerated = this.canBeRegenerated();
  39743. return serializationObject;
  39744. };
  39745. return _PrimitiveGeometry;
  39746. }(Geometry));
  39747. BABYLON._PrimitiveGeometry = _PrimitiveGeometry;
  39748. /**
  39749. * Creates a ribbon geometry
  39750. * @description See http://doc.babylonjs.com/how_to/ribbon_tutorial, http://doc.babylonjs.com/resources/maths_make_ribbons
  39751. */
  39752. var RibbonGeometry = /** @class */ (function (_super) {
  39753. __extends(RibbonGeometry, _super);
  39754. /**
  39755. * Creates a ribbon geometry
  39756. * @param id defines the unique ID of the geometry
  39757. * @param scene defines the hosting scene
  39758. * @param pathArray defines the array of paths to use
  39759. * @param closeArray defines if the last path and the first path must be joined
  39760. * @param closePath defines if the last and first points of each path in your pathArray must be joined
  39761. * @param offset defines the offset between points
  39762. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  39763. * @param mesh defines the hosting mesh (can be null)
  39764. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  39765. */
  39766. function RibbonGeometry(id, scene,
  39767. /**
  39768. * Defines the array of paths to use
  39769. */
  39770. pathArray,
  39771. /**
  39772. * Defines if the last and first points of each path in your pathArray must be joined
  39773. */
  39774. closeArray,
  39775. /**
  39776. * Defines if the last and first points of each path in your pathArray must be joined
  39777. */
  39778. closePath,
  39779. /**
  39780. * Defines the offset between points
  39781. */
  39782. offset, canBeRegenerated, mesh,
  39783. /**
  39784. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  39785. */
  39786. side) {
  39787. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  39788. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  39789. _this.pathArray = pathArray;
  39790. _this.closeArray = closeArray;
  39791. _this.closePath = closePath;
  39792. _this.offset = offset;
  39793. _this.side = side;
  39794. return _this;
  39795. }
  39796. /** @hidden */
  39797. RibbonGeometry.prototype._regenerateVertexData = function () {
  39798. return BABYLON.VertexData.CreateRibbon({ pathArray: this.pathArray, closeArray: this.closeArray, closePath: this.closePath, offset: this.offset, sideOrientation: this.side });
  39799. };
  39800. RibbonGeometry.prototype.copy = function (id) {
  39801. return new RibbonGeometry(id, this.getScene(), this.pathArray, this.closeArray, this.closePath, this.offset, this.canBeRegenerated(), undefined, this.side);
  39802. };
  39803. return RibbonGeometry;
  39804. }(_PrimitiveGeometry));
  39805. BABYLON.RibbonGeometry = RibbonGeometry;
  39806. /**
  39807. * Creates a box geometry
  39808. * @description see http://doc.babylonjs.com/how_to/set_shapes#box
  39809. */
  39810. var BoxGeometry = /** @class */ (function (_super) {
  39811. __extends(BoxGeometry, _super);
  39812. /**
  39813. * Creates a box geometry
  39814. * @param id defines the unique ID of the geometry
  39815. * @param scene defines the hosting scene
  39816. * @param size defines the zise of the box (width, height and depth are the same)
  39817. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  39818. * @param mesh defines the hosting mesh (can be null)
  39819. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  39820. */
  39821. function BoxGeometry(id, scene,
  39822. /**
  39823. * Defines the zise of the box (width, height and depth are the same)
  39824. */
  39825. size, canBeRegenerated, mesh,
  39826. /**
  39827. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  39828. */
  39829. side) {
  39830. if (mesh === void 0) { mesh = null; }
  39831. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  39832. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  39833. _this.size = size;
  39834. _this.side = side;
  39835. return _this;
  39836. }
  39837. BoxGeometry.prototype._regenerateVertexData = function () {
  39838. return BABYLON.VertexData.CreateBox({ size: this.size, sideOrientation: this.side });
  39839. };
  39840. BoxGeometry.prototype.copy = function (id) {
  39841. return new BoxGeometry(id, this.getScene(), this.size, this.canBeRegenerated(), undefined, this.side);
  39842. };
  39843. BoxGeometry.prototype.serialize = function () {
  39844. var serializationObject = _super.prototype.serialize.call(this);
  39845. serializationObject.size = this.size;
  39846. return serializationObject;
  39847. };
  39848. BoxGeometry.Parse = function (parsedBox, scene) {
  39849. if (scene.getGeometryByID(parsedBox.id)) {
  39850. return null; // null since geometry could be something else than a box...
  39851. }
  39852. var box = new BoxGeometry(parsedBox.id, scene, parsedBox.size, parsedBox.canBeRegenerated, null);
  39853. if (BABYLON.Tags) {
  39854. BABYLON.Tags.AddTagsTo(box, parsedBox.tags);
  39855. }
  39856. scene.pushGeometry(box, true);
  39857. return box;
  39858. };
  39859. return BoxGeometry;
  39860. }(_PrimitiveGeometry));
  39861. BABYLON.BoxGeometry = BoxGeometry;
  39862. /**
  39863. * Creates a sphere geometry
  39864. * @description see http://doc.babylonjs.com/how_to/set_shapes#sphere
  39865. */
  39866. var SphereGeometry = /** @class */ (function (_super) {
  39867. __extends(SphereGeometry, _super);
  39868. /**
  39869. * Create a new sphere geometry
  39870. * @param id defines the unique ID of the geometry
  39871. * @param scene defines the hosting scene
  39872. * @param segments defines the number of segments to use to create the sphere
  39873. * @param diameter defines the diameter of the sphere
  39874. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  39875. * @param mesh defines the hosting mesh (can be null)
  39876. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  39877. */
  39878. function SphereGeometry(id, scene,
  39879. /**
  39880. * Defines the number of segments to use to create the sphere
  39881. */
  39882. segments,
  39883. /**
  39884. * Defines the diameter of the sphere
  39885. */
  39886. diameter, canBeRegenerated, mesh,
  39887. /**
  39888. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  39889. */
  39890. side) {
  39891. if (mesh === void 0) { mesh = null; }
  39892. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  39893. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  39894. _this.segments = segments;
  39895. _this.diameter = diameter;
  39896. _this.side = side;
  39897. return _this;
  39898. }
  39899. SphereGeometry.prototype._regenerateVertexData = function () {
  39900. return BABYLON.VertexData.CreateSphere({ segments: this.segments, diameter: this.diameter, sideOrientation: this.side });
  39901. };
  39902. SphereGeometry.prototype.copy = function (id) {
  39903. return new SphereGeometry(id, this.getScene(), this.segments, this.diameter, this.canBeRegenerated(), null, this.side);
  39904. };
  39905. SphereGeometry.prototype.serialize = function () {
  39906. var serializationObject = _super.prototype.serialize.call(this);
  39907. serializationObject.segments = this.segments;
  39908. serializationObject.diameter = this.diameter;
  39909. return serializationObject;
  39910. };
  39911. SphereGeometry.Parse = function (parsedSphere, scene) {
  39912. if (scene.getGeometryByID(parsedSphere.id)) {
  39913. return null; // null since geometry could be something else than a sphere...
  39914. }
  39915. var sphere = new SphereGeometry(parsedSphere.id, scene, parsedSphere.segments, parsedSphere.diameter, parsedSphere.canBeRegenerated, null);
  39916. if (BABYLON.Tags) {
  39917. BABYLON.Tags.AddTagsTo(sphere, parsedSphere.tags);
  39918. }
  39919. scene.pushGeometry(sphere, true);
  39920. return sphere;
  39921. };
  39922. return SphereGeometry;
  39923. }(_PrimitiveGeometry));
  39924. BABYLON.SphereGeometry = SphereGeometry;
  39925. /**
  39926. * Creates a disc geometry
  39927. * @description see http://doc.babylonjs.com/how_to/set_shapes#disc-or-regular-polygon
  39928. */
  39929. var DiscGeometry = /** @class */ (function (_super) {
  39930. __extends(DiscGeometry, _super);
  39931. /**
  39932. * Creates a new disc geometry
  39933. * @param id defines the unique ID of the geometry
  39934. * @param scene defines the hosting scene
  39935. * @param radius defines the radius of the disc
  39936. * @param tessellation defines the tesselation factor to apply to the disc
  39937. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  39938. * @param mesh defines the hosting mesh (can be null)
  39939. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  39940. */
  39941. function DiscGeometry(id, scene,
  39942. /**
  39943. * Defines the radius of the disc
  39944. */
  39945. radius,
  39946. /**
  39947. * Defines the tesselation factor to apply to the disc
  39948. */
  39949. tessellation, canBeRegenerated, mesh,
  39950. /**
  39951. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  39952. */
  39953. side) {
  39954. if (mesh === void 0) { mesh = null; }
  39955. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  39956. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  39957. _this.radius = radius;
  39958. _this.tessellation = tessellation;
  39959. _this.side = side;
  39960. return _this;
  39961. }
  39962. DiscGeometry.prototype._regenerateVertexData = function () {
  39963. return BABYLON.VertexData.CreateDisc({ radius: this.radius, tessellation: this.tessellation, sideOrientation: this.side });
  39964. };
  39965. DiscGeometry.prototype.copy = function (id) {
  39966. return new DiscGeometry(id, this.getScene(), this.radius, this.tessellation, this.canBeRegenerated(), null, this.side);
  39967. };
  39968. return DiscGeometry;
  39969. }(_PrimitiveGeometry));
  39970. BABYLON.DiscGeometry = DiscGeometry;
  39971. /**
  39972. * Creates a new cylinder geometry
  39973. * @description see http://doc.babylonjs.com/how_to/set_shapes#cylinder-or-cone
  39974. */
  39975. var CylinderGeometry = /** @class */ (function (_super) {
  39976. __extends(CylinderGeometry, _super);
  39977. /**
  39978. * Creates a new cylinder geometry
  39979. * @param id defines the unique ID of the geometry
  39980. * @param scene defines the hosting scene
  39981. * @param height defines the height of the cylinder
  39982. * @param diameterTop defines the diameter of the cylinder's top cap
  39983. * @param diameterBottom defines the diameter of the cylinder's bottom cap
  39984. * @param tessellation defines the tessellation factor to apply to the cylinder (number of radial sides)
  39985. * @param subdivisions defines the number of subdivisions to apply to the cylinder (number of rings) (1 by default)
  39986. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  39987. * @param mesh defines the hosting mesh (can be null)
  39988. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  39989. */
  39990. function CylinderGeometry(id, scene,
  39991. /**
  39992. * Defines the height of the cylinder
  39993. */
  39994. height,
  39995. /**
  39996. * Defines the diameter of the cylinder's top cap
  39997. */
  39998. diameterTop,
  39999. /**
  40000. * Defines the diameter of the cylinder's bottom cap
  40001. */
  40002. diameterBottom,
  40003. /**
  40004. * Defines the tessellation factor to apply to the cylinder
  40005. */
  40006. tessellation,
  40007. /**
  40008. * Defines the number of subdivisions to apply to the cylinder (1 by default)
  40009. */
  40010. subdivisions, canBeRegenerated, mesh,
  40011. /**
  40012. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  40013. */
  40014. side) {
  40015. if (subdivisions === void 0) { subdivisions = 1; }
  40016. if (mesh === void 0) { mesh = null; }
  40017. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  40018. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  40019. _this.height = height;
  40020. _this.diameterTop = diameterTop;
  40021. _this.diameterBottom = diameterBottom;
  40022. _this.tessellation = tessellation;
  40023. _this.subdivisions = subdivisions;
  40024. _this.side = side;
  40025. return _this;
  40026. }
  40027. CylinderGeometry.prototype._regenerateVertexData = function () {
  40028. return BABYLON.VertexData.CreateCylinder({ height: this.height, diameterTop: this.diameterTop, diameterBottom: this.diameterBottom, tessellation: this.tessellation, subdivisions: this.subdivisions, sideOrientation: this.side });
  40029. };
  40030. CylinderGeometry.prototype.copy = function (id) {
  40031. return new CylinderGeometry(id, this.getScene(), this.height, this.diameterTop, this.diameterBottom, this.tessellation, this.subdivisions, this.canBeRegenerated(), null, this.side);
  40032. };
  40033. CylinderGeometry.prototype.serialize = function () {
  40034. var serializationObject = _super.prototype.serialize.call(this);
  40035. serializationObject.height = this.height;
  40036. serializationObject.diameterTop = this.diameterTop;
  40037. serializationObject.diameterBottom = this.diameterBottom;
  40038. serializationObject.tessellation = this.tessellation;
  40039. return serializationObject;
  40040. };
  40041. CylinderGeometry.Parse = function (parsedCylinder, scene) {
  40042. if (scene.getGeometryByID(parsedCylinder.id)) {
  40043. return null; // null since geometry could be something else than a cylinder...
  40044. }
  40045. var cylinder = new CylinderGeometry(parsedCylinder.id, scene, parsedCylinder.height, parsedCylinder.diameterTop, parsedCylinder.diameterBottom, parsedCylinder.tessellation, parsedCylinder.subdivisions, parsedCylinder.canBeRegenerated, null);
  40046. if (BABYLON.Tags) {
  40047. BABYLON.Tags.AddTagsTo(cylinder, parsedCylinder.tags);
  40048. }
  40049. scene.pushGeometry(cylinder, true);
  40050. return cylinder;
  40051. };
  40052. return CylinderGeometry;
  40053. }(_PrimitiveGeometry));
  40054. BABYLON.CylinderGeometry = CylinderGeometry;
  40055. /**
  40056. * Creates a new torus geometry
  40057. * @description see http://doc.babylonjs.com/how_to/set_shapes#torus
  40058. */
  40059. var TorusGeometry = /** @class */ (function (_super) {
  40060. __extends(TorusGeometry, _super);
  40061. /**
  40062. * Creates a new torus geometry
  40063. * @param id defines the unique ID of the geometry
  40064. * @param scene defines the hosting scene
  40065. * @param diameter defines the diameter of the torus
  40066. * @param thickness defines the thickness of the torus (ie. internal diameter)
  40067. * @param tessellation defines the tesselation factor to apply to the torus (number of segments along the circle)
  40068. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  40069. * @param mesh defines the hosting mesh (can be null)
  40070. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  40071. */
  40072. function TorusGeometry(id, scene,
  40073. /**
  40074. * Defines the diameter of the torus
  40075. */
  40076. diameter,
  40077. /**
  40078. * Defines the thickness of the torus (ie. internal diameter)
  40079. */
  40080. thickness,
  40081. /**
  40082. * Defines the tesselation factor to apply to the torus
  40083. */
  40084. tessellation, canBeRegenerated, mesh,
  40085. /**
  40086. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  40087. */
  40088. side) {
  40089. if (mesh === void 0) { mesh = null; }
  40090. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  40091. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  40092. _this.diameter = diameter;
  40093. _this.thickness = thickness;
  40094. _this.tessellation = tessellation;
  40095. _this.side = side;
  40096. return _this;
  40097. }
  40098. TorusGeometry.prototype._regenerateVertexData = function () {
  40099. return BABYLON.VertexData.CreateTorus({ diameter: this.diameter, thickness: this.thickness, tessellation: this.tessellation, sideOrientation: this.side });
  40100. };
  40101. TorusGeometry.prototype.copy = function (id) {
  40102. return new TorusGeometry(id, this.getScene(), this.diameter, this.thickness, this.tessellation, this.canBeRegenerated(), null, this.side);
  40103. };
  40104. TorusGeometry.prototype.serialize = function () {
  40105. var serializationObject = _super.prototype.serialize.call(this);
  40106. serializationObject.diameter = this.diameter;
  40107. serializationObject.thickness = this.thickness;
  40108. serializationObject.tessellation = this.tessellation;
  40109. return serializationObject;
  40110. };
  40111. TorusGeometry.Parse = function (parsedTorus, scene) {
  40112. if (scene.getGeometryByID(parsedTorus.id)) {
  40113. return null; // null since geometry could be something else than a torus...
  40114. }
  40115. var torus = new TorusGeometry(parsedTorus.id, scene, parsedTorus.diameter, parsedTorus.thickness, parsedTorus.tessellation, parsedTorus.canBeRegenerated, null);
  40116. if (BABYLON.Tags) {
  40117. BABYLON.Tags.AddTagsTo(torus, parsedTorus.tags);
  40118. }
  40119. scene.pushGeometry(torus, true);
  40120. return torus;
  40121. };
  40122. return TorusGeometry;
  40123. }(_PrimitiveGeometry));
  40124. BABYLON.TorusGeometry = TorusGeometry;
  40125. /**
  40126. * Creates a new ground geometry
  40127. * @description see http://doc.babylonjs.com/how_to/set_shapes#ground
  40128. */
  40129. var GroundGeometry = /** @class */ (function (_super) {
  40130. __extends(GroundGeometry, _super);
  40131. /**
  40132. * Creates a new ground geometry
  40133. * @param id defines the unique ID of the geometry
  40134. * @param scene defines the hosting scene
  40135. * @param width defines the width of the ground
  40136. * @param height defines the height of the ground
  40137. * @param subdivisions defines the subdivisions to apply to the ground
  40138. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  40139. * @param mesh defines the hosting mesh (can be null)
  40140. */
  40141. function GroundGeometry(id, scene,
  40142. /**
  40143. * Defines the width of the ground
  40144. */
  40145. width,
  40146. /**
  40147. * Defines the height of the ground
  40148. */
  40149. height,
  40150. /**
  40151. * Defines the subdivisions to apply to the ground
  40152. */
  40153. subdivisions, canBeRegenerated, mesh) {
  40154. if (mesh === void 0) { mesh = null; }
  40155. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  40156. _this.width = width;
  40157. _this.height = height;
  40158. _this.subdivisions = subdivisions;
  40159. return _this;
  40160. }
  40161. GroundGeometry.prototype._regenerateVertexData = function () {
  40162. return BABYLON.VertexData.CreateGround({ width: this.width, height: this.height, subdivisions: this.subdivisions });
  40163. };
  40164. GroundGeometry.prototype.copy = function (id) {
  40165. return new GroundGeometry(id, this.getScene(), this.width, this.height, this.subdivisions, this.canBeRegenerated(), null);
  40166. };
  40167. GroundGeometry.prototype.serialize = function () {
  40168. var serializationObject = _super.prototype.serialize.call(this);
  40169. serializationObject.width = this.width;
  40170. serializationObject.height = this.height;
  40171. serializationObject.subdivisions = this.subdivisions;
  40172. return serializationObject;
  40173. };
  40174. GroundGeometry.Parse = function (parsedGround, scene) {
  40175. if (scene.getGeometryByID(parsedGround.id)) {
  40176. return null; // null since geometry could be something else than a ground...
  40177. }
  40178. var ground = new GroundGeometry(parsedGround.id, scene, parsedGround.width, parsedGround.height, parsedGround.subdivisions, parsedGround.canBeRegenerated, null);
  40179. if (BABYLON.Tags) {
  40180. BABYLON.Tags.AddTagsTo(ground, parsedGround.tags);
  40181. }
  40182. scene.pushGeometry(ground, true);
  40183. return ground;
  40184. };
  40185. return GroundGeometry;
  40186. }(_PrimitiveGeometry));
  40187. BABYLON.GroundGeometry = GroundGeometry;
  40188. /**
  40189. * Creates a tiled ground geometry
  40190. * @description see http://doc.babylonjs.com/how_to/set_shapes#tiled-ground
  40191. */
  40192. var TiledGroundGeometry = /** @class */ (function (_super) {
  40193. __extends(TiledGroundGeometry, _super);
  40194. /**
  40195. * Creates a tiled ground geometry
  40196. * @param id defines the unique ID of the geometry
  40197. * @param scene defines the hosting scene
  40198. * @param xmin defines the minimum value on X axis
  40199. * @param zmin defines the minimum value on Z axis
  40200. * @param xmax defines the maximum value on X axis
  40201. * @param zmax defines the maximum value on Z axis
  40202. * @param subdivisions defines the subdivisions to apply to the ground (number of subdivisions (tiles) on the height and the width of the map)
  40203. * @param precision defines the precision to use when computing the tiles
  40204. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  40205. * @param mesh defines the hosting mesh (can be null)
  40206. */
  40207. function TiledGroundGeometry(id, scene,
  40208. /**
  40209. * Defines the minimum value on X axis
  40210. */
  40211. xmin,
  40212. /**
  40213. * Defines the minimum value on Z axis
  40214. */
  40215. zmin,
  40216. /**
  40217. * Defines the maximum value on X axis
  40218. */
  40219. xmax,
  40220. /**
  40221. * Defines the maximum value on Z axis
  40222. */
  40223. zmax,
  40224. /**
  40225. * Defines the subdivisions to apply to the ground
  40226. */
  40227. subdivisions,
  40228. /**
  40229. * Defines the precision to use when computing the tiles
  40230. */
  40231. precision, canBeRegenerated, mesh) {
  40232. if (mesh === void 0) { mesh = null; }
  40233. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  40234. _this.xmin = xmin;
  40235. _this.zmin = zmin;
  40236. _this.xmax = xmax;
  40237. _this.zmax = zmax;
  40238. _this.subdivisions = subdivisions;
  40239. _this.precision = precision;
  40240. return _this;
  40241. }
  40242. TiledGroundGeometry.prototype._regenerateVertexData = function () {
  40243. return BABYLON.VertexData.CreateTiledGround({ xmin: this.xmin, zmin: this.zmin, xmax: this.xmax, zmax: this.zmax, subdivisions: this.subdivisions, precision: this.precision });
  40244. };
  40245. TiledGroundGeometry.prototype.copy = function (id) {
  40246. return new TiledGroundGeometry(id, this.getScene(), this.xmin, this.zmin, this.xmax, this.zmax, this.subdivisions, this.precision, this.canBeRegenerated(), null);
  40247. };
  40248. return TiledGroundGeometry;
  40249. }(_PrimitiveGeometry));
  40250. BABYLON.TiledGroundGeometry = TiledGroundGeometry;
  40251. /**
  40252. * Creates a plane geometry
  40253. * @description see http://doc.babylonjs.com/how_to/set_shapes#plane
  40254. */
  40255. var PlaneGeometry = /** @class */ (function (_super) {
  40256. __extends(PlaneGeometry, _super);
  40257. /**
  40258. * Creates a plane geometry
  40259. * @param id defines the unique ID of the geometry
  40260. * @param scene defines the hosting scene
  40261. * @param size defines the size of the plane (width === height)
  40262. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  40263. * @param mesh defines the hosting mesh (can be null)
  40264. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  40265. */
  40266. function PlaneGeometry(id, scene,
  40267. /**
  40268. * Defines the size of the plane (width === height)
  40269. */
  40270. size, canBeRegenerated, mesh,
  40271. /**
  40272. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  40273. */
  40274. side) {
  40275. if (mesh === void 0) { mesh = null; }
  40276. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  40277. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  40278. _this.size = size;
  40279. _this.side = side;
  40280. return _this;
  40281. }
  40282. PlaneGeometry.prototype._regenerateVertexData = function () {
  40283. return BABYLON.VertexData.CreatePlane({ size: this.size, sideOrientation: this.side });
  40284. };
  40285. PlaneGeometry.prototype.copy = function (id) {
  40286. return new PlaneGeometry(id, this.getScene(), this.size, this.canBeRegenerated(), null, this.side);
  40287. };
  40288. PlaneGeometry.prototype.serialize = function () {
  40289. var serializationObject = _super.prototype.serialize.call(this);
  40290. serializationObject.size = this.size;
  40291. return serializationObject;
  40292. };
  40293. PlaneGeometry.Parse = function (parsedPlane, scene) {
  40294. if (scene.getGeometryByID(parsedPlane.id)) {
  40295. return null; // null since geometry could be something else than a ground...
  40296. }
  40297. var plane = new PlaneGeometry(parsedPlane.id, scene, parsedPlane.size, parsedPlane.canBeRegenerated, null);
  40298. if (BABYLON.Tags) {
  40299. BABYLON.Tags.AddTagsTo(plane, parsedPlane.tags);
  40300. }
  40301. scene.pushGeometry(plane, true);
  40302. return plane;
  40303. };
  40304. return PlaneGeometry;
  40305. }(_PrimitiveGeometry));
  40306. BABYLON.PlaneGeometry = PlaneGeometry;
  40307. /**
  40308. * Creates a torus knot geometry
  40309. * @description see http://doc.babylonjs.com/how_to/set_shapes#torus-knot
  40310. */
  40311. var TorusKnotGeometry = /** @class */ (function (_super) {
  40312. __extends(TorusKnotGeometry, _super);
  40313. /**
  40314. * Creates a torus knot geometry
  40315. * @param id defines the unique ID of the geometry
  40316. * @param scene defines the hosting scene
  40317. * @param radius defines the radius of the torus knot
  40318. * @param tube defines the thickness of the torus knot tube
  40319. * @param radialSegments defines the number of radial segments
  40320. * @param tubularSegments defines the number of tubular segments
  40321. * @param p defines the first number of windings
  40322. * @param q defines the second number of windings
  40323. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  40324. * @param mesh defines the hosting mesh (can be null)
  40325. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  40326. */
  40327. function TorusKnotGeometry(id, scene,
  40328. /**
  40329. * Defines the radius of the torus knot
  40330. */
  40331. radius,
  40332. /**
  40333. * Defines the thickness of the torus knot tube
  40334. */
  40335. tube,
  40336. /**
  40337. * Defines the number of radial segments
  40338. */
  40339. radialSegments,
  40340. /**
  40341. * Defines the number of tubular segments
  40342. */
  40343. tubularSegments,
  40344. /**
  40345. * Defines the first number of windings
  40346. */
  40347. p,
  40348. /**
  40349. * Defines the second number of windings
  40350. */
  40351. q, canBeRegenerated, mesh,
  40352. /**
  40353. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  40354. */
  40355. side) {
  40356. if (mesh === void 0) { mesh = null; }
  40357. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  40358. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  40359. _this.radius = radius;
  40360. _this.tube = tube;
  40361. _this.radialSegments = radialSegments;
  40362. _this.tubularSegments = tubularSegments;
  40363. _this.p = p;
  40364. _this.q = q;
  40365. _this.side = side;
  40366. return _this;
  40367. }
  40368. TorusKnotGeometry.prototype._regenerateVertexData = function () {
  40369. 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 });
  40370. };
  40371. TorusKnotGeometry.prototype.copy = function (id) {
  40372. return new TorusKnotGeometry(id, this.getScene(), this.radius, this.tube, this.radialSegments, this.tubularSegments, this.p, this.q, this.canBeRegenerated(), null, this.side);
  40373. };
  40374. TorusKnotGeometry.prototype.serialize = function () {
  40375. var serializationObject = _super.prototype.serialize.call(this);
  40376. serializationObject.radius = this.radius;
  40377. serializationObject.tube = this.tube;
  40378. serializationObject.radialSegments = this.radialSegments;
  40379. serializationObject.tubularSegments = this.tubularSegments;
  40380. serializationObject.p = this.p;
  40381. serializationObject.q = this.q;
  40382. return serializationObject;
  40383. };
  40384. ;
  40385. TorusKnotGeometry.Parse = function (parsedTorusKnot, scene) {
  40386. if (scene.getGeometryByID(parsedTorusKnot.id)) {
  40387. return null; // null since geometry could be something else than a ground...
  40388. }
  40389. var torusKnot = new TorusKnotGeometry(parsedTorusKnot.id, scene, parsedTorusKnot.radius, parsedTorusKnot.tube, parsedTorusKnot.radialSegments, parsedTorusKnot.tubularSegments, parsedTorusKnot.p, parsedTorusKnot.q, parsedTorusKnot.canBeRegenerated, null);
  40390. if (BABYLON.Tags) {
  40391. BABYLON.Tags.AddTagsTo(torusKnot, parsedTorusKnot.tags);
  40392. }
  40393. scene.pushGeometry(torusKnot, true);
  40394. return torusKnot;
  40395. };
  40396. return TorusKnotGeometry;
  40397. }(_PrimitiveGeometry));
  40398. BABYLON.TorusKnotGeometry = TorusKnotGeometry;
  40399. //}
  40400. })(BABYLON || (BABYLON = {}));
  40401. //# sourceMappingURL=babylon.geometry.js.map
  40402. var BABYLON;
  40403. (function (BABYLON) {
  40404. /**
  40405. * PostProcessManager is used to manage one or more post processes or post process pipelines
  40406. * See https://doc.babylonjs.com/how_to/how_to_use_postprocesses
  40407. */
  40408. var PostProcessManager = /** @class */ (function () {
  40409. /**
  40410. * Creates a new instance PostProcess
  40411. * @param scene The scene that the post process is associated with.
  40412. */
  40413. function PostProcessManager(scene) {
  40414. this._vertexBuffers = {};
  40415. this._scene = scene;
  40416. }
  40417. PostProcessManager.prototype._prepareBuffers = function () {
  40418. if (this._vertexBuffers[BABYLON.VertexBuffer.PositionKind]) {
  40419. return;
  40420. }
  40421. // VBO
  40422. var vertices = [];
  40423. vertices.push(1, 1);
  40424. vertices.push(-1, 1);
  40425. vertices.push(-1, -1);
  40426. vertices.push(1, -1);
  40427. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(this._scene.getEngine(), vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  40428. this._buildIndexBuffer();
  40429. };
  40430. PostProcessManager.prototype._buildIndexBuffer = function () {
  40431. // Indices
  40432. var indices = [];
  40433. indices.push(0);
  40434. indices.push(1);
  40435. indices.push(2);
  40436. indices.push(0);
  40437. indices.push(2);
  40438. indices.push(3);
  40439. this._indexBuffer = this._scene.getEngine().createIndexBuffer(indices);
  40440. };
  40441. /**
  40442. * Rebuilds the vertex buffers of the manager.
  40443. */
  40444. PostProcessManager.prototype._rebuild = function () {
  40445. var vb = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  40446. if (!vb) {
  40447. return;
  40448. }
  40449. vb._rebuild();
  40450. this._buildIndexBuffer();
  40451. };
  40452. // Methods
  40453. /**
  40454. * Prepares a frame to be run through a post process.
  40455. * @param sourceTexture The input texture to the post procesess. (default: null)
  40456. * @param postProcesses An array of post processes to be run. (default: null)
  40457. * @returns True if the post processes were able to be run.
  40458. */
  40459. PostProcessManager.prototype._prepareFrame = function (sourceTexture, postProcesses) {
  40460. if (sourceTexture === void 0) { sourceTexture = null; }
  40461. if (postProcesses === void 0) { postProcesses = null; }
  40462. var camera = this._scene.activeCamera;
  40463. if (!camera) {
  40464. return false;
  40465. }
  40466. var postProcesses = postProcesses || camera._postProcesses.filter(function (pp) { return pp != null; });
  40467. if (!postProcesses || postProcesses.length === 0 || !this._scene.postProcessesEnabled) {
  40468. return false;
  40469. }
  40470. postProcesses[0].activate(camera, sourceTexture, postProcesses !== null && postProcesses !== undefined);
  40471. return true;
  40472. };
  40473. /**
  40474. * Manually render a set of post processes to a texture.
  40475. * @param postProcesses An array of post processes to be run.
  40476. * @param targetTexture The target texture to render to.
  40477. * @param forceFullscreenViewport force gl.viewport to be full screen eg. 0,0,textureWidth,textureHeight
  40478. */
  40479. PostProcessManager.prototype.directRender = function (postProcesses, targetTexture, forceFullscreenViewport) {
  40480. if (targetTexture === void 0) { targetTexture = null; }
  40481. if (forceFullscreenViewport === void 0) { forceFullscreenViewport = false; }
  40482. var engine = this._scene.getEngine();
  40483. for (var index = 0; index < postProcesses.length; index++) {
  40484. if (index < postProcesses.length - 1) {
  40485. postProcesses[index + 1].activate(this._scene.activeCamera, targetTexture);
  40486. }
  40487. else {
  40488. if (targetTexture) {
  40489. engine.bindFramebuffer(targetTexture, 0, undefined, undefined, forceFullscreenViewport);
  40490. }
  40491. else {
  40492. engine.restoreDefaultFramebuffer();
  40493. }
  40494. }
  40495. var pp = postProcesses[index];
  40496. var effect = pp.apply();
  40497. if (effect) {
  40498. pp.onBeforeRenderObservable.notifyObservers(effect);
  40499. // VBOs
  40500. this._prepareBuffers();
  40501. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, effect);
  40502. // Draw order
  40503. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  40504. pp.onAfterRenderObservable.notifyObservers(effect);
  40505. }
  40506. }
  40507. // Restore depth buffer
  40508. engine.setDepthBuffer(true);
  40509. engine.setDepthWrite(true);
  40510. };
  40511. /**
  40512. * Finalize the result of the output of the postprocesses.
  40513. * @param doNotPresent If true the result will not be displayed to the screen.
  40514. * @param targetTexture The target texture to render to.
  40515. * @param faceIndex The index of the face to bind the target texture to.
  40516. * @param postProcesses The array of post processes to render.
  40517. * @param forceFullscreenViewport force gl.viewport to be full screen eg. 0,0,textureWidth,textureHeight (default: false)
  40518. */
  40519. PostProcessManager.prototype._finalizeFrame = function (doNotPresent, targetTexture, faceIndex, postProcesses, forceFullscreenViewport) {
  40520. if (forceFullscreenViewport === void 0) { forceFullscreenViewport = false; }
  40521. var camera = this._scene.activeCamera;
  40522. if (!camera) {
  40523. return;
  40524. }
  40525. postProcesses = postProcesses || camera._postProcesses.filter(function (pp) { return pp != null; });
  40526. if (postProcesses.length === 0 || !this._scene.postProcessesEnabled) {
  40527. return;
  40528. }
  40529. var engine = this._scene.getEngine();
  40530. for (var index = 0, len = postProcesses.length; index < len; index++) {
  40531. var pp = postProcesses[index];
  40532. if (index < len - 1) {
  40533. pp._outputTexture = postProcesses[index + 1].activate(camera, targetTexture);
  40534. }
  40535. else {
  40536. if (targetTexture) {
  40537. engine.bindFramebuffer(targetTexture, faceIndex, undefined, undefined, forceFullscreenViewport);
  40538. pp._outputTexture = targetTexture;
  40539. }
  40540. else {
  40541. engine.restoreDefaultFramebuffer();
  40542. pp._outputTexture = null;
  40543. }
  40544. }
  40545. if (doNotPresent) {
  40546. break;
  40547. }
  40548. var effect = pp.apply();
  40549. if (effect) {
  40550. pp.onBeforeRenderObservable.notifyObservers(effect);
  40551. // VBOs
  40552. this._prepareBuffers();
  40553. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, effect);
  40554. // Draw order
  40555. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  40556. pp.onAfterRenderObservable.notifyObservers(effect);
  40557. }
  40558. }
  40559. // Restore states
  40560. engine.setDepthBuffer(true);
  40561. engine.setDepthWrite(true);
  40562. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  40563. };
  40564. /**
  40565. * Disposes of the post process manager.
  40566. */
  40567. PostProcessManager.prototype.dispose = function () {
  40568. var buffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  40569. if (buffer) {
  40570. buffer.dispose();
  40571. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  40572. }
  40573. if (this._indexBuffer) {
  40574. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  40575. this._indexBuffer = null;
  40576. }
  40577. };
  40578. return PostProcessManager;
  40579. }());
  40580. BABYLON.PostProcessManager = PostProcessManager;
  40581. })(BABYLON || (BABYLON = {}));
  40582. //# sourceMappingURL=babylon.postProcessManager.js.map
  40583. var BABYLON;
  40584. (function (BABYLON) {
  40585. /**
  40586. * Performance monitor tracks rolling average frame-time and frame-time variance over a user defined sliding-window
  40587. */
  40588. var PerformanceMonitor = /** @class */ (function () {
  40589. /**
  40590. * constructor
  40591. * @param frameSampleSize The number of samples required to saturate the sliding window
  40592. */
  40593. function PerformanceMonitor(frameSampleSize) {
  40594. if (frameSampleSize === void 0) { frameSampleSize = 30; }
  40595. this._enabled = true;
  40596. this._rollingFrameTime = new RollingAverage(frameSampleSize);
  40597. }
  40598. /**
  40599. * Samples current frame
  40600. * @param timeMs A timestamp in milliseconds of the current frame to compare with other frames
  40601. */
  40602. PerformanceMonitor.prototype.sampleFrame = function (timeMs) {
  40603. if (timeMs === void 0) { timeMs = BABYLON.Tools.Now; }
  40604. if (!this._enabled)
  40605. return;
  40606. if (this._lastFrameTimeMs != null) {
  40607. var dt = timeMs - this._lastFrameTimeMs;
  40608. this._rollingFrameTime.add(dt);
  40609. }
  40610. this._lastFrameTimeMs = timeMs;
  40611. };
  40612. Object.defineProperty(PerformanceMonitor.prototype, "averageFrameTime", {
  40613. /**
  40614. * Returns the average frame time in milliseconds over the sliding window (or the subset of frames sampled so far)
  40615. * @return Average frame time in milliseconds
  40616. */
  40617. get: function () {
  40618. return this._rollingFrameTime.average;
  40619. },
  40620. enumerable: true,
  40621. configurable: true
  40622. });
  40623. Object.defineProperty(PerformanceMonitor.prototype, "averageFrameTimeVariance", {
  40624. /**
  40625. * Returns the variance frame time in milliseconds over the sliding window (or the subset of frames sampled so far)
  40626. * @return Frame time variance in milliseconds squared
  40627. */
  40628. get: function () {
  40629. return this._rollingFrameTime.variance;
  40630. },
  40631. enumerable: true,
  40632. configurable: true
  40633. });
  40634. Object.defineProperty(PerformanceMonitor.prototype, "instantaneousFrameTime", {
  40635. /**
  40636. * Returns the frame time of the most recent frame
  40637. * @return Frame time in milliseconds
  40638. */
  40639. get: function () {
  40640. return this._rollingFrameTime.history(0);
  40641. },
  40642. enumerable: true,
  40643. configurable: true
  40644. });
  40645. Object.defineProperty(PerformanceMonitor.prototype, "averageFPS", {
  40646. /**
  40647. * Returns the average framerate in frames per second over the sliding window (or the subset of frames sampled so far)
  40648. * @return Framerate in frames per second
  40649. */
  40650. get: function () {
  40651. return 1000.0 / this._rollingFrameTime.average;
  40652. },
  40653. enumerable: true,
  40654. configurable: true
  40655. });
  40656. Object.defineProperty(PerformanceMonitor.prototype, "instantaneousFPS", {
  40657. /**
  40658. * Returns the average framerate in frames per second using the most recent frame time
  40659. * @return Framerate in frames per second
  40660. */
  40661. get: function () {
  40662. var history = this._rollingFrameTime.history(0);
  40663. if (history === 0) {
  40664. return 0;
  40665. }
  40666. return 1000.0 / history;
  40667. },
  40668. enumerable: true,
  40669. configurable: true
  40670. });
  40671. Object.defineProperty(PerformanceMonitor.prototype, "isSaturated", {
  40672. /**
  40673. * Returns true if enough samples have been taken to completely fill the sliding window
  40674. * @return true if saturated
  40675. */
  40676. get: function () {
  40677. return this._rollingFrameTime.isSaturated();
  40678. },
  40679. enumerable: true,
  40680. configurable: true
  40681. });
  40682. /**
  40683. * Enables contributions to the sliding window sample set
  40684. */
  40685. PerformanceMonitor.prototype.enable = function () {
  40686. this._enabled = true;
  40687. };
  40688. /**
  40689. * Disables contributions to the sliding window sample set
  40690. * Samples will not be interpolated over the disabled period
  40691. */
  40692. PerformanceMonitor.prototype.disable = function () {
  40693. this._enabled = false;
  40694. //clear last sample to avoid interpolating over the disabled period when next enabled
  40695. this._lastFrameTimeMs = null;
  40696. };
  40697. Object.defineProperty(PerformanceMonitor.prototype, "isEnabled", {
  40698. /**
  40699. * Returns true if sampling is enabled
  40700. * @return true if enabled
  40701. */
  40702. get: function () {
  40703. return this._enabled;
  40704. },
  40705. enumerable: true,
  40706. configurable: true
  40707. });
  40708. /**
  40709. * Resets performance monitor
  40710. */
  40711. PerformanceMonitor.prototype.reset = function () {
  40712. //clear last sample to avoid interpolating over the disabled period when next enabled
  40713. this._lastFrameTimeMs = null;
  40714. //wipe record
  40715. this._rollingFrameTime.reset();
  40716. };
  40717. return PerformanceMonitor;
  40718. }());
  40719. BABYLON.PerformanceMonitor = PerformanceMonitor;
  40720. /**
  40721. * RollingAverage
  40722. *
  40723. * Utility to efficiently compute the rolling average and variance over a sliding window of samples
  40724. */
  40725. var RollingAverage = /** @class */ (function () {
  40726. /**
  40727. * constructor
  40728. * @param length The number of samples required to saturate the sliding window
  40729. */
  40730. function RollingAverage(length) {
  40731. this._samples = new Array(length);
  40732. this.reset();
  40733. }
  40734. /**
  40735. * Adds a sample to the sample set
  40736. * @param v The sample value
  40737. */
  40738. RollingAverage.prototype.add = function (v) {
  40739. //http://en.wikipedia.org/wiki/Algorithms_for_calculating_variance
  40740. var delta;
  40741. //we need to check if we've already wrapped round
  40742. if (this.isSaturated()) {
  40743. //remove bottom of stack from mean
  40744. var bottomValue = this._samples[this._pos];
  40745. delta = bottomValue - this.average;
  40746. this.average -= delta / (this._sampleCount - 1);
  40747. this._m2 -= delta * (bottomValue - this.average);
  40748. }
  40749. else {
  40750. this._sampleCount++;
  40751. }
  40752. //add new value to mean
  40753. delta = v - this.average;
  40754. this.average += delta / (this._sampleCount);
  40755. this._m2 += delta * (v - this.average);
  40756. //set the new variance
  40757. this.variance = this._m2 / (this._sampleCount - 1);
  40758. this._samples[this._pos] = v;
  40759. this._pos++;
  40760. this._pos %= this._samples.length; //positive wrap around
  40761. };
  40762. /**
  40763. * Returns previously added values or null if outside of history or outside the sliding window domain
  40764. * @param i Index in history. For example, pass 0 for the most recent value and 1 for the value before that
  40765. * @return Value previously recorded with add() or null if outside of range
  40766. */
  40767. RollingAverage.prototype.history = function (i) {
  40768. if ((i >= this._sampleCount) || (i >= this._samples.length)) {
  40769. return 0;
  40770. }
  40771. var i0 = this._wrapPosition(this._pos - 1.0);
  40772. return this._samples[this._wrapPosition(i0 - i)];
  40773. };
  40774. /**
  40775. * Returns true if enough samples have been taken to completely fill the sliding window
  40776. * @return true if sample-set saturated
  40777. */
  40778. RollingAverage.prototype.isSaturated = function () {
  40779. return this._sampleCount >= this._samples.length;
  40780. };
  40781. /**
  40782. * Resets the rolling average (equivalent to 0 samples taken so far)
  40783. */
  40784. RollingAverage.prototype.reset = function () {
  40785. this.average = 0;
  40786. this.variance = 0;
  40787. this._sampleCount = 0;
  40788. this._pos = 0;
  40789. this._m2 = 0;
  40790. };
  40791. /**
  40792. * Wraps a value around the sample range boundaries
  40793. * @param i Position in sample range, for example if the sample length is 5, and i is -3, then 2 will be returned.
  40794. * @return Wrapped position in sample range
  40795. */
  40796. RollingAverage.prototype._wrapPosition = function (i) {
  40797. var max = this._samples.length;
  40798. return ((i % max) + max) % max;
  40799. };
  40800. return RollingAverage;
  40801. }());
  40802. BABYLON.RollingAverage = RollingAverage;
  40803. })(BABYLON || (BABYLON = {}));
  40804. //# sourceMappingURL=babylon.performanceMonitor.js.map
  40805. var BABYLON;
  40806. (function (BABYLON) {
  40807. /**
  40808. * This groups together the common properties used for image processing either in direct forward pass
  40809. * or through post processing effect depending on the use of the image processing pipeline in your scene
  40810. * or not.
  40811. */
  40812. var ImageProcessingConfiguration = /** @class */ (function () {
  40813. function ImageProcessingConfiguration() {
  40814. /**
  40815. * Color curves setup used in the effect if colorCurvesEnabled is set to true
  40816. */
  40817. this.colorCurves = new BABYLON.ColorCurves();
  40818. this._colorCurvesEnabled = false;
  40819. this._colorGradingEnabled = false;
  40820. this._colorGradingWithGreenDepth = true;
  40821. this._colorGradingBGR = true;
  40822. this._exposure = 1.0;
  40823. this._toneMappingEnabled = false;
  40824. this._contrast = 1.0;
  40825. /**
  40826. * Vignette stretch size.
  40827. */
  40828. this.vignetteStretch = 0;
  40829. /**
  40830. * Vignette centre X Offset.
  40831. */
  40832. this.vignetteCentreX = 0;
  40833. /**
  40834. * Vignette centre Y Offset.
  40835. */
  40836. this.vignetteCentreY = 0;
  40837. /**
  40838. * Vignette weight or intensity of the vignette effect.
  40839. */
  40840. this.vignetteWeight = 1.5;
  40841. /**
  40842. * Color of the vignette applied on the screen through the chosen blend mode (vignetteBlendMode)
  40843. * if vignetteEnabled is set to true.
  40844. */
  40845. this.vignetteColor = new BABYLON.Color4(0, 0, 0, 0);
  40846. /**
  40847. * Camera field of view used by the Vignette effect.
  40848. */
  40849. this.vignetteCameraFov = 0.5;
  40850. this._vignetteBlendMode = ImageProcessingConfiguration.VIGNETTEMODE_MULTIPLY;
  40851. this._vignetteEnabled = false;
  40852. this._applyByPostProcess = false;
  40853. this._isEnabled = true;
  40854. /**
  40855. * An event triggered when the configuration changes and requires Shader to Update some parameters.
  40856. */
  40857. this.onUpdateParameters = new BABYLON.Observable();
  40858. }
  40859. Object.defineProperty(ImageProcessingConfiguration.prototype, "colorCurvesEnabled", {
  40860. /**
  40861. * Gets wether the color curves effect is enabled.
  40862. */
  40863. get: function () {
  40864. return this._colorCurvesEnabled;
  40865. },
  40866. /**
  40867. * Sets wether the color curves effect is enabled.
  40868. */
  40869. set: function (value) {
  40870. if (this._colorCurvesEnabled === value) {
  40871. return;
  40872. }
  40873. this._colorCurvesEnabled = value;
  40874. this._updateParameters();
  40875. },
  40876. enumerable: true,
  40877. configurable: true
  40878. });
  40879. Object.defineProperty(ImageProcessingConfiguration.prototype, "colorGradingEnabled", {
  40880. /**
  40881. * Gets wether the color grading effect is enabled.
  40882. */
  40883. get: function () {
  40884. return this._colorGradingEnabled;
  40885. },
  40886. /**
  40887. * Sets wether the color grading effect is enabled.
  40888. */
  40889. set: function (value) {
  40890. if (this._colorGradingEnabled === value) {
  40891. return;
  40892. }
  40893. this._colorGradingEnabled = value;
  40894. this._updateParameters();
  40895. },
  40896. enumerable: true,
  40897. configurable: true
  40898. });
  40899. Object.defineProperty(ImageProcessingConfiguration.prototype, "colorGradingWithGreenDepth", {
  40900. /**
  40901. * Gets wether the color grading effect is using a green depth for the 3d Texture.
  40902. */
  40903. get: function () {
  40904. return this._colorGradingWithGreenDepth;
  40905. },
  40906. /**
  40907. * Sets wether the color grading effect is using a green depth for the 3d Texture.
  40908. */
  40909. set: function (value) {
  40910. if (this._colorGradingWithGreenDepth === value) {
  40911. return;
  40912. }
  40913. this._colorGradingWithGreenDepth = value;
  40914. this._updateParameters();
  40915. },
  40916. enumerable: true,
  40917. configurable: true
  40918. });
  40919. Object.defineProperty(ImageProcessingConfiguration.prototype, "colorGradingBGR", {
  40920. /**
  40921. * Gets wether the color grading texture contains BGR values.
  40922. */
  40923. get: function () {
  40924. return this._colorGradingBGR;
  40925. },
  40926. /**
  40927. * Sets wether the color grading texture contains BGR values.
  40928. */
  40929. set: function (value) {
  40930. if (this._colorGradingBGR === value) {
  40931. return;
  40932. }
  40933. this._colorGradingBGR = value;
  40934. this._updateParameters();
  40935. },
  40936. enumerable: true,
  40937. configurable: true
  40938. });
  40939. Object.defineProperty(ImageProcessingConfiguration.prototype, "exposure", {
  40940. /**
  40941. * Gets the Exposure used in the effect.
  40942. */
  40943. get: function () {
  40944. return this._exposure;
  40945. },
  40946. /**
  40947. * Sets the Exposure used in the effect.
  40948. */
  40949. set: function (value) {
  40950. if (this._exposure === value) {
  40951. return;
  40952. }
  40953. this._exposure = value;
  40954. this._updateParameters();
  40955. },
  40956. enumerable: true,
  40957. configurable: true
  40958. });
  40959. Object.defineProperty(ImageProcessingConfiguration.prototype, "toneMappingEnabled", {
  40960. /**
  40961. * Gets wether the tone mapping effect is enabled.
  40962. */
  40963. get: function () {
  40964. return this._toneMappingEnabled;
  40965. },
  40966. /**
  40967. * Sets wether the tone mapping effect is enabled.
  40968. */
  40969. set: function (value) {
  40970. if (this._toneMappingEnabled === value) {
  40971. return;
  40972. }
  40973. this._toneMappingEnabled = value;
  40974. this._updateParameters();
  40975. },
  40976. enumerable: true,
  40977. configurable: true
  40978. });
  40979. Object.defineProperty(ImageProcessingConfiguration.prototype, "contrast", {
  40980. /**
  40981. * Gets the contrast used in the effect.
  40982. */
  40983. get: function () {
  40984. return this._contrast;
  40985. },
  40986. /**
  40987. * Sets the contrast used in the effect.
  40988. */
  40989. set: function (value) {
  40990. if (this._contrast === value) {
  40991. return;
  40992. }
  40993. this._contrast = value;
  40994. this._updateParameters();
  40995. },
  40996. enumerable: true,
  40997. configurable: true
  40998. });
  40999. Object.defineProperty(ImageProcessingConfiguration.prototype, "vignetteBlendMode", {
  41000. /**
  41001. * Gets the vignette blend mode allowing different kind of effect.
  41002. */
  41003. get: function () {
  41004. return this._vignetteBlendMode;
  41005. },
  41006. /**
  41007. * Sets the vignette blend mode allowing different kind of effect.
  41008. */
  41009. set: function (value) {
  41010. if (this._vignetteBlendMode === value) {
  41011. return;
  41012. }
  41013. this._vignetteBlendMode = value;
  41014. this._updateParameters();
  41015. },
  41016. enumerable: true,
  41017. configurable: true
  41018. });
  41019. Object.defineProperty(ImageProcessingConfiguration.prototype, "vignetteEnabled", {
  41020. /**
  41021. * Gets wether the vignette effect is enabled.
  41022. */
  41023. get: function () {
  41024. return this._vignetteEnabled;
  41025. },
  41026. /**
  41027. * Sets wether the vignette effect is enabled.
  41028. */
  41029. set: function (value) {
  41030. if (this._vignetteEnabled === value) {
  41031. return;
  41032. }
  41033. this._vignetteEnabled = value;
  41034. this._updateParameters();
  41035. },
  41036. enumerable: true,
  41037. configurable: true
  41038. });
  41039. Object.defineProperty(ImageProcessingConfiguration.prototype, "applyByPostProcess", {
  41040. /**
  41041. * Gets wether the image processing is applied through a post process or not.
  41042. */
  41043. get: function () {
  41044. return this._applyByPostProcess;
  41045. },
  41046. /**
  41047. * Sets wether the image processing is applied through a post process or not.
  41048. */
  41049. set: function (value) {
  41050. if (this._applyByPostProcess === value) {
  41051. return;
  41052. }
  41053. this._applyByPostProcess = value;
  41054. this._updateParameters();
  41055. },
  41056. enumerable: true,
  41057. configurable: true
  41058. });
  41059. Object.defineProperty(ImageProcessingConfiguration.prototype, "isEnabled", {
  41060. /**
  41061. * Gets wether the image processing is enabled or not.
  41062. */
  41063. get: function () {
  41064. return this._isEnabled;
  41065. },
  41066. /**
  41067. * Sets wether the image processing is enabled or not.
  41068. */
  41069. set: function (value) {
  41070. if (this._isEnabled === value) {
  41071. return;
  41072. }
  41073. this._isEnabled = value;
  41074. this._updateParameters();
  41075. },
  41076. enumerable: true,
  41077. configurable: true
  41078. });
  41079. /**
  41080. * Method called each time the image processing information changes requires to recompile the effect.
  41081. */
  41082. ImageProcessingConfiguration.prototype._updateParameters = function () {
  41083. this.onUpdateParameters.notifyObservers(this);
  41084. };
  41085. ImageProcessingConfiguration.prototype.getClassName = function () {
  41086. return "ImageProcessingConfiguration";
  41087. };
  41088. /**
  41089. * Prepare the list of uniforms associated with the Image Processing effects.
  41090. * @param uniformsList The list of uniforms used in the effect
  41091. * @param defines the list of defines currently in use
  41092. */
  41093. ImageProcessingConfiguration.PrepareUniforms = function (uniforms, defines) {
  41094. if (defines.EXPOSURE) {
  41095. uniforms.push("exposureLinear");
  41096. }
  41097. if (defines.CONTRAST) {
  41098. uniforms.push("contrast");
  41099. }
  41100. if (defines.COLORGRADING) {
  41101. uniforms.push("colorTransformSettings");
  41102. }
  41103. if (defines.VIGNETTE) {
  41104. uniforms.push("vInverseScreenSize");
  41105. uniforms.push("vignetteSettings1");
  41106. uniforms.push("vignetteSettings2");
  41107. }
  41108. if (defines.COLORCURVES) {
  41109. BABYLON.ColorCurves.PrepareUniforms(uniforms);
  41110. }
  41111. };
  41112. /**
  41113. * Prepare the list of samplers associated with the Image Processing effects.
  41114. * @param uniformsList The list of uniforms used in the effect
  41115. * @param defines the list of defines currently in use
  41116. */
  41117. ImageProcessingConfiguration.PrepareSamplers = function (samplersList, defines) {
  41118. if (defines.COLORGRADING) {
  41119. samplersList.push("txColorTransform");
  41120. }
  41121. };
  41122. /**
  41123. * Prepare the list of defines associated to the shader.
  41124. * @param defines the list of defines to complete
  41125. */
  41126. ImageProcessingConfiguration.prototype.prepareDefines = function (defines, forPostProcess) {
  41127. if (forPostProcess === void 0) { forPostProcess = false; }
  41128. if (forPostProcess !== this.applyByPostProcess || !this._isEnabled) {
  41129. defines.VIGNETTE = false;
  41130. defines.TONEMAPPING = false;
  41131. defines.CONTRAST = false;
  41132. defines.EXPOSURE = false;
  41133. defines.COLORCURVES = false;
  41134. defines.COLORGRADING = false;
  41135. defines.COLORGRADING3D = false;
  41136. defines.IMAGEPROCESSING = false;
  41137. defines.IMAGEPROCESSINGPOSTPROCESS = this.applyByPostProcess && this._isEnabled;
  41138. return;
  41139. }
  41140. defines.VIGNETTE = this.vignetteEnabled;
  41141. defines.VIGNETTEBLENDMODEMULTIPLY = (this.vignetteBlendMode === ImageProcessingConfiguration._VIGNETTEMODE_MULTIPLY);
  41142. defines.VIGNETTEBLENDMODEOPAQUE = !defines.VIGNETTEBLENDMODEMULTIPLY;
  41143. defines.TONEMAPPING = this.toneMappingEnabled;
  41144. defines.CONTRAST = (this.contrast !== 1.0);
  41145. defines.EXPOSURE = (this.exposure !== 1.0);
  41146. defines.COLORCURVES = (this.colorCurvesEnabled && !!this.colorCurves);
  41147. defines.COLORGRADING = (this.colorGradingEnabled && !!this.colorGradingTexture);
  41148. if (defines.COLORGRADING) {
  41149. defines.COLORGRADING3D = this.colorGradingTexture.is3D;
  41150. }
  41151. else {
  41152. defines.COLORGRADING3D = false;
  41153. }
  41154. defines.SAMPLER3DGREENDEPTH = this.colorGradingWithGreenDepth;
  41155. defines.SAMPLER3DBGRMAP = this.colorGradingBGR;
  41156. defines.IMAGEPROCESSINGPOSTPROCESS = this.applyByPostProcess;
  41157. defines.IMAGEPROCESSING = defines.VIGNETTE || defines.TONEMAPPING || defines.CONTRAST || defines.EXPOSURE || defines.COLORCURVES || defines.COLORGRADING;
  41158. };
  41159. /**
  41160. * Returns true if all the image processing information are ready.
  41161. */
  41162. ImageProcessingConfiguration.prototype.isReady = function () {
  41163. // Color Grading texure can not be none blocking.
  41164. return !this.colorGradingEnabled || !this.colorGradingTexture || this.colorGradingTexture.isReady();
  41165. };
  41166. /**
  41167. * Binds the image processing to the shader.
  41168. * @param effect The effect to bind to
  41169. */
  41170. ImageProcessingConfiguration.prototype.bind = function (effect, aspectRatio) {
  41171. if (aspectRatio === void 0) { aspectRatio = 1; }
  41172. // Color Curves
  41173. if (this._colorCurvesEnabled && this.colorCurves) {
  41174. BABYLON.ColorCurves.Bind(this.colorCurves, effect);
  41175. }
  41176. // Vignette
  41177. if (this._vignetteEnabled) {
  41178. var inverseWidth = 1 / effect.getEngine().getRenderWidth();
  41179. var inverseHeight = 1 / effect.getEngine().getRenderHeight();
  41180. effect.setFloat2("vInverseScreenSize", inverseWidth, inverseHeight);
  41181. var vignetteScaleY = Math.tan(this.vignetteCameraFov * 0.5);
  41182. var vignetteScaleX = vignetteScaleY * aspectRatio;
  41183. var vignetteScaleGeometricMean = Math.sqrt(vignetteScaleX * vignetteScaleY);
  41184. vignetteScaleX = BABYLON.Tools.Mix(vignetteScaleX, vignetteScaleGeometricMean, this.vignetteStretch);
  41185. vignetteScaleY = BABYLON.Tools.Mix(vignetteScaleY, vignetteScaleGeometricMean, this.vignetteStretch);
  41186. effect.setFloat4("vignetteSettings1", vignetteScaleX, vignetteScaleY, -vignetteScaleX * this.vignetteCentreX, -vignetteScaleY * this.vignetteCentreY);
  41187. var vignettePower = -2.0 * this.vignetteWeight;
  41188. effect.setFloat4("vignetteSettings2", this.vignetteColor.r, this.vignetteColor.g, this.vignetteColor.b, vignettePower);
  41189. }
  41190. // Exposure
  41191. effect.setFloat("exposureLinear", this.exposure);
  41192. // Contrast
  41193. effect.setFloat("contrast", this.contrast);
  41194. // Color transform settings
  41195. if (this.colorGradingTexture) {
  41196. effect.setTexture("txColorTransform", this.colorGradingTexture);
  41197. var textureSize = this.colorGradingTexture.getSize().height;
  41198. effect.setFloat4("colorTransformSettings", (textureSize - 1) / textureSize, // textureScale
  41199. 0.5 / textureSize, // textureOffset
  41200. textureSize, // textureSize
  41201. this.colorGradingTexture.level // weight
  41202. );
  41203. }
  41204. };
  41205. /**
  41206. * Clones the current image processing instance.
  41207. * @return The cloned image processing
  41208. */
  41209. ImageProcessingConfiguration.prototype.clone = function () {
  41210. return BABYLON.SerializationHelper.Clone(function () { return new ImageProcessingConfiguration(); }, this);
  41211. };
  41212. /**
  41213. * Serializes the current image processing instance to a json representation.
  41214. * @return a JSON representation
  41215. */
  41216. ImageProcessingConfiguration.prototype.serialize = function () {
  41217. return BABYLON.SerializationHelper.Serialize(this);
  41218. };
  41219. /**
  41220. * Parses the image processing from a json representation.
  41221. * @param source the JSON source to parse
  41222. * @return The parsed image processing
  41223. */
  41224. ImageProcessingConfiguration.Parse = function (source) {
  41225. return BABYLON.SerializationHelper.Parse(function () { return new ImageProcessingConfiguration(); }, source, null, null);
  41226. };
  41227. Object.defineProperty(ImageProcessingConfiguration, "VIGNETTEMODE_MULTIPLY", {
  41228. /**
  41229. * Used to apply the vignette as a mix with the pixel color.
  41230. */
  41231. get: function () {
  41232. return this._VIGNETTEMODE_MULTIPLY;
  41233. },
  41234. enumerable: true,
  41235. configurable: true
  41236. });
  41237. Object.defineProperty(ImageProcessingConfiguration, "VIGNETTEMODE_OPAQUE", {
  41238. /**
  41239. * Used to apply the vignette as a replacement of the pixel color.
  41240. */
  41241. get: function () {
  41242. return this._VIGNETTEMODE_OPAQUE;
  41243. },
  41244. enumerable: true,
  41245. configurable: true
  41246. });
  41247. // Static constants associated to the image processing.
  41248. ImageProcessingConfiguration._VIGNETTEMODE_MULTIPLY = 0;
  41249. ImageProcessingConfiguration._VIGNETTEMODE_OPAQUE = 1;
  41250. __decorate([
  41251. BABYLON.serializeAsColorCurves()
  41252. ], ImageProcessingConfiguration.prototype, "colorCurves", void 0);
  41253. __decorate([
  41254. BABYLON.serialize()
  41255. ], ImageProcessingConfiguration.prototype, "_colorCurvesEnabled", void 0);
  41256. __decorate([
  41257. BABYLON.serializeAsTexture()
  41258. ], ImageProcessingConfiguration.prototype, "colorGradingTexture", void 0);
  41259. __decorate([
  41260. BABYLON.serialize()
  41261. ], ImageProcessingConfiguration.prototype, "_colorGradingEnabled", void 0);
  41262. __decorate([
  41263. BABYLON.serialize()
  41264. ], ImageProcessingConfiguration.prototype, "_colorGradingWithGreenDepth", void 0);
  41265. __decorate([
  41266. BABYLON.serialize()
  41267. ], ImageProcessingConfiguration.prototype, "_colorGradingBGR", void 0);
  41268. __decorate([
  41269. BABYLON.serialize()
  41270. ], ImageProcessingConfiguration.prototype, "_exposure", void 0);
  41271. __decorate([
  41272. BABYLON.serialize()
  41273. ], ImageProcessingConfiguration.prototype, "_toneMappingEnabled", void 0);
  41274. __decorate([
  41275. BABYLON.serialize()
  41276. ], ImageProcessingConfiguration.prototype, "_contrast", void 0);
  41277. __decorate([
  41278. BABYLON.serialize()
  41279. ], ImageProcessingConfiguration.prototype, "vignetteStretch", void 0);
  41280. __decorate([
  41281. BABYLON.serialize()
  41282. ], ImageProcessingConfiguration.prototype, "vignetteCentreX", void 0);
  41283. __decorate([
  41284. BABYLON.serialize()
  41285. ], ImageProcessingConfiguration.prototype, "vignetteCentreY", void 0);
  41286. __decorate([
  41287. BABYLON.serialize()
  41288. ], ImageProcessingConfiguration.prototype, "vignetteWeight", void 0);
  41289. __decorate([
  41290. BABYLON.serializeAsColor4()
  41291. ], ImageProcessingConfiguration.prototype, "vignetteColor", void 0);
  41292. __decorate([
  41293. BABYLON.serialize()
  41294. ], ImageProcessingConfiguration.prototype, "vignetteCameraFov", void 0);
  41295. __decorate([
  41296. BABYLON.serialize()
  41297. ], ImageProcessingConfiguration.prototype, "_vignetteBlendMode", void 0);
  41298. __decorate([
  41299. BABYLON.serialize()
  41300. ], ImageProcessingConfiguration.prototype, "_vignetteEnabled", void 0);
  41301. __decorate([
  41302. BABYLON.serialize()
  41303. ], ImageProcessingConfiguration.prototype, "_applyByPostProcess", void 0);
  41304. __decorate([
  41305. BABYLON.serialize()
  41306. ], ImageProcessingConfiguration.prototype, "_isEnabled", void 0);
  41307. return ImageProcessingConfiguration;
  41308. }());
  41309. BABYLON.ImageProcessingConfiguration = ImageProcessingConfiguration;
  41310. })(BABYLON || (BABYLON = {}));
  41311. //# sourceMappingURL=babylon.imageProcessingConfiguration.js.map
  41312. var BABYLON;
  41313. (function (BABYLON) {
  41314. /**
  41315. * This represents a color grading texture. This acts as a lookup table LUT, useful during post process
  41316. * It can help converting any input color in a desired output one. This can then be used to create effects
  41317. * from sepia, black and white to sixties or futuristic rendering...
  41318. *
  41319. * The only supported format is currently 3dl.
  41320. * More information on LUT: https://en.wikipedia.org/wiki/3D_lookup_table/
  41321. */
  41322. var ColorGradingTexture = /** @class */ (function (_super) {
  41323. __extends(ColorGradingTexture, _super);
  41324. /**
  41325. * Instantiates a ColorGradingTexture from the following parameters.
  41326. *
  41327. * @param url The location of the color gradind data (currently only supporting 3dl)
  41328. * @param scene The scene the texture will be used in
  41329. */
  41330. function ColorGradingTexture(url, scene) {
  41331. var _this = _super.call(this, scene) || this;
  41332. if (!url) {
  41333. return _this;
  41334. }
  41335. _this._engine = scene.getEngine();
  41336. _this._textureMatrix = BABYLON.Matrix.Identity();
  41337. _this.name = url;
  41338. _this.url = url;
  41339. _this.hasAlpha = false;
  41340. _this.isCube = false;
  41341. _this.is3D = _this._engine.webGLVersion > 1;
  41342. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  41343. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  41344. _this.wrapR = BABYLON.Texture.CLAMP_ADDRESSMODE;
  41345. _this.anisotropicFilteringLevel = 1;
  41346. _this._texture = _this._getFromCache(url, true);
  41347. if (!_this._texture) {
  41348. if (!scene.useDelayedTextureLoading) {
  41349. _this.loadTexture();
  41350. }
  41351. else {
  41352. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  41353. }
  41354. }
  41355. return _this;
  41356. }
  41357. /**
  41358. * Returns the texture matrix used in most of the material.
  41359. * This is not used in color grading but keep for troubleshooting purpose (easily swap diffuse by colorgrading to look in).
  41360. */
  41361. ColorGradingTexture.prototype.getTextureMatrix = function () {
  41362. return this._textureMatrix;
  41363. };
  41364. /**
  41365. * Occurs when the file being loaded is a .3dl LUT file.
  41366. */
  41367. ColorGradingTexture.prototype.load3dlTexture = function () {
  41368. var engine = this._engine;
  41369. var texture;
  41370. if (engine.webGLVersion === 1) {
  41371. texture = engine.createRawTexture(null, 1, 1, BABYLON.Engine.TEXTUREFORMAT_RGBA, false, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  41372. }
  41373. else {
  41374. texture = engine.createRawTexture3D(null, 1, 1, 1, BABYLON.Engine.TEXTUREFORMAT_RGBA, false, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  41375. }
  41376. this._texture = texture;
  41377. var callback = function (text) {
  41378. if (typeof text !== "string") {
  41379. return;
  41380. }
  41381. var data = null;
  41382. var tempData = null;
  41383. var line;
  41384. var lines = text.split('\n');
  41385. var size = 0, pixelIndexW = 0, pixelIndexH = 0, pixelIndexSlice = 0;
  41386. var maxColor = 0;
  41387. for (var i = 0; i < lines.length; i++) {
  41388. line = lines[i];
  41389. if (!ColorGradingTexture._noneEmptyLineRegex.test(line))
  41390. continue;
  41391. if (line.indexOf('#') === 0)
  41392. continue;
  41393. var words = line.split(" ");
  41394. if (size === 0) {
  41395. // Number of space + one
  41396. size = words.length;
  41397. data = new Uint8Array(size * size * size * 4); // volume texture of side size and rgb 8
  41398. tempData = new Float32Array(size * size * size * 4);
  41399. continue;
  41400. }
  41401. if (size != 0) {
  41402. var r = Math.max(parseInt(words[0]), 0);
  41403. var g = Math.max(parseInt(words[1]), 0);
  41404. var b = Math.max(parseInt(words[2]), 0);
  41405. maxColor = Math.max(r, maxColor);
  41406. maxColor = Math.max(g, maxColor);
  41407. maxColor = Math.max(b, maxColor);
  41408. var pixelStorageIndex = (pixelIndexW + pixelIndexSlice * size + pixelIndexH * size * size) * 4;
  41409. if (tempData) {
  41410. tempData[pixelStorageIndex + 0] = r;
  41411. tempData[pixelStorageIndex + 1] = g;
  41412. tempData[pixelStorageIndex + 2] = b;
  41413. }
  41414. pixelIndexSlice++;
  41415. if (pixelIndexSlice % size == 0) {
  41416. pixelIndexH++;
  41417. pixelIndexSlice = 0;
  41418. if (pixelIndexH % size == 0) {
  41419. pixelIndexW++;
  41420. pixelIndexH = 0;
  41421. }
  41422. }
  41423. }
  41424. }
  41425. if (tempData && data) {
  41426. for (var i = 0; i < tempData.length; i++) {
  41427. if (i > 0 && (i + 1) % 4 === 0) {
  41428. data[i] = 255;
  41429. }
  41430. else {
  41431. var value = tempData[i];
  41432. data[i] = (value / maxColor * 255);
  41433. }
  41434. }
  41435. }
  41436. if (texture.is3D) {
  41437. texture.updateSize(size, size, size);
  41438. engine.updateRawTexture3D(texture, data, BABYLON.Engine.TEXTUREFORMAT_RGBA, false);
  41439. }
  41440. else {
  41441. texture.updateSize(size * size, size);
  41442. engine.updateRawTexture(texture, data, BABYLON.Engine.TEXTUREFORMAT_RGBA, false);
  41443. }
  41444. };
  41445. var scene = this.getScene();
  41446. if (scene) {
  41447. scene._loadFile(this.url, callback);
  41448. }
  41449. else {
  41450. this._engine._loadFile(this.url, callback);
  41451. }
  41452. return this._texture;
  41453. };
  41454. /**
  41455. * Starts the loading process of the texture.
  41456. */
  41457. ColorGradingTexture.prototype.loadTexture = function () {
  41458. if (this.url && this.url.toLocaleLowerCase().indexOf(".3dl") == (this.url.length - 4)) {
  41459. this.load3dlTexture();
  41460. }
  41461. };
  41462. /**
  41463. * Clones the color gradind texture.
  41464. */
  41465. ColorGradingTexture.prototype.clone = function () {
  41466. var newTexture = new ColorGradingTexture(this.url, this.getScene());
  41467. // Base texture
  41468. newTexture.level = this.level;
  41469. return newTexture;
  41470. };
  41471. /**
  41472. * Called during delayed load for textures.
  41473. */
  41474. ColorGradingTexture.prototype.delayLoad = function () {
  41475. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  41476. return;
  41477. }
  41478. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  41479. this._texture = this._getFromCache(this.url, true);
  41480. if (!this._texture) {
  41481. this.loadTexture();
  41482. }
  41483. };
  41484. /**
  41485. * Parses a color grading texture serialized by Babylon.
  41486. * @param parsedTexture The texture information being parsedTexture
  41487. * @param scene The scene to load the texture in
  41488. * @param rootUrl The root url of the data assets to load
  41489. * @return A color gradind texture
  41490. */
  41491. ColorGradingTexture.Parse = function (parsedTexture, scene, rootUrl) {
  41492. var texture = null;
  41493. if (parsedTexture.name && !parsedTexture.isRenderTarget) {
  41494. texture = new ColorGradingTexture(parsedTexture.name, scene);
  41495. texture.name = parsedTexture.name;
  41496. texture.level = parsedTexture.level;
  41497. }
  41498. return texture;
  41499. };
  41500. /**
  41501. * Serializes the LUT texture to json format.
  41502. */
  41503. ColorGradingTexture.prototype.serialize = function () {
  41504. if (!this.name) {
  41505. return null;
  41506. }
  41507. var serializationObject = {};
  41508. serializationObject.name = this.name;
  41509. serializationObject.level = this.level;
  41510. serializationObject.customType = "BABYLON.ColorGradingTexture";
  41511. return serializationObject;
  41512. };
  41513. /**
  41514. * Empty line regex stored for GC.
  41515. */
  41516. ColorGradingTexture._noneEmptyLineRegex = /\S+/;
  41517. return ColorGradingTexture;
  41518. }(BABYLON.BaseTexture));
  41519. BABYLON.ColorGradingTexture = ColorGradingTexture;
  41520. })(BABYLON || (BABYLON = {}));
  41521. //# sourceMappingURL=babylon.colorGradingTexture.js.map
  41522. var BABYLON;
  41523. (function (BABYLON) {
  41524. /**
  41525. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  41526. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  41527. * 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;
  41528. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  41529. */
  41530. var ColorCurves = /** @class */ (function () {
  41531. function ColorCurves() {
  41532. this._dirty = true;
  41533. this._tempColor = new BABYLON.Color4(0, 0, 0, 0);
  41534. this._globalCurve = new BABYLON.Color4(0, 0, 0, 0);
  41535. this._highlightsCurve = new BABYLON.Color4(0, 0, 0, 0);
  41536. this._midtonesCurve = new BABYLON.Color4(0, 0, 0, 0);
  41537. this._shadowsCurve = new BABYLON.Color4(0, 0, 0, 0);
  41538. this._positiveCurve = new BABYLON.Color4(0, 0, 0, 0);
  41539. this._negativeCurve = new BABYLON.Color4(0, 0, 0, 0);
  41540. this._globalHue = 30;
  41541. this._globalDensity = 0;
  41542. this._globalSaturation = 0;
  41543. this._globalExposure = 0;
  41544. this._highlightsHue = 30;
  41545. this._highlightsDensity = 0;
  41546. this._highlightsSaturation = 0;
  41547. this._highlightsExposure = 0;
  41548. this._midtonesHue = 30;
  41549. this._midtonesDensity = 0;
  41550. this._midtonesSaturation = 0;
  41551. this._midtonesExposure = 0;
  41552. this._shadowsHue = 30;
  41553. this._shadowsDensity = 0;
  41554. this._shadowsSaturation = 0;
  41555. this._shadowsExposure = 0;
  41556. }
  41557. Object.defineProperty(ColorCurves.prototype, "globalHue", {
  41558. /**
  41559. * Gets the global Hue value.
  41560. * 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).
  41561. */
  41562. get: function () {
  41563. return this._globalHue;
  41564. },
  41565. /**
  41566. * Sets the global Hue value.
  41567. * 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).
  41568. */
  41569. set: function (value) {
  41570. this._globalHue = value;
  41571. this._dirty = true;
  41572. },
  41573. enumerable: true,
  41574. configurable: true
  41575. });
  41576. Object.defineProperty(ColorCurves.prototype, "globalDensity", {
  41577. /**
  41578. * Gets the global Density value.
  41579. * 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.
  41580. * Values less than zero provide a filter of opposite hue.
  41581. */
  41582. get: function () {
  41583. return this._globalDensity;
  41584. },
  41585. /**
  41586. * Sets the global Density value.
  41587. * 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.
  41588. * Values less than zero provide a filter of opposite hue.
  41589. */
  41590. set: function (value) {
  41591. this._globalDensity = value;
  41592. this._dirty = true;
  41593. },
  41594. enumerable: true,
  41595. configurable: true
  41596. });
  41597. Object.defineProperty(ColorCurves.prototype, "globalSaturation", {
  41598. /**
  41599. * Gets the global Saturation value.
  41600. * 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.
  41601. */
  41602. get: function () {
  41603. return this._globalSaturation;
  41604. },
  41605. /**
  41606. * Sets the global Saturation value.
  41607. * 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.
  41608. */
  41609. set: function (value) {
  41610. this._globalSaturation = value;
  41611. this._dirty = true;
  41612. },
  41613. enumerable: true,
  41614. configurable: true
  41615. });
  41616. Object.defineProperty(ColorCurves.prototype, "highlightsHue", {
  41617. /**
  41618. * Gets the highlights Hue value.
  41619. * 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).
  41620. */
  41621. get: function () {
  41622. return this._highlightsHue;
  41623. },
  41624. /**
  41625. * Sets the highlights Hue value.
  41626. * 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).
  41627. */
  41628. set: function (value) {
  41629. this._highlightsHue = value;
  41630. this._dirty = true;
  41631. },
  41632. enumerable: true,
  41633. configurable: true
  41634. });
  41635. Object.defineProperty(ColorCurves.prototype, "highlightsDensity", {
  41636. /**
  41637. * Gets the highlights Density value.
  41638. * 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.
  41639. * Values less than zero provide a filter of opposite hue.
  41640. */
  41641. get: function () {
  41642. return this._highlightsDensity;
  41643. },
  41644. /**
  41645. * Sets the highlights Density value.
  41646. * 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.
  41647. * Values less than zero provide a filter of opposite hue.
  41648. */
  41649. set: function (value) {
  41650. this._highlightsDensity = value;
  41651. this._dirty = true;
  41652. },
  41653. enumerable: true,
  41654. configurable: true
  41655. });
  41656. Object.defineProperty(ColorCurves.prototype, "highlightsSaturation", {
  41657. /**
  41658. * Gets the highlights Saturation value.
  41659. * 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.
  41660. */
  41661. get: function () {
  41662. return this._highlightsSaturation;
  41663. },
  41664. /**
  41665. * Sets the highlights Saturation value.
  41666. * 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.
  41667. */
  41668. set: function (value) {
  41669. this._highlightsSaturation = value;
  41670. this._dirty = true;
  41671. },
  41672. enumerable: true,
  41673. configurable: true
  41674. });
  41675. Object.defineProperty(ColorCurves.prototype, "highlightsExposure", {
  41676. /**
  41677. * Gets the highlights Exposure value.
  41678. * 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.
  41679. */
  41680. get: function () {
  41681. return this._highlightsExposure;
  41682. },
  41683. /**
  41684. * Sets the highlights Exposure value.
  41685. * 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.
  41686. */
  41687. set: function (value) {
  41688. this._highlightsExposure = value;
  41689. this._dirty = true;
  41690. },
  41691. enumerable: true,
  41692. configurable: true
  41693. });
  41694. Object.defineProperty(ColorCurves.prototype, "midtonesHue", {
  41695. /**
  41696. * Gets the midtones Hue value.
  41697. * 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).
  41698. */
  41699. get: function () {
  41700. return this._midtonesHue;
  41701. },
  41702. /**
  41703. * Sets the midtones Hue value.
  41704. * 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).
  41705. */
  41706. set: function (value) {
  41707. this._midtonesHue = value;
  41708. this._dirty = true;
  41709. },
  41710. enumerable: true,
  41711. configurable: true
  41712. });
  41713. Object.defineProperty(ColorCurves.prototype, "midtonesDensity", {
  41714. /**
  41715. * Gets the midtones Density value.
  41716. * 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.
  41717. * Values less than zero provide a filter of opposite hue.
  41718. */
  41719. get: function () {
  41720. return this._midtonesDensity;
  41721. },
  41722. /**
  41723. * Sets the midtones Density value.
  41724. * 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.
  41725. * Values less than zero provide a filter of opposite hue.
  41726. */
  41727. set: function (value) {
  41728. this._midtonesDensity = value;
  41729. this._dirty = true;
  41730. },
  41731. enumerable: true,
  41732. configurable: true
  41733. });
  41734. Object.defineProperty(ColorCurves.prototype, "midtonesSaturation", {
  41735. /**
  41736. * Gets the midtones Saturation value.
  41737. * 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.
  41738. */
  41739. get: function () {
  41740. return this._midtonesSaturation;
  41741. },
  41742. /**
  41743. * Sets the midtones Saturation value.
  41744. * 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.
  41745. */
  41746. set: function (value) {
  41747. this._midtonesSaturation = value;
  41748. this._dirty = true;
  41749. },
  41750. enumerable: true,
  41751. configurable: true
  41752. });
  41753. Object.defineProperty(ColorCurves.prototype, "midtonesExposure", {
  41754. /**
  41755. * Gets the midtones Exposure value.
  41756. * 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.
  41757. */
  41758. get: function () {
  41759. return this._midtonesExposure;
  41760. },
  41761. /**
  41762. * Sets the midtones Exposure value.
  41763. * 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.
  41764. */
  41765. set: function (value) {
  41766. this._midtonesExposure = value;
  41767. this._dirty = true;
  41768. },
  41769. enumerable: true,
  41770. configurable: true
  41771. });
  41772. Object.defineProperty(ColorCurves.prototype, "shadowsHue", {
  41773. /**
  41774. * Gets the shadows Hue value.
  41775. * 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).
  41776. */
  41777. get: function () {
  41778. return this._shadowsHue;
  41779. },
  41780. /**
  41781. * Sets the shadows Hue value.
  41782. * 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).
  41783. */
  41784. set: function (value) {
  41785. this._shadowsHue = value;
  41786. this._dirty = true;
  41787. },
  41788. enumerable: true,
  41789. configurable: true
  41790. });
  41791. Object.defineProperty(ColorCurves.prototype, "shadowsDensity", {
  41792. /**
  41793. * Gets the shadows Density value.
  41794. * 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.
  41795. * Values less than zero provide a filter of opposite hue.
  41796. */
  41797. get: function () {
  41798. return this._shadowsDensity;
  41799. },
  41800. /**
  41801. * Sets the shadows Density value.
  41802. * 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.
  41803. * Values less than zero provide a filter of opposite hue.
  41804. */
  41805. set: function (value) {
  41806. this._shadowsDensity = value;
  41807. this._dirty = true;
  41808. },
  41809. enumerable: true,
  41810. configurable: true
  41811. });
  41812. Object.defineProperty(ColorCurves.prototype, "shadowsSaturation", {
  41813. /**
  41814. * Gets the shadows Saturation value.
  41815. * 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.
  41816. */
  41817. get: function () {
  41818. return this._shadowsSaturation;
  41819. },
  41820. /**
  41821. * Sets the shadows Saturation value.
  41822. * 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.
  41823. */
  41824. set: function (value) {
  41825. this._shadowsSaturation = value;
  41826. this._dirty = true;
  41827. },
  41828. enumerable: true,
  41829. configurable: true
  41830. });
  41831. Object.defineProperty(ColorCurves.prototype, "shadowsExposure", {
  41832. /**
  41833. * Gets the shadows Exposure value.
  41834. * 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.
  41835. */
  41836. get: function () {
  41837. return this._shadowsExposure;
  41838. },
  41839. /**
  41840. * Sets the shadows Exposure value.
  41841. * 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.
  41842. */
  41843. set: function (value) {
  41844. this._shadowsExposure = value;
  41845. this._dirty = true;
  41846. },
  41847. enumerable: true,
  41848. configurable: true
  41849. });
  41850. ColorCurves.prototype.getClassName = function () {
  41851. return "ColorCurves";
  41852. };
  41853. /**
  41854. * Binds the color curves to the shader.
  41855. * @param colorCurves The color curve to bind
  41856. * @param effect The effect to bind to
  41857. */
  41858. ColorCurves.Bind = function (colorCurves, effect, positiveUniform, neutralUniform, negativeUniform) {
  41859. if (positiveUniform === void 0) { positiveUniform = "vCameraColorCurvePositive"; }
  41860. if (neutralUniform === void 0) { neutralUniform = "vCameraColorCurveNeutral"; }
  41861. if (negativeUniform === void 0) { negativeUniform = "vCameraColorCurveNegative"; }
  41862. if (colorCurves._dirty) {
  41863. colorCurves._dirty = false;
  41864. // Fill in global info.
  41865. colorCurves.getColorGradingDataToRef(colorCurves._globalHue, colorCurves._globalDensity, colorCurves._globalSaturation, colorCurves._globalExposure, colorCurves._globalCurve);
  41866. // Compute highlights info.
  41867. colorCurves.getColorGradingDataToRef(colorCurves._highlightsHue, colorCurves._highlightsDensity, colorCurves._highlightsSaturation, colorCurves._highlightsExposure, colorCurves._tempColor);
  41868. colorCurves._tempColor.multiplyToRef(colorCurves._globalCurve, colorCurves._highlightsCurve);
  41869. // Compute midtones info.
  41870. colorCurves.getColorGradingDataToRef(colorCurves._midtonesHue, colorCurves._midtonesDensity, colorCurves._midtonesSaturation, colorCurves._midtonesExposure, colorCurves._tempColor);
  41871. colorCurves._tempColor.multiplyToRef(colorCurves._globalCurve, colorCurves._midtonesCurve);
  41872. // Compute shadows info.
  41873. colorCurves.getColorGradingDataToRef(colorCurves._shadowsHue, colorCurves._shadowsDensity, colorCurves._shadowsSaturation, colorCurves._shadowsExposure, colorCurves._tempColor);
  41874. colorCurves._tempColor.multiplyToRef(colorCurves._globalCurve, colorCurves._shadowsCurve);
  41875. // Compute deltas (neutral is midtones).
  41876. colorCurves._highlightsCurve.subtractToRef(colorCurves._midtonesCurve, colorCurves._positiveCurve);
  41877. colorCurves._midtonesCurve.subtractToRef(colorCurves._shadowsCurve, colorCurves._negativeCurve);
  41878. }
  41879. if (effect) {
  41880. effect.setFloat4(positiveUniform, colorCurves._positiveCurve.r, colorCurves._positiveCurve.g, colorCurves._positiveCurve.b, colorCurves._positiveCurve.a);
  41881. effect.setFloat4(neutralUniform, colorCurves._midtonesCurve.r, colorCurves._midtonesCurve.g, colorCurves._midtonesCurve.b, colorCurves._midtonesCurve.a);
  41882. effect.setFloat4(negativeUniform, colorCurves._negativeCurve.r, colorCurves._negativeCurve.g, colorCurves._negativeCurve.b, colorCurves._negativeCurve.a);
  41883. }
  41884. };
  41885. /**
  41886. * Prepare the list of uniforms associated with the ColorCurves effects.
  41887. * @param uniformsList The list of uniforms used in the effect
  41888. */
  41889. ColorCurves.PrepareUniforms = function (uniformsList) {
  41890. uniformsList.push("vCameraColorCurveNeutral", "vCameraColorCurvePositive", "vCameraColorCurveNegative");
  41891. };
  41892. /**
  41893. * Returns color grading data based on a hue, density, saturation and exposure value.
  41894. * @param filterHue The hue of the color filter.
  41895. * @param filterDensity The density of the color filter.
  41896. * @param saturation The saturation.
  41897. * @param exposure The exposure.
  41898. * @param result The result data container.
  41899. */
  41900. ColorCurves.prototype.getColorGradingDataToRef = function (hue, density, saturation, exposure, result) {
  41901. if (hue == null) {
  41902. return;
  41903. }
  41904. hue = ColorCurves.clamp(hue, 0, 360);
  41905. density = ColorCurves.clamp(density, -100, 100);
  41906. saturation = ColorCurves.clamp(saturation, -100, 100);
  41907. exposure = ColorCurves.clamp(exposure, -100, 100);
  41908. // Remap the slider/config filter density with non-linear mapping and also scale by half
  41909. // so that the maximum filter density is only 50% control. This provides fine control
  41910. // for small values and reasonable range.
  41911. density = ColorCurves.applyColorGradingSliderNonlinear(density);
  41912. density *= 0.5;
  41913. exposure = ColorCurves.applyColorGradingSliderNonlinear(exposure);
  41914. if (density < 0) {
  41915. density *= -1;
  41916. hue = (hue + 180) % 360;
  41917. }
  41918. ColorCurves.fromHSBToRef(hue, density, 50 + 0.25 * exposure, result);
  41919. result.scaleToRef(2, result);
  41920. result.a = 1 + 0.01 * saturation;
  41921. };
  41922. /**
  41923. * Takes an input slider value and returns an adjusted value that provides extra control near the centre.
  41924. * @param value The input slider value in range [-100,100].
  41925. * @returns Adjusted value.
  41926. */
  41927. ColorCurves.applyColorGradingSliderNonlinear = function (value) {
  41928. value /= 100;
  41929. var x = Math.abs(value);
  41930. x = Math.pow(x, 2);
  41931. if (value < 0) {
  41932. x *= -1;
  41933. }
  41934. x *= 100;
  41935. return x;
  41936. };
  41937. /**
  41938. * Returns an RGBA Color4 based on Hue, Saturation and Brightness (also referred to as value, HSV).
  41939. * @param hue The hue (H) input.
  41940. * @param saturation The saturation (S) input.
  41941. * @param brightness The brightness (B) input.
  41942. * @result An RGBA color represented as Vector4.
  41943. */
  41944. ColorCurves.fromHSBToRef = function (hue, saturation, brightness, result) {
  41945. var h = ColorCurves.clamp(hue, 0, 360);
  41946. var s = ColorCurves.clamp(saturation / 100, 0, 1);
  41947. var v = ColorCurves.clamp(brightness / 100, 0, 1);
  41948. if (s === 0) {
  41949. result.r = v;
  41950. result.g = v;
  41951. result.b = v;
  41952. }
  41953. else {
  41954. // sector 0 to 5
  41955. h /= 60;
  41956. var i = Math.floor(h);
  41957. // fractional part of h
  41958. var f = h - i;
  41959. var p = v * (1 - s);
  41960. var q = v * (1 - s * f);
  41961. var t = v * (1 - s * (1 - f));
  41962. switch (i) {
  41963. case 0:
  41964. result.r = v;
  41965. result.g = t;
  41966. result.b = p;
  41967. break;
  41968. case 1:
  41969. result.r = q;
  41970. result.g = v;
  41971. result.b = p;
  41972. break;
  41973. case 2:
  41974. result.r = p;
  41975. result.g = v;
  41976. result.b = t;
  41977. break;
  41978. case 3:
  41979. result.r = p;
  41980. result.g = q;
  41981. result.b = v;
  41982. break;
  41983. case 4:
  41984. result.r = t;
  41985. result.g = p;
  41986. result.b = v;
  41987. break;
  41988. default: // case 5:
  41989. result.r = v;
  41990. result.g = p;
  41991. result.b = q;
  41992. break;
  41993. }
  41994. }
  41995. result.a = 1;
  41996. };
  41997. /**
  41998. * Returns a value clamped between min and max
  41999. * @param value The value to clamp
  42000. * @param min The minimum of value
  42001. * @param max The maximum of value
  42002. * @returns The clamped value.
  42003. */
  42004. ColorCurves.clamp = function (value, min, max) {
  42005. return Math.min(Math.max(value, min), max);
  42006. };
  42007. /**
  42008. * Clones the current color curve instance.
  42009. * @return The cloned curves
  42010. */
  42011. ColorCurves.prototype.clone = function () {
  42012. return BABYLON.SerializationHelper.Clone(function () { return new ColorCurves(); }, this);
  42013. };
  42014. /**
  42015. * Serializes the current color curve instance to a json representation.
  42016. * @return a JSON representation
  42017. */
  42018. ColorCurves.prototype.serialize = function () {
  42019. return BABYLON.SerializationHelper.Serialize(this);
  42020. };
  42021. /**
  42022. * Parses the color curve from a json representation.
  42023. * @param source the JSON source to parse
  42024. * @return The parsed curves
  42025. */
  42026. ColorCurves.Parse = function (source) {
  42027. return BABYLON.SerializationHelper.Parse(function () { return new ColorCurves(); }, source, null, null);
  42028. };
  42029. __decorate([
  42030. BABYLON.serialize()
  42031. ], ColorCurves.prototype, "_globalHue", void 0);
  42032. __decorate([
  42033. BABYLON.serialize()
  42034. ], ColorCurves.prototype, "_globalDensity", void 0);
  42035. __decorate([
  42036. BABYLON.serialize()
  42037. ], ColorCurves.prototype, "_globalSaturation", void 0);
  42038. __decorate([
  42039. BABYLON.serialize()
  42040. ], ColorCurves.prototype, "_globalExposure", void 0);
  42041. __decorate([
  42042. BABYLON.serialize()
  42043. ], ColorCurves.prototype, "_highlightsHue", void 0);
  42044. __decorate([
  42045. BABYLON.serialize()
  42046. ], ColorCurves.prototype, "_highlightsDensity", void 0);
  42047. __decorate([
  42048. BABYLON.serialize()
  42049. ], ColorCurves.prototype, "_highlightsSaturation", void 0);
  42050. __decorate([
  42051. BABYLON.serialize()
  42052. ], ColorCurves.prototype, "_highlightsExposure", void 0);
  42053. __decorate([
  42054. BABYLON.serialize()
  42055. ], ColorCurves.prototype, "_midtonesHue", void 0);
  42056. __decorate([
  42057. BABYLON.serialize()
  42058. ], ColorCurves.prototype, "_midtonesDensity", void 0);
  42059. __decorate([
  42060. BABYLON.serialize()
  42061. ], ColorCurves.prototype, "_midtonesSaturation", void 0);
  42062. __decorate([
  42063. BABYLON.serialize()
  42064. ], ColorCurves.prototype, "_midtonesExposure", void 0);
  42065. return ColorCurves;
  42066. }());
  42067. BABYLON.ColorCurves = ColorCurves;
  42068. })(BABYLON || (BABYLON = {}));
  42069. //# sourceMappingURL=babylon.colorCurves.js.map
  42070. //# sourceMappingURL=babylon.behavior.js.map
  42071. var BABYLON;
  42072. (function (BABYLON) {
  42073. /**
  42074. * "Static Class" containing the most commonly used helper while dealing with material for
  42075. * rendering purpose.
  42076. *
  42077. * It contains the basic tools to help defining defines, binding uniform for the common part of the materials.
  42078. *
  42079. * This works by convention in BabylonJS but is meant to be use only with shader following the in place naming rules and conventions.
  42080. */
  42081. var MaterialHelper = /** @class */ (function () {
  42082. function MaterialHelper() {
  42083. }
  42084. /**
  42085. * Bind the current view position to an effect.
  42086. * @param effect The effect to be bound
  42087. * @param scene The scene the eyes position is used from
  42088. */
  42089. MaterialHelper.BindEyePosition = function (effect, scene) {
  42090. if (scene._forcedViewPosition) {
  42091. effect.setVector3("vEyePosition", scene._forcedViewPosition);
  42092. return;
  42093. }
  42094. effect.setVector3("vEyePosition", scene._mirroredCameraPosition ? scene._mirroredCameraPosition : scene.activeCamera.globalPosition);
  42095. };
  42096. /**
  42097. * Helps preparing the defines values about the UVs in used in the effect.
  42098. * UVs are shared as much as we can accross chanels in the shaders.
  42099. * @param texture The texture we are preparing the UVs for
  42100. * @param defines The defines to update
  42101. * @param key The chanel key "diffuse", "specular"... used in the shader
  42102. */
  42103. MaterialHelper.PrepareDefinesForMergedUV = function (texture, defines, key) {
  42104. defines._needUVs = true;
  42105. defines[key] = true;
  42106. if (texture.getTextureMatrix().isIdentity(true)) {
  42107. defines[key + "DIRECTUV"] = texture.coordinatesIndex + 1;
  42108. if (texture.coordinatesIndex === 0) {
  42109. defines["MAINUV1"] = true;
  42110. }
  42111. else {
  42112. defines["MAINUV2"] = true;
  42113. }
  42114. }
  42115. else {
  42116. defines[key + "DIRECTUV"] = 0;
  42117. }
  42118. };
  42119. /**
  42120. * Binds a texture matrix value to its corrsponding uniform
  42121. * @param texture The texture to bind the matrix for
  42122. * @param uniformBuffer The uniform buffer receivin the data
  42123. * @param key The chanel key "diffuse", "specular"... used in the shader
  42124. */
  42125. MaterialHelper.BindTextureMatrix = function (texture, uniformBuffer, key) {
  42126. var matrix = texture.getTextureMatrix();
  42127. if (!matrix.isIdentity(true)) {
  42128. uniformBuffer.updateMatrix(key + "Matrix", matrix);
  42129. }
  42130. };
  42131. /**
  42132. * Helper used to prepare the list of defines associated with misc. values for shader compilation
  42133. * @param mesh defines the current mesh
  42134. * @param scene defines the current scene
  42135. * @param useLogarithmicDepth defines if logarithmic depth has to be turned on
  42136. * @param pointsCloud defines if point cloud rendering has to be turned on
  42137. * @param fogEnabled defines if fog has to be turned on
  42138. * @param alphaTest defines if alpha testing has to be turned on
  42139. * @param defines defines the current list of defines
  42140. */
  42141. MaterialHelper.PrepareDefinesForMisc = function (mesh, scene, useLogarithmicDepth, pointsCloud, fogEnabled, alphaTest, defines) {
  42142. if (defines._areMiscDirty) {
  42143. defines["LOGARITHMICDEPTH"] = useLogarithmicDepth;
  42144. defines["POINTSIZE"] = pointsCloud;
  42145. defines["FOG"] = (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && fogEnabled);
  42146. defines["NONUNIFORMSCALING"] = mesh.nonUniformScaling;
  42147. defines["ALPHATEST"] = alphaTest;
  42148. }
  42149. };
  42150. /**
  42151. * Helper used to prepare the list of defines associated with frame values for shader compilation
  42152. * @param scene defines the current scene
  42153. * @param engine defines the current engine
  42154. * @param defines specifies the list of active defines
  42155. * @param useInstances defines if instances have to be turned on
  42156. * @param useClipPlane defines if clip plane have to be turned on
  42157. */
  42158. MaterialHelper.PrepareDefinesForFrameBoundValues = function (scene, engine, defines, useInstances, useClipPlane) {
  42159. if (useClipPlane === void 0) { useClipPlane = null; }
  42160. var changed = false;
  42161. if (useClipPlane == null) {
  42162. useClipPlane = (scene.clipPlane !== undefined && scene.clipPlane !== null);
  42163. }
  42164. if (defines["CLIPPLANE"] !== useClipPlane) {
  42165. defines["CLIPPLANE"] = useClipPlane;
  42166. changed = true;
  42167. }
  42168. if (defines["DEPTHPREPASS"] !== !engine.getColorWrite()) {
  42169. defines["DEPTHPREPASS"] = !defines["DEPTHPREPASS"];
  42170. changed = true;
  42171. }
  42172. if (defines["INSTANCES"] !== useInstances) {
  42173. defines["INSTANCES"] = useInstances;
  42174. changed = true;
  42175. }
  42176. if (changed) {
  42177. defines.markAsUnprocessed();
  42178. }
  42179. };
  42180. /**
  42181. * Prepares the defines used in the shader depending on the attributes data available in the mesh
  42182. * @param mesh The mesh containing the geometry data we will draw
  42183. * @param defines The defines to update
  42184. * @param useVertexColor Precise whether vertex colors should be used or not (override mesh info)
  42185. * @param useBones Precise whether bones should be used or not (override mesh info)
  42186. * @param useMorphTargets Precise whether morph targets should be used or not (override mesh info)
  42187. * @param useVertexAlpha Precise whether vertex alpha should be used or not (override mesh info)
  42188. * @returns false if defines are considered not dirty and have not been checked
  42189. */
  42190. MaterialHelper.PrepareDefinesForAttributes = function (mesh, defines, useVertexColor, useBones, useMorphTargets, useVertexAlpha) {
  42191. if (useMorphTargets === void 0) { useMorphTargets = false; }
  42192. if (useVertexAlpha === void 0) { useVertexAlpha = true; }
  42193. if (!defines._areAttributesDirty && defines._needNormals === defines._normals && defines._needUVs === defines._uvs) {
  42194. return false;
  42195. }
  42196. defines._normals = defines._needNormals;
  42197. defines._uvs = defines._needUVs;
  42198. defines["NORMAL"] = (defines._needNormals && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind));
  42199. if (defines._needNormals && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind)) {
  42200. defines["TANGENT"] = true;
  42201. }
  42202. if (defines._needUVs) {
  42203. defines["UV1"] = mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind);
  42204. defines["UV2"] = mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind);
  42205. }
  42206. else {
  42207. defines["UV1"] = false;
  42208. defines["UV2"] = false;
  42209. }
  42210. if (useVertexColor) {
  42211. var hasVertexColors = mesh.useVertexColors && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind);
  42212. defines["VERTEXCOLOR"] = hasVertexColors;
  42213. defines["VERTEXALPHA"] = mesh.hasVertexAlpha && hasVertexColors && useVertexAlpha;
  42214. }
  42215. if (useBones) {
  42216. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  42217. defines["NUM_BONE_INFLUENCERS"] = mesh.numBoneInfluencers;
  42218. defines["BonesPerMesh"] = (mesh.skeleton.bones.length + 1);
  42219. }
  42220. else {
  42221. defines["NUM_BONE_INFLUENCERS"] = 0;
  42222. defines["BonesPerMesh"] = 0;
  42223. }
  42224. }
  42225. if (useMorphTargets) {
  42226. var manager = mesh.morphTargetManager;
  42227. if (manager) {
  42228. defines["MORPHTARGETS_TANGENT"] = manager.supportsTangents && defines["TANGENT"];
  42229. defines["MORPHTARGETS_NORMAL"] = manager.supportsNormals && defines["NORMAL"];
  42230. defines["MORPHTARGETS"] = (manager.numInfluencers > 0);
  42231. defines["NUM_MORPH_INFLUENCERS"] = manager.numInfluencers;
  42232. }
  42233. else {
  42234. defines["MORPHTARGETS_TANGENT"] = false;
  42235. defines["MORPHTARGETS_NORMAL"] = false;
  42236. defines["MORPHTARGETS"] = false;
  42237. defines["NUM_MORPH_INFLUENCERS"] = 0;
  42238. }
  42239. }
  42240. return true;
  42241. };
  42242. /**
  42243. * Prepares the defines related to the light information passed in parameter
  42244. * @param scene The scene we are intending to draw
  42245. * @param mesh The mesh the effect is compiling for
  42246. * @param defines The defines to update
  42247. * @param specularSupported Specifies whether specular is supported or not (override lights data)
  42248. * @param maxSimultaneousLights Specfies how manuy lights can be added to the effect at max
  42249. * @param disableLighting Specifies whether the lighting is disabled (override scene and light)
  42250. * @returns true if normals will be required for the rest of the effect
  42251. */
  42252. MaterialHelper.PrepareDefinesForLights = function (scene, mesh, defines, specularSupported, maxSimultaneousLights, disableLighting) {
  42253. if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }
  42254. if (disableLighting === void 0) { disableLighting = false; }
  42255. if (!defines._areLightsDirty) {
  42256. return defines._needNormals;
  42257. }
  42258. var lightIndex = 0;
  42259. var needNormals = false;
  42260. var needRebuild = false;
  42261. var lightmapMode = false;
  42262. var shadowEnabled = false;
  42263. var specularEnabled = false;
  42264. if (scene.lightsEnabled && !disableLighting) {
  42265. for (var _i = 0, _a = mesh._lightSources; _i < _a.length; _i++) {
  42266. var light = _a[_i];
  42267. needNormals = true;
  42268. if (defines["LIGHT" + lightIndex] === undefined) {
  42269. needRebuild = true;
  42270. }
  42271. defines["LIGHT" + lightIndex] = true;
  42272. defines["SPOTLIGHT" + lightIndex] = false;
  42273. defines["HEMILIGHT" + lightIndex] = false;
  42274. defines["POINTLIGHT" + lightIndex] = false;
  42275. defines["DIRLIGHT" + lightIndex] = false;
  42276. var type;
  42277. if (light.getTypeID() === BABYLON.Light.LIGHTTYPEID_SPOTLIGHT) {
  42278. type = "SPOTLIGHT" + lightIndex;
  42279. var spotLight = light;
  42280. defines["PROJECTEDLIGHTTEXTURE" + lightIndex] = spotLight.projectionTexture ? true : false;
  42281. }
  42282. else if (light.getTypeID() === BABYLON.Light.LIGHTTYPEID_HEMISPHERICLIGHT) {
  42283. type = "HEMILIGHT" + lightIndex;
  42284. }
  42285. else if (light.getTypeID() === BABYLON.Light.LIGHTTYPEID_POINTLIGHT) {
  42286. type = "POINTLIGHT" + lightIndex;
  42287. }
  42288. else {
  42289. type = "DIRLIGHT" + lightIndex;
  42290. }
  42291. defines[type] = true;
  42292. // Specular
  42293. if (specularSupported && !light.specular.equalsFloats(0, 0, 0)) {
  42294. specularEnabled = true;
  42295. }
  42296. // Shadows
  42297. defines["SHADOW" + lightIndex] = false;
  42298. defines["SHADOWPCF" + lightIndex] = false;
  42299. defines["SHADOWPCSS" + lightIndex] = false;
  42300. defines["SHADOWPOISSON" + lightIndex] = false;
  42301. defines["SHADOWESM" + lightIndex] = false;
  42302. defines["SHADOWCUBE" + lightIndex] = false;
  42303. defines["SHADOWLOWQUALITY" + lightIndex] = false;
  42304. defines["SHADOWMEDIUMQUALITY" + lightIndex] = false;
  42305. if (mesh && mesh.receiveShadows && scene.shadowsEnabled && light.shadowEnabled) {
  42306. var shadowGenerator = light.getShadowGenerator();
  42307. if (shadowGenerator) {
  42308. shadowEnabled = true;
  42309. shadowGenerator.prepareDefines(defines, lightIndex);
  42310. }
  42311. }
  42312. if (light.lightmapMode != BABYLON.Light.LIGHTMAP_DEFAULT) {
  42313. lightmapMode = true;
  42314. defines["LIGHTMAPEXCLUDED" + lightIndex] = true;
  42315. defines["LIGHTMAPNOSPECULAR" + lightIndex] = (light.lightmapMode == BABYLON.Light.LIGHTMAP_SHADOWSONLY);
  42316. }
  42317. else {
  42318. defines["LIGHTMAPEXCLUDED" + lightIndex] = false;
  42319. defines["LIGHTMAPNOSPECULAR" + lightIndex] = false;
  42320. }
  42321. lightIndex++;
  42322. if (lightIndex === maxSimultaneousLights)
  42323. break;
  42324. }
  42325. }
  42326. defines["SPECULARTERM"] = specularEnabled;
  42327. defines["SHADOWS"] = shadowEnabled;
  42328. // Resetting all other lights if any
  42329. for (var index = lightIndex; index < maxSimultaneousLights; index++) {
  42330. if (defines["LIGHT" + index] !== undefined) {
  42331. defines["LIGHT" + index] = false;
  42332. defines["HEMILIGHT" + lightIndex] = false;
  42333. defines["POINTLIGHT" + lightIndex] = false;
  42334. defines["DIRLIGHT" + lightIndex] = false;
  42335. defines["SPOTLIGHT" + lightIndex] = false;
  42336. defines["SHADOW" + lightIndex] = false;
  42337. }
  42338. }
  42339. var caps = scene.getEngine().getCaps();
  42340. if (defines["SHADOWFLOAT"] === undefined) {
  42341. needRebuild = true;
  42342. }
  42343. defines["SHADOWFLOAT"] = shadowEnabled &&
  42344. ((caps.textureFloatRender && caps.textureFloatLinearFiltering) ||
  42345. (caps.textureHalfFloatRender && caps.textureHalfFloatLinearFiltering));
  42346. defines["LIGHTMAPEXCLUDED"] = lightmapMode;
  42347. if (needRebuild) {
  42348. defines.rebuild();
  42349. }
  42350. return needNormals;
  42351. };
  42352. /**
  42353. * Prepares the uniforms and samplers list to be used in the effect. This can automatically remove from the list uniforms
  42354. * that won t be acctive due to defines being turned off.
  42355. * @param uniformsListOrOptions The uniform names to prepare or an EffectCreationOptions containing the liist and extra information
  42356. * @param samplersList The samplers list
  42357. * @param defines The defines helping in the list generation
  42358. * @param maxSimultaneousLights The maximum number of simultanous light allowed in the effect
  42359. */
  42360. MaterialHelper.PrepareUniformsAndSamplersList = function (uniformsListOrOptions, samplersList, defines, maxSimultaneousLights) {
  42361. if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }
  42362. var uniformsList;
  42363. var uniformBuffersList = null;
  42364. if (uniformsListOrOptions.uniformsNames) {
  42365. var options = uniformsListOrOptions;
  42366. uniformsList = options.uniformsNames;
  42367. uniformBuffersList = options.uniformBuffersNames;
  42368. samplersList = options.samplers;
  42369. defines = options.defines;
  42370. maxSimultaneousLights = options.maxSimultaneousLights;
  42371. }
  42372. else {
  42373. uniformsList = uniformsListOrOptions;
  42374. if (!samplersList) {
  42375. samplersList = [];
  42376. }
  42377. }
  42378. for (var lightIndex = 0; lightIndex < maxSimultaneousLights; lightIndex++) {
  42379. if (!defines["LIGHT" + lightIndex]) {
  42380. break;
  42381. }
  42382. uniformsList.push("vLightData" + lightIndex, "vLightDiffuse" + lightIndex, "vLightSpecular" + lightIndex, "vLightDirection" + lightIndex, "vLightGround" + lightIndex, "lightMatrix" + lightIndex, "shadowsInfo" + lightIndex, "depthValues" + lightIndex);
  42383. if (uniformBuffersList) {
  42384. uniformBuffersList.push("Light" + lightIndex);
  42385. }
  42386. samplersList.push("shadowSampler" + lightIndex);
  42387. samplersList.push("depthSampler" + lightIndex);
  42388. if (defines["PROJECTEDLIGHTTEXTURE" + lightIndex]) {
  42389. samplersList.push("projectionLightSampler" + lightIndex);
  42390. uniformsList.push("textureProjectionMatrix" + lightIndex);
  42391. }
  42392. }
  42393. if (defines["NUM_MORPH_INFLUENCERS"]) {
  42394. uniformsList.push("morphTargetInfluences");
  42395. }
  42396. };
  42397. /**
  42398. * This helps decreasing rank by rank the shadow quality (0 being the highest rank and quality)
  42399. * @param defines The defines to update while falling back
  42400. * @param fallbacks The authorized effect fallbacks
  42401. * @param maxSimultaneousLights The maximum number of lights allowed
  42402. * @param rank the current rank of the Effect
  42403. * @returns The newly affected rank
  42404. */
  42405. MaterialHelper.HandleFallbacksForShadows = function (defines, fallbacks, maxSimultaneousLights, rank) {
  42406. if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }
  42407. if (rank === void 0) { rank = 0; }
  42408. var lightFallbackRank = 0;
  42409. for (var lightIndex = 0; lightIndex < maxSimultaneousLights; lightIndex++) {
  42410. if (!defines["LIGHT" + lightIndex]) {
  42411. break;
  42412. }
  42413. if (lightIndex > 0) {
  42414. lightFallbackRank = rank + lightIndex;
  42415. fallbacks.addFallback(lightFallbackRank, "LIGHT" + lightIndex);
  42416. }
  42417. if (!defines["SHADOWS"]) {
  42418. if (defines["SHADOW" + lightIndex]) {
  42419. fallbacks.addFallback(rank, "SHADOW" + lightIndex);
  42420. }
  42421. if (defines["SHADOWPCF" + lightIndex]) {
  42422. fallbacks.addFallback(rank, "SHADOWPCF" + lightIndex);
  42423. }
  42424. if (defines["SHADOWPCSS" + lightIndex]) {
  42425. fallbacks.addFallback(rank, "SHADOWPCSS" + lightIndex);
  42426. }
  42427. if (defines["SHADOWPOISSON" + lightIndex]) {
  42428. fallbacks.addFallback(rank, "SHADOWPOISSON" + lightIndex);
  42429. }
  42430. if (defines["SHADOWESM" + lightIndex]) {
  42431. fallbacks.addFallback(rank, "SHADOWESM" + lightIndex);
  42432. }
  42433. }
  42434. }
  42435. return lightFallbackRank++;
  42436. };
  42437. /**
  42438. * Prepares the list of attributes required for morph targets according to the effect defines.
  42439. * @param attribs The current list of supported attribs
  42440. * @param mesh The mesh to prepare the morph targets attributes for
  42441. * @param defines The current Defines of the effect
  42442. */
  42443. MaterialHelper.PrepareAttributesForMorphTargets = function (attribs, mesh, defines) {
  42444. var influencers = defines["NUM_MORPH_INFLUENCERS"];
  42445. if (influencers > 0 && BABYLON.Engine.LastCreatedEngine) {
  42446. var maxAttributesCount = BABYLON.Engine.LastCreatedEngine.getCaps().maxVertexAttribs;
  42447. var manager = mesh.morphTargetManager;
  42448. var normal = manager && manager.supportsNormals && defines["NORMAL"];
  42449. var tangent = manager && manager.supportsTangents && defines["TANGENT"];
  42450. for (var index = 0; index < influencers; index++) {
  42451. attribs.push(BABYLON.VertexBuffer.PositionKind + index);
  42452. if (normal) {
  42453. attribs.push(BABYLON.VertexBuffer.NormalKind + index);
  42454. }
  42455. if (tangent) {
  42456. attribs.push(BABYLON.VertexBuffer.TangentKind + index);
  42457. }
  42458. if (attribs.length > maxAttributesCount) {
  42459. BABYLON.Tools.Error("Cannot add more vertex attributes for mesh " + mesh.name);
  42460. }
  42461. }
  42462. }
  42463. };
  42464. /**
  42465. * Prepares the list of attributes required for bones according to the effect defines.
  42466. * @param attribs The current list of supported attribs
  42467. * @param mesh The mesh to prepare the bones attributes for
  42468. * @param defines The current Defines of the effect
  42469. * @param fallbacks The current efffect fallback strategy
  42470. */
  42471. MaterialHelper.PrepareAttributesForBones = function (attribs, mesh, defines, fallbacks) {
  42472. if (defines["NUM_BONE_INFLUENCERS"] > 0) {
  42473. fallbacks.addCPUSkinningFallback(0, mesh);
  42474. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  42475. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  42476. if (defines["NUM_BONE_INFLUENCERS"] > 4) {
  42477. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  42478. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  42479. }
  42480. }
  42481. };
  42482. /**
  42483. * Prepares the list of attributes required for instances according to the effect defines.
  42484. * @param attribs The current list of supported attribs
  42485. * @param defines The current Defines of the effect
  42486. */
  42487. MaterialHelper.PrepareAttributesForInstances = function (attribs, defines) {
  42488. if (defines["INSTANCES"]) {
  42489. attribs.push("world0");
  42490. attribs.push("world1");
  42491. attribs.push("world2");
  42492. attribs.push("world3");
  42493. }
  42494. };
  42495. /**
  42496. * Binds the light shadow information to the effect for the given mesh.
  42497. * @param light The light containing the generator
  42498. * @param scene The scene the lights belongs to
  42499. * @param mesh The mesh we are binding the information to render
  42500. * @param lightIndex The light index in the effect used to render the mesh
  42501. * @param effect The effect we are binding the data to
  42502. */
  42503. MaterialHelper.BindLightShadow = function (light, scene, mesh, lightIndex, effect) {
  42504. if (light.shadowEnabled && mesh.receiveShadows) {
  42505. var shadowGenerator = light.getShadowGenerator();
  42506. if (shadowGenerator) {
  42507. shadowGenerator.bindShadowLight(lightIndex, effect);
  42508. }
  42509. }
  42510. };
  42511. /**
  42512. * Binds the light information to the effect.
  42513. * @param light The light containing the generator
  42514. * @param effect The effect we are binding the data to
  42515. * @param lightIndex The light index in the effect used to render
  42516. */
  42517. MaterialHelper.BindLightProperties = function (light, effect, lightIndex) {
  42518. light.transferToEffect(effect, lightIndex + "");
  42519. };
  42520. /**
  42521. * Binds the lights information from the scene to the effect for the given mesh.
  42522. * @param scene The scene the lights belongs to
  42523. * @param mesh The mesh we are binding the information to render
  42524. * @param effect The effect we are binding the data to
  42525. * @param defines The generated defines for the effect
  42526. * @param maxSimultaneousLights The maximum number of light that can be bound to the effect
  42527. * @param usePhysicalLightFalloff Specifies whether the light falloff is defined physically or not
  42528. */
  42529. MaterialHelper.BindLights = function (scene, mesh, effect, defines, maxSimultaneousLights, usePhysicalLightFalloff) {
  42530. if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }
  42531. if (usePhysicalLightFalloff === void 0) { usePhysicalLightFalloff = false; }
  42532. var len = Math.min(mesh._lightSources.length, maxSimultaneousLights);
  42533. for (var i = 0; i < len; i++) {
  42534. var light = mesh._lightSources[i];
  42535. var iAsString = i.toString();
  42536. var scaledIntensity = light.getScaledIntensity();
  42537. light._uniformBuffer.bindToEffect(effect, "Light" + i);
  42538. MaterialHelper.BindLightProperties(light, effect, i);
  42539. light.diffuse.scaleToRef(scaledIntensity, BABYLON.Tmp.Color3[0]);
  42540. light._uniformBuffer.updateColor4("vLightDiffuse", BABYLON.Tmp.Color3[0], usePhysicalLightFalloff ? light.radius : light.range, iAsString);
  42541. if (defines["SPECULARTERM"]) {
  42542. light.specular.scaleToRef(scaledIntensity, BABYLON.Tmp.Color3[1]);
  42543. light._uniformBuffer.updateColor3("vLightSpecular", BABYLON.Tmp.Color3[1], iAsString);
  42544. }
  42545. // Shadows
  42546. if (scene.shadowsEnabled) {
  42547. this.BindLightShadow(light, scene, mesh, iAsString, effect);
  42548. }
  42549. light._uniformBuffer.update();
  42550. }
  42551. };
  42552. /**
  42553. * Binds the fog information from the scene to the effect for the given mesh.
  42554. * @param scene The scene the lights belongs to
  42555. * @param mesh The mesh we are binding the information to render
  42556. * @param effect The effect we are binding the data to
  42557. */
  42558. MaterialHelper.BindFogParameters = function (scene, mesh, effect) {
  42559. if (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE) {
  42560. effect.setFloat4("vFogInfos", scene.fogMode, scene.fogStart, scene.fogEnd, scene.fogDensity);
  42561. effect.setColor3("vFogColor", scene.fogColor);
  42562. }
  42563. };
  42564. /**
  42565. * Binds the bones information from the mesh to the effect.
  42566. * @param mesh The mesh we are binding the information to render
  42567. * @param effect The effect we are binding the data to
  42568. */
  42569. MaterialHelper.BindBonesParameters = function (mesh, effect) {
  42570. if (mesh && mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  42571. var matrices = mesh.skeleton.getTransformMatrices(mesh);
  42572. if (matrices && effect) {
  42573. effect.setMatrices("mBones", matrices);
  42574. }
  42575. }
  42576. };
  42577. /**
  42578. * Binds the morph targets information from the mesh to the effect.
  42579. * @param abstractMesh The mesh we are binding the information to render
  42580. * @param effect The effect we are binding the data to
  42581. */
  42582. MaterialHelper.BindMorphTargetParameters = function (abstractMesh, effect) {
  42583. var manager = abstractMesh.morphTargetManager;
  42584. if (!abstractMesh || !manager) {
  42585. return;
  42586. }
  42587. effect.setFloatArray("morphTargetInfluences", manager.influences);
  42588. };
  42589. /**
  42590. * Binds the logarithmic depth information from the scene to the effect for the given defines.
  42591. * @param defines The generated defines used in the effect
  42592. * @param effect The effect we are binding the data to
  42593. * @param scene The scene we are willing to render with logarithmic scale for
  42594. */
  42595. MaterialHelper.BindLogDepth = function (defines, effect, scene) {
  42596. if (defines["LOGARITHMICDEPTH"]) {
  42597. effect.setFloat("logarithmicDepthConstant", 2.0 / (Math.log(scene.activeCamera.maxZ + 1.0) / Math.LN2));
  42598. }
  42599. };
  42600. /**
  42601. * Binds the clip plane information from the scene to the effect.
  42602. * @param scene The scene the clip plane information are extracted from
  42603. * @param effect The effect we are binding the data to
  42604. */
  42605. MaterialHelper.BindClipPlane = function (effect, scene) {
  42606. if (scene.clipPlane) {
  42607. var clipPlane = scene.clipPlane;
  42608. effect.setFloat4("vClipPlane", clipPlane.normal.x, clipPlane.normal.y, clipPlane.normal.z, clipPlane.d);
  42609. }
  42610. };
  42611. return MaterialHelper;
  42612. }());
  42613. BABYLON.MaterialHelper = MaterialHelper;
  42614. })(BABYLON || (BABYLON = {}));
  42615. //# sourceMappingURL=babylon.materialHelper.js.map
  42616. var BABYLON;
  42617. (function (BABYLON) {
  42618. var PushMaterial = /** @class */ (function (_super) {
  42619. __extends(PushMaterial, _super);
  42620. function PushMaterial(name, scene) {
  42621. var _this = _super.call(this, name, scene) || this;
  42622. _this._normalMatrix = new BABYLON.Matrix();
  42623. _this.storeEffectOnSubMeshes = true;
  42624. return _this;
  42625. }
  42626. PushMaterial.prototype.getEffect = function () {
  42627. return this._activeEffect;
  42628. };
  42629. PushMaterial.prototype.isReady = function (mesh, useInstances) {
  42630. if (!mesh) {
  42631. return false;
  42632. }
  42633. if (!mesh.subMeshes || mesh.subMeshes.length === 0) {
  42634. return true;
  42635. }
  42636. return this.isReadyForSubMesh(mesh, mesh.subMeshes[0], useInstances);
  42637. };
  42638. /**
  42639. * Binds the given world matrix to the active effect
  42640. *
  42641. * @param world the matrix to bind
  42642. */
  42643. PushMaterial.prototype.bindOnlyWorldMatrix = function (world) {
  42644. this._activeEffect.setMatrix("world", world);
  42645. };
  42646. /**
  42647. * Binds the given normal matrix to the active effect
  42648. *
  42649. * @param normalMatrix the matrix to bind
  42650. */
  42651. PushMaterial.prototype.bindOnlyNormalMatrix = function (normalMatrix) {
  42652. this._activeEffect.setMatrix("normalMatrix", normalMatrix);
  42653. };
  42654. PushMaterial.prototype.bind = function (world, mesh) {
  42655. if (!mesh) {
  42656. return;
  42657. }
  42658. this.bindForSubMesh(world, mesh, mesh.subMeshes[0]);
  42659. };
  42660. PushMaterial.prototype._afterBind = function (mesh, effect) {
  42661. if (effect === void 0) { effect = null; }
  42662. _super.prototype._afterBind.call(this, mesh);
  42663. this.getScene()._cachedEffect = effect;
  42664. };
  42665. PushMaterial.prototype._mustRebind = function (scene, effect, visibility) {
  42666. if (visibility === void 0) { visibility = 1; }
  42667. return scene.isCachedMaterialInvalid(this, effect, visibility);
  42668. };
  42669. return PushMaterial;
  42670. }(BABYLON.Material));
  42671. BABYLON.PushMaterial = PushMaterial;
  42672. })(BABYLON || (BABYLON = {}));
  42673. //# sourceMappingURL=babylon.pushMaterial.js.map
  42674. var BABYLON;
  42675. (function (BABYLON) {
  42676. /** @hidden */
  42677. var StandardMaterialDefines = /** @class */ (function (_super) {
  42678. __extends(StandardMaterialDefines, _super);
  42679. function StandardMaterialDefines() {
  42680. var _this = _super.call(this) || this;
  42681. _this.MAINUV1 = false;
  42682. _this.MAINUV2 = false;
  42683. _this.DIFFUSE = false;
  42684. _this.DIFFUSEDIRECTUV = 0;
  42685. _this.AMBIENT = false;
  42686. _this.AMBIENTDIRECTUV = 0;
  42687. _this.OPACITY = false;
  42688. _this.OPACITYDIRECTUV = 0;
  42689. _this.OPACITYRGB = false;
  42690. _this.REFLECTION = false;
  42691. _this.EMISSIVE = false;
  42692. _this.EMISSIVEDIRECTUV = 0;
  42693. _this.SPECULAR = false;
  42694. _this.SPECULARDIRECTUV = 0;
  42695. _this.BUMP = false;
  42696. _this.BUMPDIRECTUV = 0;
  42697. _this.PARALLAX = false;
  42698. _this.PARALLAXOCCLUSION = false;
  42699. _this.SPECULAROVERALPHA = false;
  42700. _this.CLIPPLANE = false;
  42701. _this.ALPHATEST = false;
  42702. _this.DEPTHPREPASS = false;
  42703. _this.ALPHAFROMDIFFUSE = false;
  42704. _this.POINTSIZE = false;
  42705. _this.FOG = false;
  42706. _this.SPECULARTERM = false;
  42707. _this.DIFFUSEFRESNEL = false;
  42708. _this.OPACITYFRESNEL = false;
  42709. _this.REFLECTIONFRESNEL = false;
  42710. _this.REFRACTIONFRESNEL = false;
  42711. _this.EMISSIVEFRESNEL = false;
  42712. _this.FRESNEL = false;
  42713. _this.NORMAL = false;
  42714. _this.UV1 = false;
  42715. _this.UV2 = false;
  42716. _this.VERTEXCOLOR = false;
  42717. _this.VERTEXALPHA = false;
  42718. _this.NUM_BONE_INFLUENCERS = 0;
  42719. _this.BonesPerMesh = 0;
  42720. _this.INSTANCES = false;
  42721. _this.GLOSSINESS = false;
  42722. _this.ROUGHNESS = false;
  42723. _this.EMISSIVEASILLUMINATION = false;
  42724. _this.LINKEMISSIVEWITHDIFFUSE = false;
  42725. _this.REFLECTIONFRESNELFROMSPECULAR = false;
  42726. _this.LIGHTMAP = false;
  42727. _this.LIGHTMAPDIRECTUV = 0;
  42728. _this.OBJECTSPACE_NORMALMAP = false;
  42729. _this.USELIGHTMAPASSHADOWMAP = false;
  42730. _this.REFLECTIONMAP_3D = false;
  42731. _this.REFLECTIONMAP_SPHERICAL = false;
  42732. _this.REFLECTIONMAP_PLANAR = false;
  42733. _this.REFLECTIONMAP_CUBIC = false;
  42734. _this.USE_LOCAL_REFLECTIONMAP_CUBIC = false;
  42735. _this.REFLECTIONMAP_PROJECTION = false;
  42736. _this.REFLECTIONMAP_SKYBOX = false;
  42737. _this.REFLECTIONMAP_EXPLICIT = false;
  42738. _this.REFLECTIONMAP_EQUIRECTANGULAR = false;
  42739. _this.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  42740. _this.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false;
  42741. _this.INVERTCUBICMAP = false;
  42742. _this.LOGARITHMICDEPTH = false;
  42743. _this.REFRACTION = false;
  42744. _this.REFRACTIONMAP_3D = false;
  42745. _this.REFLECTIONOVERALPHA = false;
  42746. _this.TWOSIDEDLIGHTING = false;
  42747. _this.SHADOWFLOAT = false;
  42748. _this.MORPHTARGETS = false;
  42749. _this.MORPHTARGETS_NORMAL = false;
  42750. _this.MORPHTARGETS_TANGENT = false;
  42751. _this.NUM_MORPH_INFLUENCERS = 0;
  42752. _this.NONUNIFORMSCALING = false; // https://playground.babylonjs.com#V6DWIH
  42753. _this.PREMULTIPLYALPHA = false; // https://playground.babylonjs.com#LNVJJ7
  42754. _this.IMAGEPROCESSING = false;
  42755. _this.VIGNETTE = false;
  42756. _this.VIGNETTEBLENDMODEMULTIPLY = false;
  42757. _this.VIGNETTEBLENDMODEOPAQUE = false;
  42758. _this.TONEMAPPING = false;
  42759. _this.CONTRAST = false;
  42760. _this.COLORCURVES = false;
  42761. _this.COLORGRADING = false;
  42762. _this.COLORGRADING3D = false;
  42763. _this.SAMPLER3DGREENDEPTH = false;
  42764. _this.SAMPLER3DBGRMAP = false;
  42765. _this.IMAGEPROCESSINGPOSTPROCESS = false;
  42766. /**
  42767. * If the reflection texture on this material is in linear color space
  42768. * @hidden
  42769. */
  42770. _this.IS_REFLECTION_LINEAR = false;
  42771. /**
  42772. * If the refraction texture on this material is in linear color space
  42773. * @hidden
  42774. */
  42775. _this.IS_REFRACTION_LINEAR = false;
  42776. _this.EXPOSURE = false;
  42777. _this.rebuild();
  42778. return _this;
  42779. }
  42780. StandardMaterialDefines.prototype.setReflectionMode = function (modeToEnable) {
  42781. var modes = [
  42782. "REFLECTIONMAP_CUBIC", "REFLECTIONMAP_EXPLICIT", "REFLECTIONMAP_PLANAR",
  42783. "REFLECTIONMAP_PROJECTION", "REFLECTIONMAP_PROJECTION", "REFLECTIONMAP_SKYBOX",
  42784. "REFLECTIONMAP_SPHERICAL", "REFLECTIONMAP_EQUIRECTANGULAR", "REFLECTIONMAP_EQUIRECTANGULAR_FIXED",
  42785. "REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED"
  42786. ];
  42787. for (var _i = 0, modes_1 = modes; _i < modes_1.length; _i++) {
  42788. var mode = modes_1[_i];
  42789. this[mode] = (mode === modeToEnable);
  42790. }
  42791. };
  42792. return StandardMaterialDefines;
  42793. }(BABYLON.MaterialDefines));
  42794. BABYLON.StandardMaterialDefines = StandardMaterialDefines;
  42795. var StandardMaterial = /** @class */ (function (_super) {
  42796. __extends(StandardMaterial, _super);
  42797. function StandardMaterial(name, scene) {
  42798. var _this = _super.call(this, name, scene) || this;
  42799. _this.ambientColor = new BABYLON.Color3(0, 0, 0);
  42800. _this.diffuseColor = new BABYLON.Color3(1, 1, 1);
  42801. _this.specularColor = new BABYLON.Color3(1, 1, 1);
  42802. _this.emissiveColor = new BABYLON.Color3(0, 0, 0);
  42803. _this.specularPower = 64;
  42804. _this._useAlphaFromDiffuseTexture = false;
  42805. _this._useEmissiveAsIllumination = false;
  42806. _this._linkEmissiveWithDiffuse = false;
  42807. _this._useSpecularOverAlpha = false;
  42808. _this._useReflectionOverAlpha = false;
  42809. _this._disableLighting = false;
  42810. _this._useObjectSpaceNormalMap = false;
  42811. _this._useParallax = false;
  42812. _this._useParallaxOcclusion = false;
  42813. _this.parallaxScaleBias = 0.05;
  42814. _this._roughness = 0;
  42815. _this.indexOfRefraction = 0.98;
  42816. _this.invertRefractionY = true;
  42817. /**
  42818. * Defines the alpha limits in alpha test mode
  42819. */
  42820. _this.alphaCutOff = 0.4;
  42821. _this._useLightmapAsShadowmap = false;
  42822. _this._useReflectionFresnelFromSpecular = false;
  42823. _this._useGlossinessFromSpecularMapAlpha = false;
  42824. _this._maxSimultaneousLights = 4;
  42825. /**
  42826. * If sets to true, x component of normal map value will invert (x = 1.0 - x).
  42827. */
  42828. _this._invertNormalMapX = false;
  42829. /**
  42830. * If sets to true, y component of normal map value will invert (y = 1.0 - y).
  42831. */
  42832. _this._invertNormalMapY = false;
  42833. /**
  42834. * If sets to true and backfaceCulling is false, normals will be flipped on the backside.
  42835. */
  42836. _this._twoSidedLighting = false;
  42837. _this._renderTargets = new BABYLON.SmartArray(16);
  42838. _this._worldViewProjectionMatrix = BABYLON.Matrix.Zero();
  42839. _this._globalAmbientColor = new BABYLON.Color3(0, 0, 0);
  42840. // Setup the default processing configuration to the scene.
  42841. _this._attachImageProcessingConfiguration(null);
  42842. _this.getRenderTargetTextures = function () {
  42843. _this._renderTargets.reset();
  42844. if (StandardMaterial.ReflectionTextureEnabled && _this._reflectionTexture && _this._reflectionTexture.isRenderTarget) {
  42845. _this._renderTargets.push(_this._reflectionTexture);
  42846. }
  42847. if (StandardMaterial.RefractionTextureEnabled && _this._refractionTexture && _this._refractionTexture.isRenderTarget) {
  42848. _this._renderTargets.push(_this._refractionTexture);
  42849. }
  42850. return _this._renderTargets;
  42851. };
  42852. return _this;
  42853. }
  42854. ;
  42855. ;
  42856. ;
  42857. ;
  42858. ;
  42859. ;
  42860. ;
  42861. ;
  42862. ;
  42863. ;
  42864. ;
  42865. ;
  42866. ;
  42867. ;
  42868. ;
  42869. ;
  42870. ;
  42871. Object.defineProperty(StandardMaterial.prototype, "imageProcessingConfiguration", {
  42872. /**
  42873. * Gets the image processing configuration used either in this material.
  42874. */
  42875. get: function () {
  42876. return this._imageProcessingConfiguration;
  42877. },
  42878. /**
  42879. * Sets the Default image processing configuration used either in the this material.
  42880. *
  42881. * If sets to null, the scene one is in use.
  42882. */
  42883. set: function (value) {
  42884. this._attachImageProcessingConfiguration(value);
  42885. // Ensure the effect will be rebuilt.
  42886. this._markAllSubMeshesAsTexturesDirty();
  42887. },
  42888. enumerable: true,
  42889. configurable: true
  42890. });
  42891. /**
  42892. * Attaches a new image processing configuration to the Standard Material.
  42893. * @param configuration
  42894. */
  42895. StandardMaterial.prototype._attachImageProcessingConfiguration = function (configuration) {
  42896. var _this = this;
  42897. if (configuration === this._imageProcessingConfiguration) {
  42898. return;
  42899. }
  42900. // Detaches observer.
  42901. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  42902. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  42903. }
  42904. // Pick the scene configuration if needed.
  42905. if (!configuration) {
  42906. this._imageProcessingConfiguration = this.getScene().imageProcessingConfiguration;
  42907. }
  42908. else {
  42909. this._imageProcessingConfiguration = configuration;
  42910. }
  42911. // Attaches observer.
  42912. this._imageProcessingObserver = this._imageProcessingConfiguration.onUpdateParameters.add(function (conf) {
  42913. _this._markAllSubMeshesAsImageProcessingDirty();
  42914. });
  42915. };
  42916. Object.defineProperty(StandardMaterial.prototype, "cameraColorCurvesEnabled", {
  42917. /**
  42918. * Gets wether the color curves effect is enabled.
  42919. */
  42920. get: function () {
  42921. return this.imageProcessingConfiguration.colorCurvesEnabled;
  42922. },
  42923. /**
  42924. * Sets wether the color curves effect is enabled.
  42925. */
  42926. set: function (value) {
  42927. this.imageProcessingConfiguration.colorCurvesEnabled = value;
  42928. },
  42929. enumerable: true,
  42930. configurable: true
  42931. });
  42932. Object.defineProperty(StandardMaterial.prototype, "cameraColorGradingEnabled", {
  42933. /**
  42934. * Gets wether the color grading effect is enabled.
  42935. */
  42936. get: function () {
  42937. return this.imageProcessingConfiguration.colorGradingEnabled;
  42938. },
  42939. /**
  42940. * Gets wether the color grading effect is enabled.
  42941. */
  42942. set: function (value) {
  42943. this.imageProcessingConfiguration.colorGradingEnabled = value;
  42944. },
  42945. enumerable: true,
  42946. configurable: true
  42947. });
  42948. Object.defineProperty(StandardMaterial.prototype, "cameraToneMappingEnabled", {
  42949. /**
  42950. * Gets wether tonemapping is enabled or not.
  42951. */
  42952. get: function () {
  42953. return this._imageProcessingConfiguration.toneMappingEnabled;
  42954. },
  42955. /**
  42956. * Sets wether tonemapping is enabled or not
  42957. */
  42958. set: function (value) {
  42959. this._imageProcessingConfiguration.toneMappingEnabled = value;
  42960. },
  42961. enumerable: true,
  42962. configurable: true
  42963. });
  42964. ;
  42965. ;
  42966. Object.defineProperty(StandardMaterial.prototype, "cameraExposure", {
  42967. /**
  42968. * The camera exposure used on this material.
  42969. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  42970. * This corresponds to a photographic exposure.
  42971. */
  42972. get: function () {
  42973. return this._imageProcessingConfiguration.exposure;
  42974. },
  42975. /**
  42976. * The camera exposure used on this material.
  42977. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  42978. * This corresponds to a photographic exposure.
  42979. */
  42980. set: function (value) {
  42981. this._imageProcessingConfiguration.exposure = value;
  42982. },
  42983. enumerable: true,
  42984. configurable: true
  42985. });
  42986. ;
  42987. ;
  42988. Object.defineProperty(StandardMaterial.prototype, "cameraContrast", {
  42989. /**
  42990. * Gets The camera contrast used on this material.
  42991. */
  42992. get: function () {
  42993. return this._imageProcessingConfiguration.contrast;
  42994. },
  42995. /**
  42996. * Sets The camera contrast used on this material.
  42997. */
  42998. set: function (value) {
  42999. this._imageProcessingConfiguration.contrast = value;
  43000. },
  43001. enumerable: true,
  43002. configurable: true
  43003. });
  43004. Object.defineProperty(StandardMaterial.prototype, "cameraColorGradingTexture", {
  43005. /**
  43006. * Gets the Color Grading 2D Lookup Texture.
  43007. */
  43008. get: function () {
  43009. return this._imageProcessingConfiguration.colorGradingTexture;
  43010. },
  43011. /**
  43012. * Sets the Color Grading 2D Lookup Texture.
  43013. */
  43014. set: function (value) {
  43015. this._imageProcessingConfiguration.colorGradingTexture = value;
  43016. },
  43017. enumerable: true,
  43018. configurable: true
  43019. });
  43020. Object.defineProperty(StandardMaterial.prototype, "cameraColorCurves", {
  43021. /**
  43022. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  43023. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  43024. * 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;
  43025. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  43026. */
  43027. get: function () {
  43028. return this._imageProcessingConfiguration.colorCurves;
  43029. },
  43030. /**
  43031. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  43032. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  43033. * 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;
  43034. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  43035. */
  43036. set: function (value) {
  43037. this._imageProcessingConfiguration.colorCurves = value;
  43038. },
  43039. enumerable: true,
  43040. configurable: true
  43041. });
  43042. StandardMaterial.prototype.getClassName = function () {
  43043. return "StandardMaterial";
  43044. };
  43045. Object.defineProperty(StandardMaterial.prototype, "useLogarithmicDepth", {
  43046. get: function () {
  43047. return this._useLogarithmicDepth;
  43048. },
  43049. set: function (value) {
  43050. this._useLogarithmicDepth = value && this.getScene().getEngine().getCaps().fragmentDepthSupported;
  43051. this._markAllSubMeshesAsMiscDirty();
  43052. },
  43053. enumerable: true,
  43054. configurable: true
  43055. });
  43056. StandardMaterial.prototype.needAlphaBlending = function () {
  43057. return (this.alpha < 1.0) || (this._opacityTexture != null) || this._shouldUseAlphaFromDiffuseTexture() || this._opacityFresnelParameters && this._opacityFresnelParameters.isEnabled;
  43058. };
  43059. StandardMaterial.prototype.needAlphaTesting = function () {
  43060. return this._diffuseTexture != null && this._diffuseTexture.hasAlpha;
  43061. };
  43062. StandardMaterial.prototype._shouldUseAlphaFromDiffuseTexture = function () {
  43063. return this._diffuseTexture != null && this._diffuseTexture.hasAlpha && this._useAlphaFromDiffuseTexture;
  43064. };
  43065. StandardMaterial.prototype.getAlphaTestTexture = function () {
  43066. return this._diffuseTexture;
  43067. };
  43068. /**
  43069. * Child classes can use it to update shaders
  43070. */
  43071. StandardMaterial.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  43072. if (useInstances === void 0) { useInstances = false; }
  43073. if (subMesh.effect && this.isFrozen) {
  43074. if (this._wasPreviouslyReady && subMesh.effect) {
  43075. return true;
  43076. }
  43077. }
  43078. if (!subMesh._materialDefines) {
  43079. subMesh._materialDefines = new StandardMaterialDefines();
  43080. }
  43081. var scene = this.getScene();
  43082. var defines = subMesh._materialDefines;
  43083. if (!this.checkReadyOnEveryCall && subMesh.effect) {
  43084. if (defines._renderId === scene.getRenderId()) {
  43085. return true;
  43086. }
  43087. }
  43088. var engine = scene.getEngine();
  43089. // Lights
  43090. defines._needNormals = BABYLON.MaterialHelper.PrepareDefinesForLights(scene, mesh, defines, true, this._maxSimultaneousLights, this._disableLighting);
  43091. // Textures
  43092. if (defines._areTexturesDirty) {
  43093. defines._needUVs = false;
  43094. defines.MAINUV1 = false;
  43095. defines.MAINUV2 = false;
  43096. if (scene.texturesEnabled) {
  43097. if (this._diffuseTexture && StandardMaterial.DiffuseTextureEnabled) {
  43098. if (!this._diffuseTexture.isReadyOrNotBlocking()) {
  43099. return false;
  43100. }
  43101. else {
  43102. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._diffuseTexture, defines, "DIFFUSE");
  43103. }
  43104. }
  43105. else {
  43106. defines.DIFFUSE = false;
  43107. }
  43108. if (this._ambientTexture && StandardMaterial.AmbientTextureEnabled) {
  43109. if (!this._ambientTexture.isReadyOrNotBlocking()) {
  43110. return false;
  43111. }
  43112. else {
  43113. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._ambientTexture, defines, "AMBIENT");
  43114. }
  43115. }
  43116. else {
  43117. defines.AMBIENT = false;
  43118. }
  43119. if (this._opacityTexture && StandardMaterial.OpacityTextureEnabled) {
  43120. if (!this._opacityTexture.isReadyOrNotBlocking()) {
  43121. return false;
  43122. }
  43123. else {
  43124. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._opacityTexture, defines, "OPACITY");
  43125. defines.OPACITYRGB = this._opacityTexture.getAlphaFromRGB;
  43126. }
  43127. }
  43128. else {
  43129. defines.OPACITY = false;
  43130. }
  43131. if (this._reflectionTexture && StandardMaterial.ReflectionTextureEnabled) {
  43132. if (!this._reflectionTexture.isReadyOrNotBlocking()) {
  43133. return false;
  43134. }
  43135. else {
  43136. defines._needNormals = true;
  43137. defines.REFLECTION = true;
  43138. defines.ROUGHNESS = (this._roughness > 0);
  43139. defines.REFLECTIONOVERALPHA = this._useReflectionOverAlpha;
  43140. defines.INVERTCUBICMAP = (this._reflectionTexture.coordinatesMode === BABYLON.Texture.INVCUBIC_MODE);
  43141. defines.REFLECTIONMAP_3D = this._reflectionTexture.isCube;
  43142. switch (this._reflectionTexture.coordinatesMode) {
  43143. case BABYLON.Texture.CUBIC_MODE:
  43144. case BABYLON.Texture.INVCUBIC_MODE:
  43145. defines.setReflectionMode("REFLECTIONMAP_CUBIC");
  43146. break;
  43147. case BABYLON.Texture.EXPLICIT_MODE:
  43148. defines.setReflectionMode("REFLECTIONMAP_EXPLICIT");
  43149. break;
  43150. case BABYLON.Texture.PLANAR_MODE:
  43151. defines.setReflectionMode("REFLECTIONMAP_PLANAR");
  43152. break;
  43153. case BABYLON.Texture.PROJECTION_MODE:
  43154. defines.setReflectionMode("REFLECTIONMAP_PROJECTION");
  43155. break;
  43156. case BABYLON.Texture.SKYBOX_MODE:
  43157. defines.setReflectionMode("REFLECTIONMAP_SKYBOX");
  43158. break;
  43159. case BABYLON.Texture.SPHERICAL_MODE:
  43160. defines.setReflectionMode("REFLECTIONMAP_SPHERICAL");
  43161. break;
  43162. case BABYLON.Texture.EQUIRECTANGULAR_MODE:
  43163. defines.setReflectionMode("REFLECTIONMAP_EQUIRECTANGULAR");
  43164. break;
  43165. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MODE:
  43166. defines.setReflectionMode("REFLECTIONMAP_EQUIRECTANGULAR_FIXED");
  43167. break;
  43168. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE:
  43169. defines.setReflectionMode("REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED");
  43170. break;
  43171. }
  43172. defines.USE_LOCAL_REFLECTIONMAP_CUBIC = this._reflectionTexture.boundingBoxSize ? true : false;
  43173. }
  43174. }
  43175. else {
  43176. defines.REFLECTION = false;
  43177. }
  43178. if (this._emissiveTexture && StandardMaterial.EmissiveTextureEnabled) {
  43179. if (!this._emissiveTexture.isReadyOrNotBlocking()) {
  43180. return false;
  43181. }
  43182. else {
  43183. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._emissiveTexture, defines, "EMISSIVE");
  43184. }
  43185. }
  43186. else {
  43187. defines.EMISSIVE = false;
  43188. }
  43189. if (this._lightmapTexture && StandardMaterial.LightmapTextureEnabled) {
  43190. if (!this._lightmapTexture.isReadyOrNotBlocking()) {
  43191. return false;
  43192. }
  43193. else {
  43194. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._lightmapTexture, defines, "LIGHTMAP");
  43195. defines.USELIGHTMAPASSHADOWMAP = this._useLightmapAsShadowmap;
  43196. }
  43197. }
  43198. else {
  43199. defines.LIGHTMAP = false;
  43200. }
  43201. if (this._specularTexture && StandardMaterial.SpecularTextureEnabled) {
  43202. if (!this._specularTexture.isReadyOrNotBlocking()) {
  43203. return false;
  43204. }
  43205. else {
  43206. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._specularTexture, defines, "SPECULAR");
  43207. defines.GLOSSINESS = this._useGlossinessFromSpecularMapAlpha;
  43208. }
  43209. }
  43210. else {
  43211. defines.SPECULAR = false;
  43212. }
  43213. if (scene.getEngine().getCaps().standardDerivatives && this._bumpTexture && StandardMaterial.BumpTextureEnabled) {
  43214. // Bump texure can not be not blocking.
  43215. if (!this._bumpTexture.isReady()) {
  43216. return false;
  43217. }
  43218. else {
  43219. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._bumpTexture, defines, "BUMP");
  43220. defines.PARALLAX = this._useParallax;
  43221. defines.PARALLAXOCCLUSION = this._useParallaxOcclusion;
  43222. }
  43223. defines.OBJECTSPACE_NORMALMAP = this._useObjectSpaceNormalMap;
  43224. }
  43225. else {
  43226. defines.BUMP = false;
  43227. }
  43228. if (this._refractionTexture && StandardMaterial.RefractionTextureEnabled) {
  43229. if (!this._refractionTexture.isReadyOrNotBlocking()) {
  43230. return false;
  43231. }
  43232. else {
  43233. defines._needUVs = true;
  43234. defines.REFRACTION = true;
  43235. defines.REFRACTIONMAP_3D = this._refractionTexture.isCube;
  43236. }
  43237. }
  43238. else {
  43239. defines.REFRACTION = false;
  43240. }
  43241. defines.TWOSIDEDLIGHTING = !this._backFaceCulling && this._twoSidedLighting;
  43242. }
  43243. else {
  43244. defines.DIFFUSE = false;
  43245. defines.AMBIENT = false;
  43246. defines.OPACITY = false;
  43247. defines.REFLECTION = false;
  43248. defines.EMISSIVE = false;
  43249. defines.LIGHTMAP = false;
  43250. defines.BUMP = false;
  43251. defines.REFRACTION = false;
  43252. }
  43253. defines.ALPHAFROMDIFFUSE = this._shouldUseAlphaFromDiffuseTexture();
  43254. defines.EMISSIVEASILLUMINATION = this._useEmissiveAsIllumination;
  43255. defines.LINKEMISSIVEWITHDIFFUSE = this._linkEmissiveWithDiffuse;
  43256. defines.SPECULAROVERALPHA = this._useSpecularOverAlpha;
  43257. defines.PREMULTIPLYALPHA = (this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED || this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED_PORTERDUFF);
  43258. }
  43259. if (defines._areImageProcessingDirty) {
  43260. if (!this._imageProcessingConfiguration.isReady()) {
  43261. return false;
  43262. }
  43263. this._imageProcessingConfiguration.prepareDefines(defines);
  43264. defines.IS_REFLECTION_LINEAR = (this.reflectionTexture != null && !this.reflectionTexture.gammaSpace);
  43265. defines.IS_REFRACTION_LINEAR = (this.refractionTexture != null && !this.refractionTexture.gammaSpace);
  43266. }
  43267. if (defines._areFresnelDirty) {
  43268. if (StandardMaterial.FresnelEnabled) {
  43269. // Fresnel
  43270. if (this._diffuseFresnelParameters || this._opacityFresnelParameters ||
  43271. this._emissiveFresnelParameters || this._refractionFresnelParameters ||
  43272. this._reflectionFresnelParameters) {
  43273. defines.DIFFUSEFRESNEL = (this._diffuseFresnelParameters && this._diffuseFresnelParameters.isEnabled);
  43274. defines.OPACITYFRESNEL = (this._opacityFresnelParameters && this._opacityFresnelParameters.isEnabled);
  43275. defines.REFLECTIONFRESNEL = (this._reflectionFresnelParameters && this._reflectionFresnelParameters.isEnabled);
  43276. defines.REFLECTIONFRESNELFROMSPECULAR = this._useReflectionFresnelFromSpecular;
  43277. defines.REFRACTIONFRESNEL = (this._refractionFresnelParameters && this._refractionFresnelParameters.isEnabled);
  43278. defines.EMISSIVEFRESNEL = (this._emissiveFresnelParameters && this._emissiveFresnelParameters.isEnabled);
  43279. defines._needNormals = true;
  43280. defines.FRESNEL = true;
  43281. }
  43282. }
  43283. else {
  43284. defines.FRESNEL = false;
  43285. }
  43286. }
  43287. // Misc.
  43288. BABYLON.MaterialHelper.PrepareDefinesForMisc(mesh, scene, this._useLogarithmicDepth, this.pointsCloud, this.fogEnabled, this._shouldTurnAlphaTestOn(mesh), defines);
  43289. // Attribs
  43290. BABYLON.MaterialHelper.PrepareDefinesForAttributes(mesh, defines, true, true, true);
  43291. // Values that need to be evaluated on every frame
  43292. BABYLON.MaterialHelper.PrepareDefinesForFrameBoundValues(scene, engine, defines, useInstances);
  43293. // Get correct effect
  43294. if (defines.isDirty) {
  43295. defines.markAsProcessed();
  43296. scene.resetCachedMaterial();
  43297. // Fallbacks
  43298. var fallbacks = new BABYLON.EffectFallbacks();
  43299. if (defines.REFLECTION) {
  43300. fallbacks.addFallback(0, "REFLECTION");
  43301. }
  43302. if (defines.SPECULAR) {
  43303. fallbacks.addFallback(0, "SPECULAR");
  43304. }
  43305. if (defines.BUMP) {
  43306. fallbacks.addFallback(0, "BUMP");
  43307. }
  43308. if (defines.PARALLAX) {
  43309. fallbacks.addFallback(1, "PARALLAX");
  43310. }
  43311. if (defines.PARALLAXOCCLUSION) {
  43312. fallbacks.addFallback(0, "PARALLAXOCCLUSION");
  43313. }
  43314. if (defines.SPECULAROVERALPHA) {
  43315. fallbacks.addFallback(0, "SPECULAROVERALPHA");
  43316. }
  43317. if (defines.FOG) {
  43318. fallbacks.addFallback(1, "FOG");
  43319. }
  43320. if (defines.POINTSIZE) {
  43321. fallbacks.addFallback(0, "POINTSIZE");
  43322. }
  43323. if (defines.LOGARITHMICDEPTH) {
  43324. fallbacks.addFallback(0, "LOGARITHMICDEPTH");
  43325. }
  43326. BABYLON.MaterialHelper.HandleFallbacksForShadows(defines, fallbacks, this._maxSimultaneousLights);
  43327. if (defines.SPECULARTERM) {
  43328. fallbacks.addFallback(0, "SPECULARTERM");
  43329. }
  43330. if (defines.DIFFUSEFRESNEL) {
  43331. fallbacks.addFallback(1, "DIFFUSEFRESNEL");
  43332. }
  43333. if (defines.OPACITYFRESNEL) {
  43334. fallbacks.addFallback(2, "OPACITYFRESNEL");
  43335. }
  43336. if (defines.REFLECTIONFRESNEL) {
  43337. fallbacks.addFallback(3, "REFLECTIONFRESNEL");
  43338. }
  43339. if (defines.EMISSIVEFRESNEL) {
  43340. fallbacks.addFallback(4, "EMISSIVEFRESNEL");
  43341. }
  43342. if (defines.FRESNEL) {
  43343. fallbacks.addFallback(4, "FRESNEL");
  43344. }
  43345. //Attributes
  43346. var attribs = [BABYLON.VertexBuffer.PositionKind];
  43347. if (defines.NORMAL) {
  43348. attribs.push(BABYLON.VertexBuffer.NormalKind);
  43349. }
  43350. if (defines.UV1) {
  43351. attribs.push(BABYLON.VertexBuffer.UVKind);
  43352. }
  43353. if (defines.UV2) {
  43354. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  43355. }
  43356. if (defines.VERTEXCOLOR) {
  43357. attribs.push(BABYLON.VertexBuffer.ColorKind);
  43358. }
  43359. BABYLON.MaterialHelper.PrepareAttributesForBones(attribs, mesh, defines, fallbacks);
  43360. BABYLON.MaterialHelper.PrepareAttributesForInstances(attribs, defines);
  43361. BABYLON.MaterialHelper.PrepareAttributesForMorphTargets(attribs, mesh, defines);
  43362. var shaderName = "default";
  43363. var uniforms = ["world", "view", "viewProjection", "vEyePosition", "vLightsType", "vAmbientColor", "vDiffuseColor", "vSpecularColor", "vEmissiveColor",
  43364. "vFogInfos", "vFogColor", "pointSize",
  43365. "vDiffuseInfos", "vAmbientInfos", "vOpacityInfos", "vReflectionInfos", "vEmissiveInfos", "vSpecularInfos", "vBumpInfos", "vLightmapInfos", "vRefractionInfos",
  43366. "mBones",
  43367. "vClipPlane", "diffuseMatrix", "ambientMatrix", "opacityMatrix", "reflectionMatrix", "emissiveMatrix", "specularMatrix", "bumpMatrix", "normalMatrix", "lightmapMatrix", "refractionMatrix",
  43368. "diffuseLeftColor", "diffuseRightColor", "opacityParts", "reflectionLeftColor", "reflectionRightColor", "emissiveLeftColor", "emissiveRightColor", "refractionLeftColor", "refractionRightColor",
  43369. "vReflectionPosition", "vReflectionSize",
  43370. "logarithmicDepthConstant", "vTangentSpaceParams", "alphaCutOff"
  43371. ];
  43372. var samplers = ["diffuseSampler", "ambientSampler", "opacitySampler", "reflectionCubeSampler", "reflection2DSampler", "emissiveSampler", "specularSampler", "bumpSampler", "lightmapSampler", "refractionCubeSampler", "refraction2DSampler"];
  43373. var uniformBuffers = ["Material", "Scene"];
  43374. BABYLON.ImageProcessingConfiguration.PrepareUniforms(uniforms, defines);
  43375. BABYLON.ImageProcessingConfiguration.PrepareSamplers(samplers, defines);
  43376. BABYLON.MaterialHelper.PrepareUniformsAndSamplersList({
  43377. uniformsNames: uniforms,
  43378. uniformBuffersNames: uniformBuffers,
  43379. samplers: samplers,
  43380. defines: defines,
  43381. maxSimultaneousLights: this._maxSimultaneousLights
  43382. });
  43383. if (this.customShaderNameResolve) {
  43384. shaderName = this.customShaderNameResolve(shaderName, uniforms, uniformBuffers, samplers, defines);
  43385. }
  43386. var join = defines.toString();
  43387. subMesh.setEffect(scene.getEngine().createEffect(shaderName, {
  43388. attributes: attribs,
  43389. uniformsNames: uniforms,
  43390. uniformBuffersNames: uniformBuffers,
  43391. samplers: samplers,
  43392. defines: join,
  43393. fallbacks: fallbacks,
  43394. onCompiled: this.onCompiled,
  43395. onError: this.onError,
  43396. indexParameters: { maxSimultaneousLights: this._maxSimultaneousLights, maxSimultaneousMorphTargets: defines.NUM_MORPH_INFLUENCERS }
  43397. }, engine), defines);
  43398. this.buildUniformLayout();
  43399. }
  43400. if (!subMesh.effect || !subMesh.effect.isReady()) {
  43401. return false;
  43402. }
  43403. defines._renderId = scene.getRenderId();
  43404. this._wasPreviouslyReady = true;
  43405. return true;
  43406. };
  43407. StandardMaterial.prototype.buildUniformLayout = function () {
  43408. // Order is important !
  43409. this._uniformBuffer.addUniform("diffuseLeftColor", 4);
  43410. this._uniformBuffer.addUniform("diffuseRightColor", 4);
  43411. this._uniformBuffer.addUniform("opacityParts", 4);
  43412. this._uniformBuffer.addUniform("reflectionLeftColor", 4);
  43413. this._uniformBuffer.addUniform("reflectionRightColor", 4);
  43414. this._uniformBuffer.addUniform("refractionLeftColor", 4);
  43415. this._uniformBuffer.addUniform("refractionRightColor", 4);
  43416. this._uniformBuffer.addUniform("emissiveLeftColor", 4);
  43417. this._uniformBuffer.addUniform("emissiveRightColor", 4);
  43418. this._uniformBuffer.addUniform("vDiffuseInfos", 2);
  43419. this._uniformBuffer.addUniform("vAmbientInfos", 2);
  43420. this._uniformBuffer.addUniform("vOpacityInfos", 2);
  43421. this._uniformBuffer.addUniform("vReflectionInfos", 2);
  43422. this._uniformBuffer.addUniform("vReflectionPosition", 3);
  43423. this._uniformBuffer.addUniform("vReflectionSize", 3);
  43424. this._uniformBuffer.addUniform("vEmissiveInfos", 2);
  43425. this._uniformBuffer.addUniform("vLightmapInfos", 2);
  43426. this._uniformBuffer.addUniform("vSpecularInfos", 2);
  43427. this._uniformBuffer.addUniform("vBumpInfos", 3);
  43428. this._uniformBuffer.addUniform("diffuseMatrix", 16);
  43429. this._uniformBuffer.addUniform("ambientMatrix", 16);
  43430. this._uniformBuffer.addUniform("opacityMatrix", 16);
  43431. this._uniformBuffer.addUniform("reflectionMatrix", 16);
  43432. this._uniformBuffer.addUniform("emissiveMatrix", 16);
  43433. this._uniformBuffer.addUniform("lightmapMatrix", 16);
  43434. this._uniformBuffer.addUniform("specularMatrix", 16);
  43435. this._uniformBuffer.addUniform("bumpMatrix", 16);
  43436. this._uniformBuffer.addUniform("vTangentSpaceParams", 2);
  43437. this._uniformBuffer.addUniform("refractionMatrix", 16);
  43438. this._uniformBuffer.addUniform("vRefractionInfos", 4);
  43439. this._uniformBuffer.addUniform("vSpecularColor", 4);
  43440. this._uniformBuffer.addUniform("vEmissiveColor", 3);
  43441. this._uniformBuffer.addUniform("vDiffuseColor", 4);
  43442. this._uniformBuffer.addUniform("pointSize", 1);
  43443. this._uniformBuffer.create();
  43444. };
  43445. StandardMaterial.prototype.unbind = function () {
  43446. if (this._activeEffect) {
  43447. var needFlag = false;
  43448. if (this._reflectionTexture && this._reflectionTexture.isRenderTarget) {
  43449. this._activeEffect.setTexture("reflection2DSampler", null);
  43450. needFlag = true;
  43451. }
  43452. if (this._refractionTexture && this._refractionTexture.isRenderTarget) {
  43453. this._activeEffect.setTexture("refraction2DSampler", null);
  43454. needFlag = true;
  43455. }
  43456. if (needFlag) {
  43457. this._markAllSubMeshesAsTexturesDirty();
  43458. }
  43459. }
  43460. _super.prototype.unbind.call(this);
  43461. };
  43462. StandardMaterial.prototype.bindForSubMesh = function (world, mesh, subMesh) {
  43463. var scene = this.getScene();
  43464. var defines = subMesh._materialDefines;
  43465. if (!defines) {
  43466. return;
  43467. }
  43468. var effect = subMesh.effect;
  43469. if (!effect) {
  43470. return;
  43471. }
  43472. this._activeEffect = effect;
  43473. // Matrices
  43474. this.bindOnlyWorldMatrix(world);
  43475. // Normal Matrix
  43476. if (defines.OBJECTSPACE_NORMALMAP) {
  43477. world.toNormalMatrix(this._normalMatrix);
  43478. this.bindOnlyNormalMatrix(this._normalMatrix);
  43479. }
  43480. var mustRebind = this._mustRebind(scene, effect, mesh.visibility);
  43481. // Bones
  43482. BABYLON.MaterialHelper.BindBonesParameters(mesh, effect);
  43483. if (mustRebind) {
  43484. this._uniformBuffer.bindToEffect(effect, "Material");
  43485. this.bindViewProjection(effect);
  43486. if (!this._uniformBuffer.useUbo || !this.isFrozen || !this._uniformBuffer.isSync) {
  43487. if (StandardMaterial.FresnelEnabled && defines.FRESNEL) {
  43488. // Fresnel
  43489. if (this.diffuseFresnelParameters && this.diffuseFresnelParameters.isEnabled) {
  43490. this._uniformBuffer.updateColor4("diffuseLeftColor", this.diffuseFresnelParameters.leftColor, this.diffuseFresnelParameters.power);
  43491. this._uniformBuffer.updateColor4("diffuseRightColor", this.diffuseFresnelParameters.rightColor, this.diffuseFresnelParameters.bias);
  43492. }
  43493. if (this.opacityFresnelParameters && this.opacityFresnelParameters.isEnabled) {
  43494. this._uniformBuffer.updateColor4("opacityParts", new BABYLON.Color3(this.opacityFresnelParameters.leftColor.toLuminance(), this.opacityFresnelParameters.rightColor.toLuminance(), this.opacityFresnelParameters.bias), this.opacityFresnelParameters.power);
  43495. }
  43496. if (this.reflectionFresnelParameters && this.reflectionFresnelParameters.isEnabled) {
  43497. this._uniformBuffer.updateColor4("reflectionLeftColor", this.reflectionFresnelParameters.leftColor, this.reflectionFresnelParameters.power);
  43498. this._uniformBuffer.updateColor4("reflectionRightColor", this.reflectionFresnelParameters.rightColor, this.reflectionFresnelParameters.bias);
  43499. }
  43500. if (this.refractionFresnelParameters && this.refractionFresnelParameters.isEnabled) {
  43501. this._uniformBuffer.updateColor4("refractionLeftColor", this.refractionFresnelParameters.leftColor, this.refractionFresnelParameters.power);
  43502. this._uniformBuffer.updateColor4("refractionRightColor", this.refractionFresnelParameters.rightColor, this.refractionFresnelParameters.bias);
  43503. }
  43504. if (this.emissiveFresnelParameters && this.emissiveFresnelParameters.isEnabled) {
  43505. this._uniformBuffer.updateColor4("emissiveLeftColor", this.emissiveFresnelParameters.leftColor, this.emissiveFresnelParameters.power);
  43506. this._uniformBuffer.updateColor4("emissiveRightColor", this.emissiveFresnelParameters.rightColor, this.emissiveFresnelParameters.bias);
  43507. }
  43508. }
  43509. // Textures
  43510. if (scene.texturesEnabled) {
  43511. if (this._diffuseTexture && StandardMaterial.DiffuseTextureEnabled) {
  43512. this._uniformBuffer.updateFloat2("vDiffuseInfos", this._diffuseTexture.coordinatesIndex, this._diffuseTexture.level);
  43513. BABYLON.MaterialHelper.BindTextureMatrix(this._diffuseTexture, this._uniformBuffer, "diffuse");
  43514. if (this._diffuseTexture.hasAlpha) {
  43515. effect.setFloat("alphaCutOff", this.alphaCutOff);
  43516. }
  43517. }
  43518. if (this._ambientTexture && StandardMaterial.AmbientTextureEnabled) {
  43519. this._uniformBuffer.updateFloat2("vAmbientInfos", this._ambientTexture.coordinatesIndex, this._ambientTexture.level);
  43520. BABYLON.MaterialHelper.BindTextureMatrix(this._ambientTexture, this._uniformBuffer, "ambient");
  43521. }
  43522. if (this._opacityTexture && StandardMaterial.OpacityTextureEnabled) {
  43523. this._uniformBuffer.updateFloat2("vOpacityInfos", this._opacityTexture.coordinatesIndex, this._opacityTexture.level);
  43524. BABYLON.MaterialHelper.BindTextureMatrix(this._opacityTexture, this._uniformBuffer, "opacity");
  43525. }
  43526. if (this._reflectionTexture && StandardMaterial.ReflectionTextureEnabled) {
  43527. this._uniformBuffer.updateFloat2("vReflectionInfos", this._reflectionTexture.level, this.roughness);
  43528. this._uniformBuffer.updateMatrix("reflectionMatrix", this._reflectionTexture.getReflectionTextureMatrix());
  43529. if (this._reflectionTexture.boundingBoxSize) {
  43530. var cubeTexture = this._reflectionTexture;
  43531. this._uniformBuffer.updateVector3("vReflectionPosition", cubeTexture.boundingBoxPosition);
  43532. this._uniformBuffer.updateVector3("vReflectionSize", cubeTexture.boundingBoxSize);
  43533. }
  43534. }
  43535. if (this._emissiveTexture && StandardMaterial.EmissiveTextureEnabled) {
  43536. this._uniformBuffer.updateFloat2("vEmissiveInfos", this._emissiveTexture.coordinatesIndex, this._emissiveTexture.level);
  43537. BABYLON.MaterialHelper.BindTextureMatrix(this._emissiveTexture, this._uniformBuffer, "emissive");
  43538. }
  43539. if (this._lightmapTexture && StandardMaterial.LightmapTextureEnabled) {
  43540. this._uniformBuffer.updateFloat2("vLightmapInfos", this._lightmapTexture.coordinatesIndex, this._lightmapTexture.level);
  43541. BABYLON.MaterialHelper.BindTextureMatrix(this._lightmapTexture, this._uniformBuffer, "lightmap");
  43542. }
  43543. if (this._specularTexture && StandardMaterial.SpecularTextureEnabled) {
  43544. this._uniformBuffer.updateFloat2("vSpecularInfos", this._specularTexture.coordinatesIndex, this._specularTexture.level);
  43545. BABYLON.MaterialHelper.BindTextureMatrix(this._specularTexture, this._uniformBuffer, "specular");
  43546. }
  43547. if (this._bumpTexture && scene.getEngine().getCaps().standardDerivatives && StandardMaterial.BumpTextureEnabled) {
  43548. this._uniformBuffer.updateFloat3("vBumpInfos", this._bumpTexture.coordinatesIndex, 1.0 / this._bumpTexture.level, this.parallaxScaleBias);
  43549. BABYLON.MaterialHelper.BindTextureMatrix(this._bumpTexture, this._uniformBuffer, "bump");
  43550. if (scene._mirroredCameraPosition) {
  43551. this._uniformBuffer.updateFloat2("vTangentSpaceParams", this._invertNormalMapX ? 1.0 : -1.0, this._invertNormalMapY ? 1.0 : -1.0);
  43552. }
  43553. else {
  43554. this._uniformBuffer.updateFloat2("vTangentSpaceParams", this._invertNormalMapX ? -1.0 : 1.0, this._invertNormalMapY ? -1.0 : 1.0);
  43555. }
  43556. }
  43557. if (this._refractionTexture && StandardMaterial.RefractionTextureEnabled) {
  43558. var depth = 1.0;
  43559. if (!this._refractionTexture.isCube) {
  43560. this._uniformBuffer.updateMatrix("refractionMatrix", this._refractionTexture.getReflectionTextureMatrix());
  43561. if (this._refractionTexture.depth) {
  43562. depth = this._refractionTexture.depth;
  43563. }
  43564. }
  43565. this._uniformBuffer.updateFloat4("vRefractionInfos", this._refractionTexture.level, this.indexOfRefraction, depth, this.invertRefractionY ? -1 : 1);
  43566. }
  43567. }
  43568. // Point size
  43569. if (this.pointsCloud) {
  43570. this._uniformBuffer.updateFloat("pointSize", this.pointSize);
  43571. }
  43572. if (defines.SPECULARTERM) {
  43573. this._uniformBuffer.updateColor4("vSpecularColor", this.specularColor, this.specularPower);
  43574. }
  43575. this._uniformBuffer.updateColor3("vEmissiveColor", this.emissiveColor);
  43576. // Diffuse
  43577. this._uniformBuffer.updateColor4("vDiffuseColor", this.diffuseColor, this.alpha * mesh.visibility);
  43578. }
  43579. // Textures
  43580. if (scene.texturesEnabled) {
  43581. if (this._diffuseTexture && StandardMaterial.DiffuseTextureEnabled) {
  43582. effect.setTexture("diffuseSampler", this._diffuseTexture);
  43583. }
  43584. if (this._ambientTexture && StandardMaterial.AmbientTextureEnabled) {
  43585. effect.setTexture("ambientSampler", this._ambientTexture);
  43586. }
  43587. if (this._opacityTexture && StandardMaterial.OpacityTextureEnabled) {
  43588. effect.setTexture("opacitySampler", this._opacityTexture);
  43589. }
  43590. if (this._reflectionTexture && StandardMaterial.ReflectionTextureEnabled) {
  43591. if (this._reflectionTexture.isCube) {
  43592. effect.setTexture("reflectionCubeSampler", this._reflectionTexture);
  43593. }
  43594. else {
  43595. effect.setTexture("reflection2DSampler", this._reflectionTexture);
  43596. }
  43597. }
  43598. if (this._emissiveTexture && StandardMaterial.EmissiveTextureEnabled) {
  43599. effect.setTexture("emissiveSampler", this._emissiveTexture);
  43600. }
  43601. if (this._lightmapTexture && StandardMaterial.LightmapTextureEnabled) {
  43602. effect.setTexture("lightmapSampler", this._lightmapTexture);
  43603. }
  43604. if (this._specularTexture && StandardMaterial.SpecularTextureEnabled) {
  43605. effect.setTexture("specularSampler", this._specularTexture);
  43606. }
  43607. if (this._bumpTexture && scene.getEngine().getCaps().standardDerivatives && StandardMaterial.BumpTextureEnabled) {
  43608. effect.setTexture("bumpSampler", this._bumpTexture);
  43609. }
  43610. if (this._refractionTexture && StandardMaterial.RefractionTextureEnabled) {
  43611. var depth = 1.0;
  43612. if (this._refractionTexture.isCube) {
  43613. effect.setTexture("refractionCubeSampler", this._refractionTexture);
  43614. }
  43615. else {
  43616. effect.setTexture("refraction2DSampler", this._refractionTexture);
  43617. }
  43618. }
  43619. }
  43620. // Clip plane
  43621. BABYLON.MaterialHelper.BindClipPlane(effect, scene);
  43622. // Colors
  43623. scene.ambientColor.multiplyToRef(this.ambientColor, this._globalAmbientColor);
  43624. BABYLON.MaterialHelper.BindEyePosition(effect, scene);
  43625. effect.setColor3("vAmbientColor", this._globalAmbientColor);
  43626. }
  43627. if (mustRebind || !this.isFrozen) {
  43628. // Lights
  43629. if (scene.lightsEnabled && !this._disableLighting) {
  43630. BABYLON.MaterialHelper.BindLights(scene, mesh, effect, defines, this._maxSimultaneousLights);
  43631. }
  43632. // View
  43633. if (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE || this._reflectionTexture || this._refractionTexture) {
  43634. this.bindView(effect);
  43635. }
  43636. // Fog
  43637. BABYLON.MaterialHelper.BindFogParameters(scene, mesh, effect);
  43638. // Morph targets
  43639. if (defines.NUM_MORPH_INFLUENCERS) {
  43640. BABYLON.MaterialHelper.BindMorphTargetParameters(mesh, effect);
  43641. }
  43642. // Log. depth
  43643. BABYLON.MaterialHelper.BindLogDepth(defines, effect, scene);
  43644. // image processing
  43645. if (!this._imageProcessingConfiguration.applyByPostProcess) {
  43646. this._imageProcessingConfiguration.bind(this._activeEffect);
  43647. }
  43648. }
  43649. this._uniformBuffer.update();
  43650. this._afterBind(mesh, this._activeEffect);
  43651. };
  43652. StandardMaterial.prototype.getAnimatables = function () {
  43653. var results = [];
  43654. if (this._diffuseTexture && this._diffuseTexture.animations && this._diffuseTexture.animations.length > 0) {
  43655. results.push(this._diffuseTexture);
  43656. }
  43657. if (this._ambientTexture && this._ambientTexture.animations && this._ambientTexture.animations.length > 0) {
  43658. results.push(this._ambientTexture);
  43659. }
  43660. if (this._opacityTexture && this._opacityTexture.animations && this._opacityTexture.animations.length > 0) {
  43661. results.push(this._opacityTexture);
  43662. }
  43663. if (this._reflectionTexture && this._reflectionTexture.animations && this._reflectionTexture.animations.length > 0) {
  43664. results.push(this._reflectionTexture);
  43665. }
  43666. if (this._emissiveTexture && this._emissiveTexture.animations && this._emissiveTexture.animations.length > 0) {
  43667. results.push(this._emissiveTexture);
  43668. }
  43669. if (this._specularTexture && this._specularTexture.animations && this._specularTexture.animations.length > 0) {
  43670. results.push(this._specularTexture);
  43671. }
  43672. if (this._bumpTexture && this._bumpTexture.animations && this._bumpTexture.animations.length > 0) {
  43673. results.push(this._bumpTexture);
  43674. }
  43675. if (this._lightmapTexture && this._lightmapTexture.animations && this._lightmapTexture.animations.length > 0) {
  43676. results.push(this._lightmapTexture);
  43677. }
  43678. if (this._refractionTexture && this._refractionTexture.animations && this._refractionTexture.animations.length > 0) {
  43679. results.push(this._refractionTexture);
  43680. }
  43681. return results;
  43682. };
  43683. StandardMaterial.prototype.getActiveTextures = function () {
  43684. var activeTextures = _super.prototype.getActiveTextures.call(this);
  43685. if (this._diffuseTexture) {
  43686. activeTextures.push(this._diffuseTexture);
  43687. }
  43688. if (this._ambientTexture) {
  43689. activeTextures.push(this._ambientTexture);
  43690. }
  43691. if (this._opacityTexture) {
  43692. activeTextures.push(this._opacityTexture);
  43693. }
  43694. if (this._reflectionTexture) {
  43695. activeTextures.push(this._reflectionTexture);
  43696. }
  43697. if (this._emissiveTexture) {
  43698. activeTextures.push(this._emissiveTexture);
  43699. }
  43700. if (this._specularTexture) {
  43701. activeTextures.push(this._specularTexture);
  43702. }
  43703. if (this._bumpTexture) {
  43704. activeTextures.push(this._bumpTexture);
  43705. }
  43706. if (this._lightmapTexture) {
  43707. activeTextures.push(this._lightmapTexture);
  43708. }
  43709. if (this._refractionTexture) {
  43710. activeTextures.push(this._refractionTexture);
  43711. }
  43712. return activeTextures;
  43713. };
  43714. StandardMaterial.prototype.hasTexture = function (texture) {
  43715. if (_super.prototype.hasTexture.call(this, texture)) {
  43716. return true;
  43717. }
  43718. if (this._diffuseTexture === texture) {
  43719. return true;
  43720. }
  43721. if (this._ambientTexture === texture) {
  43722. return true;
  43723. }
  43724. if (this._opacityTexture === texture) {
  43725. return true;
  43726. }
  43727. if (this._reflectionTexture === texture) {
  43728. return true;
  43729. }
  43730. if (this._emissiveTexture === texture) {
  43731. return true;
  43732. }
  43733. if (this._specularTexture === texture) {
  43734. return true;
  43735. }
  43736. if (this._bumpTexture === texture) {
  43737. return true;
  43738. }
  43739. if (this._lightmapTexture === texture) {
  43740. return true;
  43741. }
  43742. if (this._refractionTexture === texture) {
  43743. return true;
  43744. }
  43745. return false;
  43746. };
  43747. StandardMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  43748. if (forceDisposeTextures) {
  43749. if (this._diffuseTexture) {
  43750. this._diffuseTexture.dispose();
  43751. }
  43752. if (this._ambientTexture) {
  43753. this._ambientTexture.dispose();
  43754. }
  43755. if (this._opacityTexture) {
  43756. this._opacityTexture.dispose();
  43757. }
  43758. if (this._reflectionTexture) {
  43759. this._reflectionTexture.dispose();
  43760. }
  43761. if (this._emissiveTexture) {
  43762. this._emissiveTexture.dispose();
  43763. }
  43764. if (this._specularTexture) {
  43765. this._specularTexture.dispose();
  43766. }
  43767. if (this._bumpTexture) {
  43768. this._bumpTexture.dispose();
  43769. }
  43770. if (this._lightmapTexture) {
  43771. this._lightmapTexture.dispose();
  43772. }
  43773. if (this._refractionTexture) {
  43774. this._refractionTexture.dispose();
  43775. }
  43776. }
  43777. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  43778. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  43779. }
  43780. _super.prototype.dispose.call(this, forceDisposeEffect, forceDisposeTextures);
  43781. };
  43782. StandardMaterial.prototype.clone = function (name) {
  43783. var _this = this;
  43784. var result = BABYLON.SerializationHelper.Clone(function () { return new StandardMaterial(name, _this.getScene()); }, this);
  43785. result.name = name;
  43786. result.id = name;
  43787. return result;
  43788. };
  43789. StandardMaterial.prototype.serialize = function () {
  43790. return BABYLON.SerializationHelper.Serialize(this);
  43791. };
  43792. // Statics
  43793. StandardMaterial.Parse = function (source, scene, rootUrl) {
  43794. return BABYLON.SerializationHelper.Parse(function () { return new StandardMaterial(source.name, scene); }, source, scene, rootUrl);
  43795. };
  43796. Object.defineProperty(StandardMaterial, "DiffuseTextureEnabled", {
  43797. get: function () {
  43798. return StandardMaterial._DiffuseTextureEnabled;
  43799. },
  43800. set: function (value) {
  43801. if (StandardMaterial._DiffuseTextureEnabled === value) {
  43802. return;
  43803. }
  43804. StandardMaterial._DiffuseTextureEnabled = value;
  43805. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  43806. },
  43807. enumerable: true,
  43808. configurable: true
  43809. });
  43810. Object.defineProperty(StandardMaterial, "AmbientTextureEnabled", {
  43811. get: function () {
  43812. return StandardMaterial._AmbientTextureEnabled;
  43813. },
  43814. set: function (value) {
  43815. if (StandardMaterial._AmbientTextureEnabled === value) {
  43816. return;
  43817. }
  43818. StandardMaterial._AmbientTextureEnabled = value;
  43819. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  43820. },
  43821. enumerable: true,
  43822. configurable: true
  43823. });
  43824. Object.defineProperty(StandardMaterial, "OpacityTextureEnabled", {
  43825. get: function () {
  43826. return StandardMaterial._OpacityTextureEnabled;
  43827. },
  43828. set: function (value) {
  43829. if (StandardMaterial._OpacityTextureEnabled === value) {
  43830. return;
  43831. }
  43832. StandardMaterial._OpacityTextureEnabled = value;
  43833. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  43834. },
  43835. enumerable: true,
  43836. configurable: true
  43837. });
  43838. Object.defineProperty(StandardMaterial, "ReflectionTextureEnabled", {
  43839. get: function () {
  43840. return StandardMaterial._ReflectionTextureEnabled;
  43841. },
  43842. set: function (value) {
  43843. if (StandardMaterial._ReflectionTextureEnabled === value) {
  43844. return;
  43845. }
  43846. StandardMaterial._ReflectionTextureEnabled = value;
  43847. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  43848. },
  43849. enumerable: true,
  43850. configurable: true
  43851. });
  43852. Object.defineProperty(StandardMaterial, "EmissiveTextureEnabled", {
  43853. get: function () {
  43854. return StandardMaterial._EmissiveTextureEnabled;
  43855. },
  43856. set: function (value) {
  43857. if (StandardMaterial._EmissiveTextureEnabled === value) {
  43858. return;
  43859. }
  43860. StandardMaterial._EmissiveTextureEnabled = value;
  43861. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  43862. },
  43863. enumerable: true,
  43864. configurable: true
  43865. });
  43866. Object.defineProperty(StandardMaterial, "SpecularTextureEnabled", {
  43867. get: function () {
  43868. return StandardMaterial._SpecularTextureEnabled;
  43869. },
  43870. set: function (value) {
  43871. if (StandardMaterial._SpecularTextureEnabled === value) {
  43872. return;
  43873. }
  43874. StandardMaterial._SpecularTextureEnabled = value;
  43875. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  43876. },
  43877. enumerable: true,
  43878. configurable: true
  43879. });
  43880. Object.defineProperty(StandardMaterial, "BumpTextureEnabled", {
  43881. get: function () {
  43882. return StandardMaterial._BumpTextureEnabled;
  43883. },
  43884. set: function (value) {
  43885. if (StandardMaterial._BumpTextureEnabled === value) {
  43886. return;
  43887. }
  43888. StandardMaterial._BumpTextureEnabled = value;
  43889. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  43890. },
  43891. enumerable: true,
  43892. configurable: true
  43893. });
  43894. Object.defineProperty(StandardMaterial, "LightmapTextureEnabled", {
  43895. get: function () {
  43896. return StandardMaterial._LightmapTextureEnabled;
  43897. },
  43898. set: function (value) {
  43899. if (StandardMaterial._LightmapTextureEnabled === value) {
  43900. return;
  43901. }
  43902. StandardMaterial._LightmapTextureEnabled = value;
  43903. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  43904. },
  43905. enumerable: true,
  43906. configurable: true
  43907. });
  43908. Object.defineProperty(StandardMaterial, "RefractionTextureEnabled", {
  43909. get: function () {
  43910. return StandardMaterial._RefractionTextureEnabled;
  43911. },
  43912. set: function (value) {
  43913. if (StandardMaterial._RefractionTextureEnabled === value) {
  43914. return;
  43915. }
  43916. StandardMaterial._RefractionTextureEnabled = value;
  43917. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  43918. },
  43919. enumerable: true,
  43920. configurable: true
  43921. });
  43922. Object.defineProperty(StandardMaterial, "ColorGradingTextureEnabled", {
  43923. get: function () {
  43924. return StandardMaterial._ColorGradingTextureEnabled;
  43925. },
  43926. set: function (value) {
  43927. if (StandardMaterial._ColorGradingTextureEnabled === value) {
  43928. return;
  43929. }
  43930. StandardMaterial._ColorGradingTextureEnabled = value;
  43931. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  43932. },
  43933. enumerable: true,
  43934. configurable: true
  43935. });
  43936. Object.defineProperty(StandardMaterial, "FresnelEnabled", {
  43937. get: function () {
  43938. return StandardMaterial._FresnelEnabled;
  43939. },
  43940. set: function (value) {
  43941. if (StandardMaterial._FresnelEnabled === value) {
  43942. return;
  43943. }
  43944. StandardMaterial._FresnelEnabled = value;
  43945. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.FresnelDirtyFlag);
  43946. },
  43947. enumerable: true,
  43948. configurable: true
  43949. });
  43950. // Flags used to enable or disable a type of texture for all Standard Materials
  43951. StandardMaterial._DiffuseTextureEnabled = true;
  43952. StandardMaterial._AmbientTextureEnabled = true;
  43953. StandardMaterial._OpacityTextureEnabled = true;
  43954. StandardMaterial._ReflectionTextureEnabled = true;
  43955. StandardMaterial._EmissiveTextureEnabled = true;
  43956. StandardMaterial._SpecularTextureEnabled = true;
  43957. StandardMaterial._BumpTextureEnabled = true;
  43958. StandardMaterial._LightmapTextureEnabled = true;
  43959. StandardMaterial._RefractionTextureEnabled = true;
  43960. StandardMaterial._ColorGradingTextureEnabled = true;
  43961. StandardMaterial._FresnelEnabled = true;
  43962. __decorate([
  43963. BABYLON.serializeAsTexture("diffuseTexture")
  43964. ], StandardMaterial.prototype, "_diffuseTexture", void 0);
  43965. __decorate([
  43966. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesAndMiscDirty")
  43967. ], StandardMaterial.prototype, "diffuseTexture", void 0);
  43968. __decorate([
  43969. BABYLON.serializeAsTexture("ambientTexture")
  43970. ], StandardMaterial.prototype, "_ambientTexture", void 0);
  43971. __decorate([
  43972. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43973. ], StandardMaterial.prototype, "ambientTexture", void 0);
  43974. __decorate([
  43975. BABYLON.serializeAsTexture("opacityTexture")
  43976. ], StandardMaterial.prototype, "_opacityTexture", void 0);
  43977. __decorate([
  43978. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesAndMiscDirty")
  43979. ], StandardMaterial.prototype, "opacityTexture", void 0);
  43980. __decorate([
  43981. BABYLON.serializeAsTexture("reflectionTexture")
  43982. ], StandardMaterial.prototype, "_reflectionTexture", void 0);
  43983. __decorate([
  43984. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43985. ], StandardMaterial.prototype, "reflectionTexture", void 0);
  43986. __decorate([
  43987. BABYLON.serializeAsTexture("emissiveTexture")
  43988. ], StandardMaterial.prototype, "_emissiveTexture", void 0);
  43989. __decorate([
  43990. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43991. ], StandardMaterial.prototype, "emissiveTexture", void 0);
  43992. __decorate([
  43993. BABYLON.serializeAsTexture("specularTexture")
  43994. ], StandardMaterial.prototype, "_specularTexture", void 0);
  43995. __decorate([
  43996. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43997. ], StandardMaterial.prototype, "specularTexture", void 0);
  43998. __decorate([
  43999. BABYLON.serializeAsTexture("bumpTexture")
  44000. ], StandardMaterial.prototype, "_bumpTexture", void 0);
  44001. __decorate([
  44002. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  44003. ], StandardMaterial.prototype, "bumpTexture", void 0);
  44004. __decorate([
  44005. BABYLON.serializeAsTexture("lightmapTexture")
  44006. ], StandardMaterial.prototype, "_lightmapTexture", void 0);
  44007. __decorate([
  44008. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  44009. ], StandardMaterial.prototype, "lightmapTexture", void 0);
  44010. __decorate([
  44011. BABYLON.serializeAsTexture("refractionTexture")
  44012. ], StandardMaterial.prototype, "_refractionTexture", void 0);
  44013. __decorate([
  44014. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  44015. ], StandardMaterial.prototype, "refractionTexture", void 0);
  44016. __decorate([
  44017. BABYLON.serializeAsColor3("ambient")
  44018. ], StandardMaterial.prototype, "ambientColor", void 0);
  44019. __decorate([
  44020. BABYLON.serializeAsColor3("diffuse")
  44021. ], StandardMaterial.prototype, "diffuseColor", void 0);
  44022. __decorate([
  44023. BABYLON.serializeAsColor3("specular")
  44024. ], StandardMaterial.prototype, "specularColor", void 0);
  44025. __decorate([
  44026. BABYLON.serializeAsColor3("emissive")
  44027. ], StandardMaterial.prototype, "emissiveColor", void 0);
  44028. __decorate([
  44029. BABYLON.serialize()
  44030. ], StandardMaterial.prototype, "specularPower", void 0);
  44031. __decorate([
  44032. BABYLON.serialize("useAlphaFromDiffuseTexture")
  44033. ], StandardMaterial.prototype, "_useAlphaFromDiffuseTexture", void 0);
  44034. __decorate([
  44035. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  44036. ], StandardMaterial.prototype, "useAlphaFromDiffuseTexture", void 0);
  44037. __decorate([
  44038. BABYLON.serialize("useEmissiveAsIllumination")
  44039. ], StandardMaterial.prototype, "_useEmissiveAsIllumination", void 0);
  44040. __decorate([
  44041. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  44042. ], StandardMaterial.prototype, "useEmissiveAsIllumination", void 0);
  44043. __decorate([
  44044. BABYLON.serialize("linkEmissiveWithDiffuse")
  44045. ], StandardMaterial.prototype, "_linkEmissiveWithDiffuse", void 0);
  44046. __decorate([
  44047. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  44048. ], StandardMaterial.prototype, "linkEmissiveWithDiffuse", void 0);
  44049. __decorate([
  44050. BABYLON.serialize("useSpecularOverAlpha")
  44051. ], StandardMaterial.prototype, "_useSpecularOverAlpha", void 0);
  44052. __decorate([
  44053. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  44054. ], StandardMaterial.prototype, "useSpecularOverAlpha", void 0);
  44055. __decorate([
  44056. BABYLON.serialize("useReflectionOverAlpha")
  44057. ], StandardMaterial.prototype, "_useReflectionOverAlpha", void 0);
  44058. __decorate([
  44059. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  44060. ], StandardMaterial.prototype, "useReflectionOverAlpha", void 0);
  44061. __decorate([
  44062. BABYLON.serialize("disableLighting")
  44063. ], StandardMaterial.prototype, "_disableLighting", void 0);
  44064. __decorate([
  44065. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  44066. ], StandardMaterial.prototype, "disableLighting", void 0);
  44067. __decorate([
  44068. BABYLON.serialize("useObjectSpaceNormalMap")
  44069. ], StandardMaterial.prototype, "_useObjectSpaceNormalMap", void 0);
  44070. __decorate([
  44071. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  44072. ], StandardMaterial.prototype, "useObjectSpaceNormalMap", void 0);
  44073. __decorate([
  44074. BABYLON.serialize("useParallax")
  44075. ], StandardMaterial.prototype, "_useParallax", void 0);
  44076. __decorate([
  44077. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  44078. ], StandardMaterial.prototype, "useParallax", void 0);
  44079. __decorate([
  44080. BABYLON.serialize("useParallaxOcclusion")
  44081. ], StandardMaterial.prototype, "_useParallaxOcclusion", void 0);
  44082. __decorate([
  44083. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  44084. ], StandardMaterial.prototype, "useParallaxOcclusion", void 0);
  44085. __decorate([
  44086. BABYLON.serialize()
  44087. ], StandardMaterial.prototype, "parallaxScaleBias", void 0);
  44088. __decorate([
  44089. BABYLON.serialize("roughness")
  44090. ], StandardMaterial.prototype, "_roughness", void 0);
  44091. __decorate([
  44092. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  44093. ], StandardMaterial.prototype, "roughness", void 0);
  44094. __decorate([
  44095. BABYLON.serialize()
  44096. ], StandardMaterial.prototype, "indexOfRefraction", void 0);
  44097. __decorate([
  44098. BABYLON.serialize()
  44099. ], StandardMaterial.prototype, "invertRefractionY", void 0);
  44100. __decorate([
  44101. BABYLON.serialize()
  44102. ], StandardMaterial.prototype, "alphaCutOff", void 0);
  44103. __decorate([
  44104. BABYLON.serialize("useLightmapAsShadowmap")
  44105. ], StandardMaterial.prototype, "_useLightmapAsShadowmap", void 0);
  44106. __decorate([
  44107. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  44108. ], StandardMaterial.prototype, "useLightmapAsShadowmap", void 0);
  44109. __decorate([
  44110. BABYLON.serializeAsFresnelParameters("diffuseFresnelParameters")
  44111. ], StandardMaterial.prototype, "_diffuseFresnelParameters", void 0);
  44112. __decorate([
  44113. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  44114. ], StandardMaterial.prototype, "diffuseFresnelParameters", void 0);
  44115. __decorate([
  44116. BABYLON.serializeAsFresnelParameters("opacityFresnelParameters")
  44117. ], StandardMaterial.prototype, "_opacityFresnelParameters", void 0);
  44118. __decorate([
  44119. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelAndMiscDirty")
  44120. ], StandardMaterial.prototype, "opacityFresnelParameters", void 0);
  44121. __decorate([
  44122. BABYLON.serializeAsFresnelParameters("reflectionFresnelParameters")
  44123. ], StandardMaterial.prototype, "_reflectionFresnelParameters", void 0);
  44124. __decorate([
  44125. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  44126. ], StandardMaterial.prototype, "reflectionFresnelParameters", void 0);
  44127. __decorate([
  44128. BABYLON.serializeAsFresnelParameters("refractionFresnelParameters")
  44129. ], StandardMaterial.prototype, "_refractionFresnelParameters", void 0);
  44130. __decorate([
  44131. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  44132. ], StandardMaterial.prototype, "refractionFresnelParameters", void 0);
  44133. __decorate([
  44134. BABYLON.serializeAsFresnelParameters("emissiveFresnelParameters")
  44135. ], StandardMaterial.prototype, "_emissiveFresnelParameters", void 0);
  44136. __decorate([
  44137. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  44138. ], StandardMaterial.prototype, "emissiveFresnelParameters", void 0);
  44139. __decorate([
  44140. BABYLON.serialize("useReflectionFresnelFromSpecular")
  44141. ], StandardMaterial.prototype, "_useReflectionFresnelFromSpecular", void 0);
  44142. __decorate([
  44143. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  44144. ], StandardMaterial.prototype, "useReflectionFresnelFromSpecular", void 0);
  44145. __decorate([
  44146. BABYLON.serialize("useGlossinessFromSpecularMapAlpha")
  44147. ], StandardMaterial.prototype, "_useGlossinessFromSpecularMapAlpha", void 0);
  44148. __decorate([
  44149. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  44150. ], StandardMaterial.prototype, "useGlossinessFromSpecularMapAlpha", void 0);
  44151. __decorate([
  44152. BABYLON.serialize("maxSimultaneousLights")
  44153. ], StandardMaterial.prototype, "_maxSimultaneousLights", void 0);
  44154. __decorate([
  44155. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  44156. ], StandardMaterial.prototype, "maxSimultaneousLights", void 0);
  44157. __decorate([
  44158. BABYLON.serialize("invertNormalMapX")
  44159. ], StandardMaterial.prototype, "_invertNormalMapX", void 0);
  44160. __decorate([
  44161. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  44162. ], StandardMaterial.prototype, "invertNormalMapX", void 0);
  44163. __decorate([
  44164. BABYLON.serialize("invertNormalMapY")
  44165. ], StandardMaterial.prototype, "_invertNormalMapY", void 0);
  44166. __decorate([
  44167. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  44168. ], StandardMaterial.prototype, "invertNormalMapY", void 0);
  44169. __decorate([
  44170. BABYLON.serialize("twoSidedLighting")
  44171. ], StandardMaterial.prototype, "_twoSidedLighting", void 0);
  44172. __decorate([
  44173. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  44174. ], StandardMaterial.prototype, "twoSidedLighting", void 0);
  44175. __decorate([
  44176. BABYLON.serialize()
  44177. ], StandardMaterial.prototype, "useLogarithmicDepth", null);
  44178. return StandardMaterial;
  44179. }(BABYLON.PushMaterial));
  44180. BABYLON.StandardMaterial = StandardMaterial;
  44181. })(BABYLON || (BABYLON = {}));
  44182. //# sourceMappingURL=babylon.standardMaterial.js.map
  44183. var BABYLON;
  44184. (function (BABYLON) {
  44185. /**
  44186. * Manages the defines for the PBR Material.
  44187. * @hiddenChildren
  44188. */
  44189. var PBRMaterialDefines = /** @class */ (function (_super) {
  44190. __extends(PBRMaterialDefines, _super);
  44191. /**
  44192. * Initializes the PBR Material defines.
  44193. */
  44194. function PBRMaterialDefines() {
  44195. var _this = _super.call(this) || this;
  44196. _this.PBR = true;
  44197. _this.MAINUV1 = false;
  44198. _this.MAINUV2 = false;
  44199. _this.UV1 = false;
  44200. _this.UV2 = false;
  44201. _this.ALBEDO = false;
  44202. _this.ALBEDODIRECTUV = 0;
  44203. _this.VERTEXCOLOR = false;
  44204. _this.AMBIENT = false;
  44205. _this.AMBIENTDIRECTUV = 0;
  44206. _this.AMBIENTINGRAYSCALE = false;
  44207. _this.OPACITY = false;
  44208. _this.VERTEXALPHA = false;
  44209. _this.OPACITYDIRECTUV = 0;
  44210. _this.OPACITYRGB = false;
  44211. _this.ALPHATEST = false;
  44212. _this.DEPTHPREPASS = false;
  44213. _this.ALPHABLEND = false;
  44214. _this.ALPHAFROMALBEDO = false;
  44215. _this.ALPHATESTVALUE = "0.5";
  44216. _this.SPECULAROVERALPHA = false;
  44217. _this.RADIANCEOVERALPHA = false;
  44218. _this.ALPHAFRESNEL = false;
  44219. _this.LINEARALPHAFRESNEL = false;
  44220. _this.PREMULTIPLYALPHA = false;
  44221. _this.EMISSIVE = false;
  44222. _this.EMISSIVEDIRECTUV = 0;
  44223. _this.REFLECTIVITY = false;
  44224. _this.REFLECTIVITYDIRECTUV = 0;
  44225. _this.SPECULARTERM = false;
  44226. _this.MICROSURFACEFROMREFLECTIVITYMAP = false;
  44227. _this.MICROSURFACEAUTOMATIC = false;
  44228. _this.LODBASEDMICROSFURACE = false;
  44229. _this.MICROSURFACEMAP = false;
  44230. _this.MICROSURFACEMAPDIRECTUV = 0;
  44231. _this.METALLICWORKFLOW = false;
  44232. _this.ROUGHNESSSTOREINMETALMAPALPHA = false;
  44233. _this.ROUGHNESSSTOREINMETALMAPGREEN = false;
  44234. _this.METALLNESSSTOREINMETALMAPBLUE = false;
  44235. _this.AOSTOREINMETALMAPRED = false;
  44236. _this.ENVIRONMENTBRDF = false;
  44237. _this.NORMAL = false;
  44238. _this.TANGENT = false;
  44239. _this.BUMP = false;
  44240. _this.BUMPDIRECTUV = 0;
  44241. _this.OBJECTSPACE_NORMALMAP = false;
  44242. _this.PARALLAX = false;
  44243. _this.PARALLAXOCCLUSION = false;
  44244. _this.NORMALXYSCALE = true;
  44245. _this.LIGHTMAP = false;
  44246. _this.LIGHTMAPDIRECTUV = 0;
  44247. _this.USELIGHTMAPASSHADOWMAP = false;
  44248. _this.GAMMALIGHTMAP = false;
  44249. _this.REFLECTION = false;
  44250. _this.REFLECTIONMAP_3D = false;
  44251. _this.REFLECTIONMAP_SPHERICAL = false;
  44252. _this.REFLECTIONMAP_PLANAR = false;
  44253. _this.REFLECTIONMAP_CUBIC = false;
  44254. _this.USE_LOCAL_REFLECTIONMAP_CUBIC = false;
  44255. _this.REFLECTIONMAP_PROJECTION = false;
  44256. _this.REFLECTIONMAP_SKYBOX = false;
  44257. _this.REFLECTIONMAP_EXPLICIT = false;
  44258. _this.REFLECTIONMAP_EQUIRECTANGULAR = false;
  44259. _this.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  44260. _this.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false;
  44261. _this.INVERTCUBICMAP = false;
  44262. _this.USESPHERICALFROMREFLECTIONMAP = false;
  44263. _this.USESPHERICALINVERTEX = false;
  44264. _this.REFLECTIONMAP_OPPOSITEZ = false;
  44265. _this.LODINREFLECTIONALPHA = false;
  44266. _this.GAMMAREFLECTION = false;
  44267. _this.RADIANCEOCCLUSION = false;
  44268. _this.HORIZONOCCLUSION = false;
  44269. _this.REFRACTION = false;
  44270. _this.REFRACTIONMAP_3D = false;
  44271. _this.REFRACTIONMAP_OPPOSITEZ = false;
  44272. _this.LODINREFRACTIONALPHA = false;
  44273. _this.GAMMAREFRACTION = false;
  44274. _this.LINKREFRACTIONTOTRANSPARENCY = false;
  44275. _this.INSTANCES = false;
  44276. _this.NUM_BONE_INFLUENCERS = 0;
  44277. _this.BonesPerMesh = 0;
  44278. _this.NONUNIFORMSCALING = false;
  44279. _this.MORPHTARGETS = false;
  44280. _this.MORPHTARGETS_NORMAL = false;
  44281. _this.MORPHTARGETS_TANGENT = false;
  44282. _this.NUM_MORPH_INFLUENCERS = 0;
  44283. _this.IMAGEPROCESSING = false;
  44284. _this.VIGNETTE = false;
  44285. _this.VIGNETTEBLENDMODEMULTIPLY = false;
  44286. _this.VIGNETTEBLENDMODEOPAQUE = false;
  44287. _this.TONEMAPPING = false;
  44288. _this.CONTRAST = false;
  44289. _this.COLORCURVES = false;
  44290. _this.COLORGRADING = false;
  44291. _this.COLORGRADING3D = false;
  44292. _this.SAMPLER3DGREENDEPTH = false;
  44293. _this.SAMPLER3DBGRMAP = false;
  44294. _this.IMAGEPROCESSINGPOSTPROCESS = false;
  44295. _this.EXPOSURE = false;
  44296. _this.USEPHYSICALLIGHTFALLOFF = false;
  44297. _this.TWOSIDEDLIGHTING = false;
  44298. _this.SHADOWFLOAT = false;
  44299. _this.CLIPPLANE = false;
  44300. _this.POINTSIZE = false;
  44301. _this.FOG = false;
  44302. _this.LOGARITHMICDEPTH = false;
  44303. _this.FORCENORMALFORWARD = false;
  44304. _this.SPECULARAA = false;
  44305. _this.UNLIT = false;
  44306. _this.rebuild();
  44307. return _this;
  44308. }
  44309. /**
  44310. * Resets the PBR Material defines.
  44311. */
  44312. PBRMaterialDefines.prototype.reset = function () {
  44313. _super.prototype.reset.call(this);
  44314. this.ALPHATESTVALUE = "0.5";
  44315. this.PBR = true;
  44316. };
  44317. return PBRMaterialDefines;
  44318. }(BABYLON.MaterialDefines));
  44319. /**
  44320. * The Physically based material base class of BJS.
  44321. *
  44322. * This offers the main features of a standard PBR material.
  44323. * For more information, please refer to the documentation :
  44324. * http://doc.babylonjs.com/extensions/Physically_Based_Rendering
  44325. */
  44326. var PBRBaseMaterial = /** @class */ (function (_super) {
  44327. __extends(PBRBaseMaterial, _super);
  44328. /**
  44329. * Instantiates a new PBRMaterial instance.
  44330. *
  44331. * @param name The material name
  44332. * @param scene The scene the material will be use in.
  44333. */
  44334. function PBRBaseMaterial(name, scene) {
  44335. var _this = _super.call(this, name, scene) || this;
  44336. /**
  44337. * Intensity of the direct lights e.g. the four lights available in your scene.
  44338. * This impacts both the direct diffuse and specular highlights.
  44339. */
  44340. _this._directIntensity = 1.0;
  44341. /**
  44342. * Intensity of the emissive part of the material.
  44343. * This helps controlling the emissive effect without modifying the emissive color.
  44344. */
  44345. _this._emissiveIntensity = 1.0;
  44346. /**
  44347. * Intensity of the environment e.g. how much the environment will light the object
  44348. * either through harmonics for rough material or through the refelction for shiny ones.
  44349. */
  44350. _this._environmentIntensity = 1.0;
  44351. /**
  44352. * This is a special control allowing the reduction of the specular highlights coming from the
  44353. * four lights of the scene. Those highlights may not be needed in full environment lighting.
  44354. */
  44355. _this._specularIntensity = 1.0;
  44356. /**
  44357. * This stores the direct, emissive, environment, and specular light intensities into a Vector4.
  44358. */
  44359. _this._lightingInfos = new BABYLON.Vector4(_this._directIntensity, _this._emissiveIntensity, _this._environmentIntensity, _this._specularIntensity);
  44360. /**
  44361. * Debug Control allowing disabling the bump map on this material.
  44362. */
  44363. _this._disableBumpMap = false;
  44364. /**
  44365. * AKA Occlusion Texture Intensity in other nomenclature.
  44366. */
  44367. _this._ambientTextureStrength = 1.0;
  44368. /**
  44369. * The color of a material in ambient lighting.
  44370. */
  44371. _this._ambientColor = new BABYLON.Color3(0, 0, 0);
  44372. /**
  44373. * AKA Diffuse Color in other nomenclature.
  44374. */
  44375. _this._albedoColor = new BABYLON.Color3(1, 1, 1);
  44376. /**
  44377. * AKA Specular Color in other nomenclature.
  44378. */
  44379. _this._reflectivityColor = new BABYLON.Color3(1, 1, 1);
  44380. /**
  44381. * The color applied when light is reflected from a material.
  44382. */
  44383. _this._reflectionColor = new BABYLON.Color3(1, 1, 1);
  44384. /**
  44385. * The color applied when light is emitted from a material.
  44386. */
  44387. _this._emissiveColor = new BABYLON.Color3(0, 0, 0);
  44388. /**
  44389. * AKA Glossiness in other nomenclature.
  44390. */
  44391. _this._microSurface = 0.9;
  44392. /**
  44393. * source material index of refraction (IOR)' / 'destination material IOR.
  44394. */
  44395. _this._indexOfRefraction = 0.66;
  44396. /**
  44397. * Controls if refraction needs to be inverted on Y. This could be usefull for procedural texture.
  44398. */
  44399. _this._invertRefractionY = false;
  44400. /**
  44401. * This parameters will make the material used its opacity to control how much it is refracting aginst not.
  44402. * Materials half opaque for instance using refraction could benefit from this control.
  44403. */
  44404. _this._linkRefractionWithTransparency = false;
  44405. /**
  44406. * Specifies that the material will use the light map as a show map.
  44407. */
  44408. _this._useLightmapAsShadowmap = false;
  44409. /**
  44410. * This parameters will enable/disable Horizon occlusion to prevent normal maps to look shiny when the normal
  44411. * makes the reflect vector face the model (under horizon).
  44412. */
  44413. _this._useHorizonOcclusion = true;
  44414. /**
  44415. * This parameters will enable/disable radiance occlusion by preventing the radiance to lit
  44416. * too much the area relying on ambient texture to define their ambient occlusion.
  44417. */
  44418. _this._useRadianceOcclusion = true;
  44419. /**
  44420. * Specifies that the alpha is coming form the albedo channel alpha channel for alpha blending.
  44421. */
  44422. _this._useAlphaFromAlbedoTexture = false;
  44423. /**
  44424. * Specifies that the material will keeps the specular highlights over a transparent surface (only the most limunous ones).
  44425. * A car glass is a good exemple of that. When sun reflects on it you can not see what is behind.
  44426. */
  44427. _this._useSpecularOverAlpha = true;
  44428. /**
  44429. * Specifies if the reflectivity texture contains the glossiness information in its alpha channel.
  44430. */
  44431. _this._useMicroSurfaceFromReflectivityMapAlpha = false;
  44432. /**
  44433. * Specifies if the metallic texture contains the roughness information in its alpha channel.
  44434. */
  44435. _this._useRoughnessFromMetallicTextureAlpha = true;
  44436. /**
  44437. * Specifies if the metallic texture contains the roughness information in its green channel.
  44438. */
  44439. _this._useRoughnessFromMetallicTextureGreen = false;
  44440. /**
  44441. * Specifies if the metallic texture contains the metallness information in its blue channel.
  44442. */
  44443. _this._useMetallnessFromMetallicTextureBlue = false;
  44444. /**
  44445. * Specifies if the metallic texture contains the ambient occlusion information in its red channel.
  44446. */
  44447. _this._useAmbientOcclusionFromMetallicTextureRed = false;
  44448. /**
  44449. * Specifies if the ambient texture contains the ambient occlusion information in its red channel only.
  44450. */
  44451. _this._useAmbientInGrayScale = false;
  44452. /**
  44453. * In case the reflectivity map does not contain the microsurface information in its alpha channel,
  44454. * The material will try to infer what glossiness each pixel should be.
  44455. */
  44456. _this._useAutoMicroSurfaceFromReflectivityMap = false;
  44457. /**
  44458. * BJS is using an harcoded light falloff based on a manually sets up range.
  44459. * In PBR, one way to represents the fallof is to use the inverse squared root algorythm.
  44460. * This parameter can help you switch back to the BJS mode in order to create scenes using both materials.
  44461. */
  44462. _this._usePhysicalLightFalloff = true;
  44463. /**
  44464. * Specifies that the material will keeps the reflection highlights over a transparent surface (only the most limunous ones).
  44465. * A car glass is a good exemple of that. When the street lights reflects on it you can not see what is behind.
  44466. */
  44467. _this._useRadianceOverAlpha = true;
  44468. /**
  44469. * Allows using an object space normal map (instead of tangent space).
  44470. */
  44471. _this._useObjectSpaceNormalMap = false;
  44472. /**
  44473. * Allows using the bump map in parallax mode.
  44474. */
  44475. _this._useParallax = false;
  44476. /**
  44477. * Allows using the bump map in parallax occlusion mode.
  44478. */
  44479. _this._useParallaxOcclusion = false;
  44480. /**
  44481. * Controls the scale bias of the parallax mode.
  44482. */
  44483. _this._parallaxScaleBias = 0.05;
  44484. /**
  44485. * If sets to true, disables all the lights affecting the material.
  44486. */
  44487. _this._disableLighting = false;
  44488. /**
  44489. * Number of Simultaneous lights allowed on the material.
  44490. */
  44491. _this._maxSimultaneousLights = 4;
  44492. /**
  44493. * If sets to true, x component of normal map value will be inverted (x = 1.0 - x).
  44494. */
  44495. _this._invertNormalMapX = false;
  44496. /**
  44497. * If sets to true, y component of normal map value will be inverted (y = 1.0 - y).
  44498. */
  44499. _this._invertNormalMapY = false;
  44500. /**
  44501. * If sets to true and backfaceCulling is false, normals will be flipped on the backside.
  44502. */
  44503. _this._twoSidedLighting = false;
  44504. /**
  44505. * Defines the alpha limits in alpha test mode.
  44506. */
  44507. _this._alphaCutOff = 0.4;
  44508. /**
  44509. * Enforces alpha test in opaque or blend mode in order to improve the performances of some situations.
  44510. */
  44511. _this._forceAlphaTest = false;
  44512. /**
  44513. * A fresnel is applied to the alpha of the model to ensure grazing angles edges are not alpha tested.
  44514. * And/Or occlude the blended part. (alpha is converted to gamma to compute the fresnel)
  44515. */
  44516. _this._useAlphaFresnel = false;
  44517. /**
  44518. * A fresnel is applied to the alpha of the model to ensure grazing angles edges are not alpha tested.
  44519. * And/Or occlude the blended part. (alpha stays linear to compute the fresnel)
  44520. */
  44521. _this._useLinearAlphaFresnel = false;
  44522. /**
  44523. * The transparency mode of the material.
  44524. */
  44525. _this._transparencyMode = null;
  44526. /**
  44527. * Specifies the environment BRDF texture used to comput the scale and offset roughness values
  44528. * from cos thetav and roughness:
  44529. * http://blog.selfshadow.com/publications/s2013-shading-course/karis/s2013_pbs_epic_notes_v2.pdf
  44530. */
  44531. _this._environmentBRDFTexture = null;
  44532. /**
  44533. * Force the shader to compute irradiance in the fragment shader in order to take bump in account.
  44534. */
  44535. _this._forceIrradianceInFragment = false;
  44536. /**
  44537. * Force normal to face away from face.
  44538. */
  44539. _this._forceNormalForward = false;
  44540. /**
  44541. * Enables specular anti aliasing in the PBR shader.
  44542. * It will both interacts on the Geometry for analytical and IBL lighting.
  44543. * It also prefilter the roughness map based on the bump values.
  44544. */
  44545. _this._enableSpecularAntiAliasing = false;
  44546. /**
  44547. * Stores the available render targets.
  44548. */
  44549. _this._renderTargets = new BABYLON.SmartArray(16);
  44550. /**
  44551. * Sets the global ambient color for the material used in lighting calculations.
  44552. */
  44553. _this._globalAmbientColor = new BABYLON.Color3(0, 0, 0);
  44554. /**
  44555. * If set to true, no lighting calculations will be applied.
  44556. */
  44557. _this._unlit = false;
  44558. // Setup the default processing configuration to the scene.
  44559. _this._attachImageProcessingConfiguration(null);
  44560. _this.getRenderTargetTextures = function () {
  44561. _this._renderTargets.reset();
  44562. if (BABYLON.StandardMaterial.ReflectionTextureEnabled && _this._reflectionTexture && _this._reflectionTexture.isRenderTarget) {
  44563. _this._renderTargets.push(_this._reflectionTexture);
  44564. }
  44565. if (BABYLON.StandardMaterial.RefractionTextureEnabled && _this._refractionTexture && _this._refractionTexture.isRenderTarget) {
  44566. _this._renderTargets.push(_this._refractionTexture);
  44567. }
  44568. return _this._renderTargets;
  44569. };
  44570. _this._environmentBRDFTexture = BABYLON.TextureTools.GetEnvironmentBRDFTexture(scene);
  44571. return _this;
  44572. }
  44573. /**
  44574. * Attaches a new image processing configuration to the PBR Material.
  44575. * @param configuration
  44576. */
  44577. PBRBaseMaterial.prototype._attachImageProcessingConfiguration = function (configuration) {
  44578. var _this = this;
  44579. if (configuration === this._imageProcessingConfiguration) {
  44580. return;
  44581. }
  44582. // Detaches observer.
  44583. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  44584. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  44585. }
  44586. // Pick the scene configuration if needed.
  44587. if (!configuration) {
  44588. this._imageProcessingConfiguration = this.getScene().imageProcessingConfiguration;
  44589. }
  44590. else {
  44591. this._imageProcessingConfiguration = configuration;
  44592. }
  44593. // Attaches observer.
  44594. this._imageProcessingObserver = this._imageProcessingConfiguration.onUpdateParameters.add(function (conf) {
  44595. _this._markAllSubMeshesAsImageProcessingDirty();
  44596. });
  44597. };
  44598. /**
  44599. * Gets the name of the material class.
  44600. */
  44601. PBRBaseMaterial.prototype.getClassName = function () {
  44602. return "PBRBaseMaterial";
  44603. };
  44604. Object.defineProperty(PBRBaseMaterial.prototype, "useLogarithmicDepth", {
  44605. /**
  44606. * Enabled the use of logarithmic depth buffers, which is good for wide depth buffers.
  44607. */
  44608. get: function () {
  44609. return this._useLogarithmicDepth;
  44610. },
  44611. /**
  44612. * Enabled the use of logarithmic depth buffers, which is good for wide depth buffers.
  44613. */
  44614. set: function (value) {
  44615. this._useLogarithmicDepth = value && this.getScene().getEngine().getCaps().fragmentDepthSupported;
  44616. },
  44617. enumerable: true,
  44618. configurable: true
  44619. });
  44620. Object.defineProperty(PBRBaseMaterial.prototype, "transparencyMode", {
  44621. /**
  44622. * Gets the current transparency mode.
  44623. */
  44624. get: function () {
  44625. return this._transparencyMode;
  44626. },
  44627. /**
  44628. * Sets the transparency mode of the material.
  44629. */
  44630. set: function (value) {
  44631. if (this._transparencyMode === value) {
  44632. return;
  44633. }
  44634. this._transparencyMode = value;
  44635. this._forceAlphaTest = (value === BABYLON.PBRMaterial.PBRMATERIAL_ALPHATESTANDBLEND);
  44636. this._markAllSubMeshesAsTexturesAndMiscDirty();
  44637. },
  44638. enumerable: true,
  44639. configurable: true
  44640. });
  44641. Object.defineProperty(PBRBaseMaterial.prototype, "_disableAlphaBlending", {
  44642. /**
  44643. * Returns true if alpha blending should be disabled.
  44644. */
  44645. get: function () {
  44646. return (this._linkRefractionWithTransparency ||
  44647. this._transparencyMode === BABYLON.PBRMaterial.PBRMATERIAL_OPAQUE ||
  44648. this._transparencyMode === BABYLON.PBRMaterial.PBRMATERIAL_ALPHATEST);
  44649. },
  44650. enumerable: true,
  44651. configurable: true
  44652. });
  44653. /**
  44654. * Specifies whether or not this material should be rendered in alpha blend mode.
  44655. */
  44656. PBRBaseMaterial.prototype.needAlphaBlending = function () {
  44657. if (this._disableAlphaBlending) {
  44658. return false;
  44659. }
  44660. return (this.alpha < 1.0) || (this._opacityTexture != null) || this._shouldUseAlphaFromAlbedoTexture();
  44661. };
  44662. /**
  44663. * Specifies if the mesh will require alpha blending.
  44664. * @param mesh - BJS mesh.
  44665. */
  44666. PBRBaseMaterial.prototype.needAlphaBlendingForMesh = function (mesh) {
  44667. if (this._disableAlphaBlending) {
  44668. return false;
  44669. }
  44670. return _super.prototype.needAlphaBlendingForMesh.call(this, mesh);
  44671. };
  44672. /**
  44673. * Specifies whether or not this material should be rendered in alpha test mode.
  44674. */
  44675. PBRBaseMaterial.prototype.needAlphaTesting = function () {
  44676. if (this._forceAlphaTest) {
  44677. return true;
  44678. }
  44679. if (this._linkRefractionWithTransparency) {
  44680. return false;
  44681. }
  44682. return this._albedoTexture != null && this._albedoTexture.hasAlpha && (this._transparencyMode == null || this._transparencyMode === BABYLON.PBRMaterial.PBRMATERIAL_ALPHATEST);
  44683. };
  44684. /**
  44685. * Specifies whether or not the alpha value of the albedo texture should be used for alpha blending.
  44686. */
  44687. PBRBaseMaterial.prototype._shouldUseAlphaFromAlbedoTexture = function () {
  44688. return this._albedoTexture != null && this._albedoTexture.hasAlpha && this._useAlphaFromAlbedoTexture && this._transparencyMode !== BABYLON.PBRMaterial.PBRMATERIAL_OPAQUE;
  44689. };
  44690. /**
  44691. * Gets the texture used for the alpha test.
  44692. */
  44693. PBRBaseMaterial.prototype.getAlphaTestTexture = function () {
  44694. return this._albedoTexture;
  44695. };
  44696. /**
  44697. * Specifies that the submesh is ready to be used.
  44698. * @param mesh - BJS mesh.
  44699. * @param subMesh - A submesh of the BJS mesh. Used to check if it is ready.
  44700. * @param useInstances - Specifies that instances should be used.
  44701. * @returns - boolean indicating that the submesh is ready or not.
  44702. */
  44703. PBRBaseMaterial.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  44704. if (subMesh.effect && this.isFrozen) {
  44705. if (this._wasPreviouslyReady) {
  44706. return true;
  44707. }
  44708. }
  44709. if (!subMesh._materialDefines) {
  44710. subMesh._materialDefines = new PBRMaterialDefines();
  44711. }
  44712. var defines = subMesh._materialDefines;
  44713. if (!this.checkReadyOnEveryCall && subMesh.effect) {
  44714. if (defines._renderId === this.getScene().getRenderId()) {
  44715. return true;
  44716. }
  44717. }
  44718. var scene = this.getScene();
  44719. var engine = scene.getEngine();
  44720. if (defines._areTexturesDirty) {
  44721. if (scene.texturesEnabled) {
  44722. if (this._albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  44723. if (!this._albedoTexture.isReadyOrNotBlocking()) {
  44724. return false;
  44725. }
  44726. }
  44727. if (this._ambientTexture && BABYLON.StandardMaterial.AmbientTextureEnabled) {
  44728. if (!this._ambientTexture.isReadyOrNotBlocking()) {
  44729. return false;
  44730. }
  44731. }
  44732. if (this._opacityTexture && BABYLON.StandardMaterial.OpacityTextureEnabled) {
  44733. if (!this._opacityTexture.isReadyOrNotBlocking()) {
  44734. return false;
  44735. }
  44736. }
  44737. var reflectionTexture = this._getReflectionTexture();
  44738. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  44739. if (!reflectionTexture.isReadyOrNotBlocking()) {
  44740. return false;
  44741. }
  44742. }
  44743. if (this._lightmapTexture && BABYLON.StandardMaterial.LightmapTextureEnabled) {
  44744. if (!this._lightmapTexture.isReadyOrNotBlocking()) {
  44745. return false;
  44746. }
  44747. }
  44748. if (this._emissiveTexture && BABYLON.StandardMaterial.EmissiveTextureEnabled) {
  44749. if (!this._emissiveTexture.isReadyOrNotBlocking()) {
  44750. return false;
  44751. }
  44752. }
  44753. if (BABYLON.StandardMaterial.SpecularTextureEnabled) {
  44754. if (this._metallicTexture) {
  44755. if (!this._metallicTexture.isReadyOrNotBlocking()) {
  44756. return false;
  44757. }
  44758. }
  44759. else if (this._reflectivityTexture) {
  44760. if (!this._reflectivityTexture.isReadyOrNotBlocking()) {
  44761. return false;
  44762. }
  44763. }
  44764. if (this._microSurfaceTexture) {
  44765. if (!this._microSurfaceTexture.isReadyOrNotBlocking()) {
  44766. return false;
  44767. }
  44768. }
  44769. }
  44770. if (engine.getCaps().standardDerivatives && this._bumpTexture && BABYLON.StandardMaterial.BumpTextureEnabled && !this._disableBumpMap) {
  44771. // Bump texture cannot be not blocking.
  44772. if (!this._bumpTexture.isReady()) {
  44773. return false;
  44774. }
  44775. }
  44776. var refractionTexture = this._getRefractionTexture();
  44777. if (refractionTexture && BABYLON.StandardMaterial.RefractionTextureEnabled) {
  44778. if (!refractionTexture.isReadyOrNotBlocking()) {
  44779. return false;
  44780. }
  44781. }
  44782. if (this._environmentBRDFTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  44783. // This is blocking.
  44784. if (!this._environmentBRDFTexture.isReady()) {
  44785. return false;
  44786. }
  44787. }
  44788. }
  44789. }
  44790. if (defines._areImageProcessingDirty) {
  44791. if (!this._imageProcessingConfiguration.isReady()) {
  44792. return false;
  44793. }
  44794. }
  44795. if (!engine.getCaps().standardDerivatives && !mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  44796. mesh.createNormals(true);
  44797. BABYLON.Tools.Warn("PBRMaterial: Normals have been created for the mesh: " + mesh.name);
  44798. }
  44799. var effect = this._prepareEffect(mesh, defines, this.onCompiled, this.onError, useInstances);
  44800. if (effect) {
  44801. scene.resetCachedMaterial();
  44802. subMesh.setEffect(effect, defines);
  44803. this.buildUniformLayout();
  44804. }
  44805. if (!subMesh.effect || !subMesh.effect.isReady()) {
  44806. return false;
  44807. }
  44808. defines._renderId = scene.getRenderId();
  44809. this._wasPreviouslyReady = true;
  44810. return true;
  44811. };
  44812. /**
  44813. * Specifies if the material uses metallic roughness workflow.
  44814. * @returns boolean specifiying if the material uses metallic roughness workflow.
  44815. */
  44816. PBRBaseMaterial.prototype.isMetallicWorkflow = function () {
  44817. if (this._metallic != null || this._roughness != null || this._metallicTexture) {
  44818. return true;
  44819. }
  44820. return false;
  44821. };
  44822. PBRBaseMaterial.prototype._prepareEffect = function (mesh, defines, onCompiled, onError, useInstances, useClipPlane) {
  44823. if (onCompiled === void 0) { onCompiled = null; }
  44824. if (onError === void 0) { onError = null; }
  44825. if (useInstances === void 0) { useInstances = null; }
  44826. if (useClipPlane === void 0) { useClipPlane = null; }
  44827. this._prepareDefines(mesh, defines, useInstances, useClipPlane);
  44828. if (!defines.isDirty) {
  44829. return null;
  44830. }
  44831. defines.markAsProcessed();
  44832. var scene = this.getScene();
  44833. var engine = scene.getEngine();
  44834. // Fallbacks
  44835. var fallbacks = new BABYLON.EffectFallbacks();
  44836. var fallbackRank = 0;
  44837. if (defines.USESPHERICALINVERTEX) {
  44838. fallbacks.addFallback(fallbackRank++, "USESPHERICALINVERTEX");
  44839. }
  44840. if (defines.FOG) {
  44841. fallbacks.addFallback(fallbackRank, "FOG");
  44842. }
  44843. if (defines.POINTSIZE) {
  44844. fallbacks.addFallback(fallbackRank, "POINTSIZE");
  44845. }
  44846. if (defines.LOGARITHMICDEPTH) {
  44847. fallbacks.addFallback(fallbackRank, "LOGARITHMICDEPTH");
  44848. }
  44849. if (defines.PARALLAX) {
  44850. fallbacks.addFallback(fallbackRank, "PARALLAX");
  44851. }
  44852. if (defines.PARALLAXOCCLUSION) {
  44853. fallbacks.addFallback(fallbackRank++, "PARALLAXOCCLUSION");
  44854. }
  44855. if (defines.ENVIRONMENTBRDF) {
  44856. fallbacks.addFallback(fallbackRank++, "ENVIRONMENTBRDF");
  44857. }
  44858. if (defines.TANGENT) {
  44859. fallbacks.addFallback(fallbackRank++, "TANGENT");
  44860. }
  44861. if (defines.BUMP) {
  44862. fallbacks.addFallback(fallbackRank++, "BUMP");
  44863. }
  44864. fallbackRank = BABYLON.MaterialHelper.HandleFallbacksForShadows(defines, fallbacks, this._maxSimultaneousLights, fallbackRank++);
  44865. if (defines.SPECULARTERM) {
  44866. fallbacks.addFallback(fallbackRank++, "SPECULARTERM");
  44867. }
  44868. if (defines.USESPHERICALFROMREFLECTIONMAP) {
  44869. fallbacks.addFallback(fallbackRank++, "USESPHERICALFROMREFLECTIONMAP");
  44870. }
  44871. if (defines.LIGHTMAP) {
  44872. fallbacks.addFallback(fallbackRank++, "LIGHTMAP");
  44873. }
  44874. if (defines.NORMAL) {
  44875. fallbacks.addFallback(fallbackRank++, "NORMAL");
  44876. }
  44877. if (defines.AMBIENT) {
  44878. fallbacks.addFallback(fallbackRank++, "AMBIENT");
  44879. }
  44880. if (defines.EMISSIVE) {
  44881. fallbacks.addFallback(fallbackRank++, "EMISSIVE");
  44882. }
  44883. if (defines.VERTEXCOLOR) {
  44884. fallbacks.addFallback(fallbackRank++, "VERTEXCOLOR");
  44885. }
  44886. if (defines.NUM_BONE_INFLUENCERS > 0) {
  44887. fallbacks.addCPUSkinningFallback(fallbackRank++, mesh);
  44888. }
  44889. if (defines.MORPHTARGETS) {
  44890. fallbacks.addFallback(fallbackRank++, "MORPHTARGETS");
  44891. }
  44892. //Attributes
  44893. var attribs = [BABYLON.VertexBuffer.PositionKind];
  44894. if (defines.NORMAL) {
  44895. attribs.push(BABYLON.VertexBuffer.NormalKind);
  44896. }
  44897. if (defines.TANGENT) {
  44898. attribs.push(BABYLON.VertexBuffer.TangentKind);
  44899. }
  44900. if (defines.UV1) {
  44901. attribs.push(BABYLON.VertexBuffer.UVKind);
  44902. }
  44903. if (defines.UV2) {
  44904. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  44905. }
  44906. if (defines.VERTEXCOLOR) {
  44907. attribs.push(BABYLON.VertexBuffer.ColorKind);
  44908. }
  44909. BABYLON.MaterialHelper.PrepareAttributesForBones(attribs, mesh, defines, fallbacks);
  44910. BABYLON.MaterialHelper.PrepareAttributesForInstances(attribs, defines);
  44911. BABYLON.MaterialHelper.PrepareAttributesForMorphTargets(attribs, mesh, defines);
  44912. var uniforms = ["world", "view", "viewProjection", "vEyePosition", "vLightsType", "vAmbientColor", "vAlbedoColor", "vReflectivityColor", "vEmissiveColor", "vReflectionColor",
  44913. "vFogInfos", "vFogColor", "pointSize",
  44914. "vAlbedoInfos", "vAmbientInfos", "vOpacityInfos", "vReflectionInfos", "vReflectionPosition", "vReflectionSize", "vEmissiveInfos", "vReflectivityInfos",
  44915. "vMicroSurfaceSamplerInfos", "vBumpInfos", "vLightmapInfos", "vRefractionInfos",
  44916. "mBones",
  44917. "vClipPlane", "albedoMatrix", "ambientMatrix", "opacityMatrix", "reflectionMatrix", "emissiveMatrix", "reflectivityMatrix", "normalMatrix", "microSurfaceSamplerMatrix", "bumpMatrix", "lightmapMatrix", "refractionMatrix",
  44918. "vLightingIntensity",
  44919. "logarithmicDepthConstant",
  44920. "vSphericalX", "vSphericalY", "vSphericalZ",
  44921. "vSphericalXX", "vSphericalYY", "vSphericalZZ",
  44922. "vSphericalXY", "vSphericalYZ", "vSphericalZX",
  44923. "vReflectionMicrosurfaceInfos", "vRefractionMicrosurfaceInfos",
  44924. "vTangentSpaceParams"
  44925. ];
  44926. var samplers = ["albedoSampler", "reflectivitySampler", "ambientSampler", "emissiveSampler",
  44927. "bumpSampler", "lightmapSampler", "opacitySampler",
  44928. "refractionSampler", "refractionSamplerLow", "refractionSamplerHigh",
  44929. "reflectionSampler", "reflectionSamplerLow", "reflectionSamplerHigh",
  44930. "microSurfaceSampler", "environmentBrdfSampler"];
  44931. var uniformBuffers = ["Material", "Scene"];
  44932. BABYLON.ImageProcessingConfiguration.PrepareUniforms(uniforms, defines);
  44933. BABYLON.ImageProcessingConfiguration.PrepareSamplers(samplers, defines);
  44934. BABYLON.MaterialHelper.PrepareUniformsAndSamplersList({
  44935. uniformsNames: uniforms,
  44936. uniformBuffersNames: uniformBuffers,
  44937. samplers: samplers,
  44938. defines: defines,
  44939. maxSimultaneousLights: this._maxSimultaneousLights
  44940. });
  44941. var join = defines.toString();
  44942. return engine.createEffect("pbr", {
  44943. attributes: attribs,
  44944. uniformsNames: uniforms,
  44945. uniformBuffersNames: uniformBuffers,
  44946. samplers: samplers,
  44947. defines: join,
  44948. fallbacks: fallbacks,
  44949. onCompiled: onCompiled,
  44950. onError: onError,
  44951. indexParameters: { maxSimultaneousLights: this._maxSimultaneousLights, maxSimultaneousMorphTargets: defines.NUM_MORPH_INFLUENCERS }
  44952. }, engine);
  44953. };
  44954. PBRBaseMaterial.prototype._prepareDefines = function (mesh, defines, useInstances, useClipPlane) {
  44955. if (useInstances === void 0) { useInstances = null; }
  44956. if (useClipPlane === void 0) { useClipPlane = null; }
  44957. var scene = this.getScene();
  44958. var engine = scene.getEngine();
  44959. // Lights
  44960. BABYLON.MaterialHelper.PrepareDefinesForLights(scene, mesh, defines, true, this._maxSimultaneousLights, this._disableLighting);
  44961. defines._needNormals = true;
  44962. // Textures
  44963. defines.METALLICWORKFLOW = this.isMetallicWorkflow();
  44964. if (defines._areTexturesDirty) {
  44965. defines._needUVs = false;
  44966. if (scene.texturesEnabled) {
  44967. if (scene.getEngine().getCaps().textureLOD) {
  44968. defines.LODBASEDMICROSFURACE = true;
  44969. }
  44970. if (this._albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  44971. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._albedoTexture, defines, "ALBEDO");
  44972. }
  44973. else {
  44974. defines.ALBEDO = false;
  44975. }
  44976. if (this._ambientTexture && BABYLON.StandardMaterial.AmbientTextureEnabled) {
  44977. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._ambientTexture, defines, "AMBIENT");
  44978. defines.AMBIENTINGRAYSCALE = this._useAmbientInGrayScale;
  44979. }
  44980. else {
  44981. defines.AMBIENT = false;
  44982. }
  44983. if (this._opacityTexture && BABYLON.StandardMaterial.OpacityTextureEnabled) {
  44984. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._opacityTexture, defines, "OPACITY");
  44985. defines.OPACITYRGB = this._opacityTexture.getAlphaFromRGB;
  44986. }
  44987. else {
  44988. defines.OPACITY = false;
  44989. }
  44990. var reflectionTexture = this._getReflectionTexture();
  44991. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  44992. defines.REFLECTION = true;
  44993. defines.GAMMAREFLECTION = reflectionTexture.gammaSpace;
  44994. defines.REFLECTIONMAP_OPPOSITEZ = this.getScene().useRightHandedSystem ? !reflectionTexture.invertZ : reflectionTexture.invertZ;
  44995. defines.LODINREFLECTIONALPHA = reflectionTexture.lodLevelInAlpha;
  44996. if (reflectionTexture.coordinatesMode === BABYLON.Texture.INVCUBIC_MODE) {
  44997. defines.INVERTCUBICMAP = true;
  44998. }
  44999. defines.REFLECTIONMAP_3D = reflectionTexture.isCube;
  45000. switch (reflectionTexture.coordinatesMode) {
  45001. case BABYLON.Texture.CUBIC_MODE:
  45002. case BABYLON.Texture.INVCUBIC_MODE:
  45003. defines.REFLECTIONMAP_CUBIC = true;
  45004. defines.USE_LOCAL_REFLECTIONMAP_CUBIC = reflectionTexture.boundingBoxSize ? true : false;
  45005. break;
  45006. case BABYLON.Texture.EXPLICIT_MODE:
  45007. defines.REFLECTIONMAP_EXPLICIT = true;
  45008. break;
  45009. case BABYLON.Texture.PLANAR_MODE:
  45010. defines.REFLECTIONMAP_PLANAR = true;
  45011. break;
  45012. case BABYLON.Texture.PROJECTION_MODE:
  45013. defines.REFLECTIONMAP_PROJECTION = true;
  45014. break;
  45015. case BABYLON.Texture.SKYBOX_MODE:
  45016. defines.REFLECTIONMAP_SKYBOX = true;
  45017. break;
  45018. case BABYLON.Texture.SPHERICAL_MODE:
  45019. defines.REFLECTIONMAP_SPHERICAL = true;
  45020. break;
  45021. case BABYLON.Texture.EQUIRECTANGULAR_MODE:
  45022. defines.REFLECTIONMAP_EQUIRECTANGULAR = true;
  45023. break;
  45024. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MODE:
  45025. defines.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = true;
  45026. break;
  45027. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE:
  45028. defines.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = true;
  45029. break;
  45030. }
  45031. if (reflectionTexture.coordinatesMode !== BABYLON.Texture.SKYBOX_MODE) {
  45032. if (reflectionTexture.sphericalPolynomial) {
  45033. defines.USESPHERICALFROMREFLECTIONMAP = true;
  45034. if (this._forceIrradianceInFragment || scene.getEngine().getCaps().maxVaryingVectors <= 8) {
  45035. defines.USESPHERICALINVERTEX = false;
  45036. }
  45037. else {
  45038. defines.USESPHERICALINVERTEX = true;
  45039. }
  45040. }
  45041. }
  45042. }
  45043. else {
  45044. defines.REFLECTION = false;
  45045. defines.REFLECTIONMAP_3D = false;
  45046. defines.REFLECTIONMAP_SPHERICAL = false;
  45047. defines.REFLECTIONMAP_PLANAR = false;
  45048. defines.REFLECTIONMAP_CUBIC = false;
  45049. defines.USE_LOCAL_REFLECTIONMAP_CUBIC = false;
  45050. defines.REFLECTIONMAP_PROJECTION = false;
  45051. defines.REFLECTIONMAP_SKYBOX = false;
  45052. defines.REFLECTIONMAP_EXPLICIT = false;
  45053. defines.REFLECTIONMAP_EQUIRECTANGULAR = false;
  45054. defines.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  45055. defines.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false;
  45056. defines.INVERTCUBICMAP = false;
  45057. defines.USESPHERICALFROMREFLECTIONMAP = false;
  45058. defines.USESPHERICALINVERTEX = false;
  45059. defines.REFLECTIONMAP_OPPOSITEZ = false;
  45060. defines.LODINREFLECTIONALPHA = false;
  45061. defines.GAMMAREFLECTION = false;
  45062. }
  45063. if (this._lightmapTexture && BABYLON.StandardMaterial.LightmapTextureEnabled) {
  45064. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._lightmapTexture, defines, "LIGHTMAP");
  45065. defines.USELIGHTMAPASSHADOWMAP = this._useLightmapAsShadowmap;
  45066. defines.GAMMALIGHTMAP = this._lightmapTexture.gammaSpace;
  45067. }
  45068. else {
  45069. defines.LIGHTMAP = false;
  45070. }
  45071. if (this._emissiveTexture && BABYLON.StandardMaterial.EmissiveTextureEnabled) {
  45072. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._emissiveTexture, defines, "EMISSIVE");
  45073. }
  45074. else {
  45075. defines.EMISSIVE = false;
  45076. }
  45077. if (BABYLON.StandardMaterial.SpecularTextureEnabled) {
  45078. if (this._metallicTexture) {
  45079. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._metallicTexture, defines, "REFLECTIVITY");
  45080. defines.ROUGHNESSSTOREINMETALMAPALPHA = this._useRoughnessFromMetallicTextureAlpha;
  45081. defines.ROUGHNESSSTOREINMETALMAPGREEN = !this._useRoughnessFromMetallicTextureAlpha && this._useRoughnessFromMetallicTextureGreen;
  45082. defines.METALLNESSSTOREINMETALMAPBLUE = this._useMetallnessFromMetallicTextureBlue;
  45083. defines.AOSTOREINMETALMAPRED = this._useAmbientOcclusionFromMetallicTextureRed;
  45084. }
  45085. else if (this._reflectivityTexture) {
  45086. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._reflectivityTexture, defines, "REFLECTIVITY");
  45087. defines.MICROSURFACEFROMREFLECTIVITYMAP = this._useMicroSurfaceFromReflectivityMapAlpha;
  45088. defines.MICROSURFACEAUTOMATIC = this._useAutoMicroSurfaceFromReflectivityMap;
  45089. }
  45090. else {
  45091. defines.REFLECTIVITY = false;
  45092. }
  45093. if (this._microSurfaceTexture) {
  45094. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._microSurfaceTexture, defines, "MICROSURFACEMAP");
  45095. }
  45096. else {
  45097. defines.MICROSURFACEMAP = false;
  45098. }
  45099. }
  45100. else {
  45101. defines.REFLECTIVITY = false;
  45102. defines.MICROSURFACEMAP = false;
  45103. }
  45104. if (scene.getEngine().getCaps().standardDerivatives && this._bumpTexture && BABYLON.StandardMaterial.BumpTextureEnabled && !this._disableBumpMap) {
  45105. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._bumpTexture, defines, "BUMP");
  45106. if (this._useParallax && this._albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  45107. defines.PARALLAX = true;
  45108. defines.PARALLAXOCCLUSION = !!this._useParallaxOcclusion;
  45109. }
  45110. else {
  45111. defines.PARALLAX = false;
  45112. }
  45113. defines.OBJECTSPACE_NORMALMAP = this._useObjectSpaceNormalMap;
  45114. }
  45115. else {
  45116. defines.BUMP = false;
  45117. }
  45118. var refractionTexture = this._getRefractionTexture();
  45119. if (refractionTexture && BABYLON.StandardMaterial.RefractionTextureEnabled) {
  45120. defines.REFRACTION = true;
  45121. defines.REFRACTIONMAP_3D = refractionTexture.isCube;
  45122. defines.GAMMAREFRACTION = refractionTexture.gammaSpace;
  45123. defines.REFRACTIONMAP_OPPOSITEZ = refractionTexture.invertZ;
  45124. defines.LODINREFRACTIONALPHA = refractionTexture.lodLevelInAlpha;
  45125. if (this._linkRefractionWithTransparency) {
  45126. defines.LINKREFRACTIONTOTRANSPARENCY = true;
  45127. }
  45128. }
  45129. else {
  45130. defines.REFRACTION = false;
  45131. }
  45132. if (this._environmentBRDFTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  45133. defines.ENVIRONMENTBRDF = true;
  45134. }
  45135. else {
  45136. defines.ENVIRONMENTBRDF = false;
  45137. }
  45138. if (this._shouldUseAlphaFromAlbedoTexture()) {
  45139. defines.ALPHAFROMALBEDO = true;
  45140. }
  45141. else {
  45142. defines.ALPHAFROMALBEDO = false;
  45143. }
  45144. }
  45145. defines.SPECULAROVERALPHA = this._useSpecularOverAlpha;
  45146. defines.USEPHYSICALLIGHTFALLOFF = this._usePhysicalLightFalloff;
  45147. defines.RADIANCEOVERALPHA = this._useRadianceOverAlpha;
  45148. if (!this.backFaceCulling && this._twoSidedLighting) {
  45149. defines.TWOSIDEDLIGHTING = true;
  45150. }
  45151. else {
  45152. defines.TWOSIDEDLIGHTING = false;
  45153. }
  45154. defines.ALPHATESTVALUE = "" + this._alphaCutOff + (this._alphaCutOff % 1 === 0 ? "." : "");
  45155. defines.PREMULTIPLYALPHA = (this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED || this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED_PORTERDUFF);
  45156. defines.ALPHABLEND = this.needAlphaBlendingForMesh(mesh);
  45157. defines.ALPHAFRESNEL = this._useAlphaFresnel || this._useLinearAlphaFresnel;
  45158. defines.LINEARALPHAFRESNEL = this._useLinearAlphaFresnel;
  45159. defines.SPECULARAA = scene.getEngine().getCaps().standardDerivatives && this._enableSpecularAntiAliasing;
  45160. }
  45161. if (defines._areImageProcessingDirty) {
  45162. this._imageProcessingConfiguration.prepareDefines(defines);
  45163. }
  45164. defines.FORCENORMALFORWARD = this._forceNormalForward;
  45165. defines.RADIANCEOCCLUSION = this._useRadianceOcclusion;
  45166. defines.HORIZONOCCLUSION = this._useHorizonOcclusion;
  45167. // Misc.
  45168. if (defines._areMiscDirty) {
  45169. BABYLON.MaterialHelper.PrepareDefinesForMisc(mesh, scene, this._useLogarithmicDepth, this.pointsCloud, this.fogEnabled, this._shouldTurnAlphaTestOn(mesh) || this._forceAlphaTest, defines);
  45170. defines.UNLIT = this._unlit || ((this.pointsCloud || this.wireframe) && !mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind));
  45171. }
  45172. // Values that need to be evaluated on every frame
  45173. BABYLON.MaterialHelper.PrepareDefinesForFrameBoundValues(scene, engine, defines, useInstances ? true : false, useClipPlane);
  45174. // Attribs
  45175. BABYLON.MaterialHelper.PrepareDefinesForAttributes(mesh, defines, true, true, true, this._transparencyMode !== BABYLON.PBRMaterial.PBRMATERIAL_OPAQUE);
  45176. };
  45177. /**
  45178. * Force shader compilation
  45179. */
  45180. PBRBaseMaterial.prototype.forceCompilation = function (mesh, onCompiled, options) {
  45181. var _this = this;
  45182. var localOptions = __assign({ clipPlane: false }, options);
  45183. var defines = new PBRMaterialDefines();
  45184. var effect = this._prepareEffect(mesh, defines, undefined, undefined, undefined, localOptions.clipPlane);
  45185. if (effect.isReady()) {
  45186. if (onCompiled) {
  45187. onCompiled(this);
  45188. }
  45189. }
  45190. else {
  45191. effect.onCompileObservable.add(function () {
  45192. if (onCompiled) {
  45193. onCompiled(_this);
  45194. }
  45195. });
  45196. }
  45197. };
  45198. /**
  45199. * Initializes the uniform buffer layout for the shader.
  45200. */
  45201. PBRBaseMaterial.prototype.buildUniformLayout = function () {
  45202. // Order is important !
  45203. this._uniformBuffer.addUniform("vAlbedoInfos", 2);
  45204. this._uniformBuffer.addUniform("vAmbientInfos", 3);
  45205. this._uniformBuffer.addUniform("vOpacityInfos", 2);
  45206. this._uniformBuffer.addUniform("vEmissiveInfos", 2);
  45207. this._uniformBuffer.addUniform("vLightmapInfos", 2);
  45208. this._uniformBuffer.addUniform("vReflectivityInfos", 3);
  45209. this._uniformBuffer.addUniform("vMicroSurfaceSamplerInfos", 2);
  45210. this._uniformBuffer.addUniform("vRefractionInfos", 4);
  45211. this._uniformBuffer.addUniform("vReflectionInfos", 2);
  45212. this._uniformBuffer.addUniform("vReflectionPosition", 3);
  45213. this._uniformBuffer.addUniform("vReflectionSize", 3);
  45214. this._uniformBuffer.addUniform("vBumpInfos", 3);
  45215. this._uniformBuffer.addUniform("albedoMatrix", 16);
  45216. this._uniformBuffer.addUniform("ambientMatrix", 16);
  45217. this._uniformBuffer.addUniform("opacityMatrix", 16);
  45218. this._uniformBuffer.addUniform("emissiveMatrix", 16);
  45219. this._uniformBuffer.addUniform("lightmapMatrix", 16);
  45220. this._uniformBuffer.addUniform("reflectivityMatrix", 16);
  45221. this._uniformBuffer.addUniform("microSurfaceSamplerMatrix", 16);
  45222. this._uniformBuffer.addUniform("bumpMatrix", 16);
  45223. this._uniformBuffer.addUniform("vTangentSpaceParams", 2);
  45224. this._uniformBuffer.addUniform("refractionMatrix", 16);
  45225. this._uniformBuffer.addUniform("reflectionMatrix", 16);
  45226. this._uniformBuffer.addUniform("vReflectionColor", 3);
  45227. this._uniformBuffer.addUniform("vAlbedoColor", 4);
  45228. this._uniformBuffer.addUniform("vLightingIntensity", 4);
  45229. this._uniformBuffer.addUniform("vRefractionMicrosurfaceInfos", 3);
  45230. this._uniformBuffer.addUniform("vReflectionMicrosurfaceInfos", 3);
  45231. this._uniformBuffer.addUniform("vReflectivityColor", 4);
  45232. this._uniformBuffer.addUniform("vEmissiveColor", 3);
  45233. this._uniformBuffer.addUniform("pointSize", 1);
  45234. this._uniformBuffer.create();
  45235. };
  45236. /**
  45237. * Unbinds the textures.
  45238. */
  45239. PBRBaseMaterial.prototype.unbind = function () {
  45240. if (this._reflectionTexture && this._reflectionTexture.isRenderTarget) {
  45241. this._uniformBuffer.setTexture("reflectionSampler", null);
  45242. }
  45243. if (this._refractionTexture && this._refractionTexture.isRenderTarget) {
  45244. this._uniformBuffer.setTexture("refractionSampler", null);
  45245. }
  45246. _super.prototype.unbind.call(this);
  45247. };
  45248. /**
  45249. * Binds the submesh data.
  45250. * @param world - The world matrix.
  45251. * @param mesh - The BJS mesh.
  45252. * @param subMesh - A submesh of the BJS mesh.
  45253. */
  45254. PBRBaseMaterial.prototype.bindForSubMesh = function (world, mesh, subMesh) {
  45255. var scene = this.getScene();
  45256. var defines = subMesh._materialDefines;
  45257. if (!defines) {
  45258. return;
  45259. }
  45260. var effect = subMesh.effect;
  45261. if (!effect) {
  45262. return;
  45263. }
  45264. this._activeEffect = effect;
  45265. // Matrices
  45266. this.bindOnlyWorldMatrix(world);
  45267. // Normal Matrix
  45268. if (defines.OBJECTSPACE_NORMALMAP) {
  45269. world.toNormalMatrix(this._normalMatrix);
  45270. this.bindOnlyNormalMatrix(this._normalMatrix);
  45271. }
  45272. var mustRebind = this._mustRebind(scene, effect, mesh.visibility);
  45273. // Bones
  45274. BABYLON.MaterialHelper.BindBonesParameters(mesh, this._activeEffect);
  45275. var reflectionTexture = null;
  45276. if (mustRebind) {
  45277. this._uniformBuffer.bindToEffect(effect, "Material");
  45278. this.bindViewProjection(effect);
  45279. reflectionTexture = this._getReflectionTexture();
  45280. var refractionTexture = this._getRefractionTexture();
  45281. if (!this._uniformBuffer.useUbo || !this.isFrozen || !this._uniformBuffer.isSync) {
  45282. // Texture uniforms
  45283. if (scene.texturesEnabled) {
  45284. if (this._albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  45285. this._uniformBuffer.updateFloat2("vAlbedoInfos", this._albedoTexture.coordinatesIndex, this._albedoTexture.level);
  45286. BABYLON.MaterialHelper.BindTextureMatrix(this._albedoTexture, this._uniformBuffer, "albedo");
  45287. }
  45288. if (this._ambientTexture && BABYLON.StandardMaterial.AmbientTextureEnabled) {
  45289. this._uniformBuffer.updateFloat3("vAmbientInfos", this._ambientTexture.coordinatesIndex, this._ambientTexture.level, this._ambientTextureStrength);
  45290. BABYLON.MaterialHelper.BindTextureMatrix(this._ambientTexture, this._uniformBuffer, "ambient");
  45291. }
  45292. if (this._opacityTexture && BABYLON.StandardMaterial.OpacityTextureEnabled) {
  45293. this._uniformBuffer.updateFloat2("vOpacityInfos", this._opacityTexture.coordinatesIndex, this._opacityTexture.level);
  45294. BABYLON.MaterialHelper.BindTextureMatrix(this._opacityTexture, this._uniformBuffer, "opacity");
  45295. }
  45296. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  45297. this._uniformBuffer.updateMatrix("reflectionMatrix", reflectionTexture.getReflectionTextureMatrix());
  45298. this._uniformBuffer.updateFloat2("vReflectionInfos", reflectionTexture.level, 0);
  45299. if (reflectionTexture.boundingBoxSize) {
  45300. var cubeTexture = reflectionTexture;
  45301. this._uniformBuffer.updateVector3("vReflectionPosition", cubeTexture.boundingBoxPosition);
  45302. this._uniformBuffer.updateVector3("vReflectionSize", cubeTexture.boundingBoxSize);
  45303. }
  45304. var polynomials = reflectionTexture.sphericalPolynomial;
  45305. if (defines.USESPHERICALFROMREFLECTIONMAP && polynomials) {
  45306. this._activeEffect.setFloat3("vSphericalX", polynomials.x.x, polynomials.x.y, polynomials.x.z);
  45307. this._activeEffect.setFloat3("vSphericalY", polynomials.y.x, polynomials.y.y, polynomials.y.z);
  45308. this._activeEffect.setFloat3("vSphericalZ", polynomials.z.x, polynomials.z.y, polynomials.z.z);
  45309. this._activeEffect.setFloat3("vSphericalXX_ZZ", polynomials.xx.x - polynomials.zz.x, polynomials.xx.y - polynomials.zz.y, polynomials.xx.z - polynomials.zz.z);
  45310. this._activeEffect.setFloat3("vSphericalYY_ZZ", polynomials.yy.x - polynomials.zz.x, polynomials.yy.y - polynomials.zz.y, polynomials.yy.z - polynomials.zz.z);
  45311. this._activeEffect.setFloat3("vSphericalZZ", polynomials.zz.x, polynomials.zz.y, polynomials.zz.z);
  45312. this._activeEffect.setFloat3("vSphericalXY", polynomials.xy.x, polynomials.xy.y, polynomials.xy.z);
  45313. this._activeEffect.setFloat3("vSphericalYZ", polynomials.yz.x, polynomials.yz.y, polynomials.yz.z);
  45314. this._activeEffect.setFloat3("vSphericalZX", polynomials.zx.x, polynomials.zx.y, polynomials.zx.z);
  45315. }
  45316. this._uniformBuffer.updateFloat3("vReflectionMicrosurfaceInfos", reflectionTexture.getSize().width, reflectionTexture.lodGenerationScale, reflectionTexture.lodGenerationOffset);
  45317. }
  45318. if (this._emissiveTexture && BABYLON.StandardMaterial.EmissiveTextureEnabled) {
  45319. this._uniformBuffer.updateFloat2("vEmissiveInfos", this._emissiveTexture.coordinatesIndex, this._emissiveTexture.level);
  45320. BABYLON.MaterialHelper.BindTextureMatrix(this._emissiveTexture, this._uniformBuffer, "emissive");
  45321. }
  45322. if (this._lightmapTexture && BABYLON.StandardMaterial.LightmapTextureEnabled) {
  45323. this._uniformBuffer.updateFloat2("vLightmapInfos", this._lightmapTexture.coordinatesIndex, this._lightmapTexture.level);
  45324. BABYLON.MaterialHelper.BindTextureMatrix(this._lightmapTexture, this._uniformBuffer, "lightmap");
  45325. }
  45326. if (BABYLON.StandardMaterial.SpecularTextureEnabled) {
  45327. if (this._metallicTexture) {
  45328. this._uniformBuffer.updateFloat3("vReflectivityInfos", this._metallicTexture.coordinatesIndex, this._metallicTexture.level, this._ambientTextureStrength);
  45329. BABYLON.MaterialHelper.BindTextureMatrix(this._metallicTexture, this._uniformBuffer, "reflectivity");
  45330. }
  45331. else if (this._reflectivityTexture) {
  45332. this._uniformBuffer.updateFloat3("vReflectivityInfos", this._reflectivityTexture.coordinatesIndex, this._reflectivityTexture.level, 1.0);
  45333. BABYLON.MaterialHelper.BindTextureMatrix(this._reflectivityTexture, this._uniformBuffer, "reflectivity");
  45334. }
  45335. if (this._microSurfaceTexture) {
  45336. this._uniformBuffer.updateFloat2("vMicroSurfaceSamplerInfos", this._microSurfaceTexture.coordinatesIndex, this._microSurfaceTexture.level);
  45337. BABYLON.MaterialHelper.BindTextureMatrix(this._microSurfaceTexture, this._uniformBuffer, "microSurfaceSampler");
  45338. }
  45339. }
  45340. if (this._bumpTexture && scene.getEngine().getCaps().standardDerivatives && BABYLON.StandardMaterial.BumpTextureEnabled && !this._disableBumpMap) {
  45341. this._uniformBuffer.updateFloat3("vBumpInfos", this._bumpTexture.coordinatesIndex, this._bumpTexture.level, this._parallaxScaleBias);
  45342. BABYLON.MaterialHelper.BindTextureMatrix(this._bumpTexture, this._uniformBuffer, "bump");
  45343. if (scene._mirroredCameraPosition) {
  45344. this._uniformBuffer.updateFloat2("vTangentSpaceParams", this._invertNormalMapX ? 1.0 : -1.0, this._invertNormalMapY ? 1.0 : -1.0);
  45345. }
  45346. else {
  45347. this._uniformBuffer.updateFloat2("vTangentSpaceParams", this._invertNormalMapX ? -1.0 : 1.0, this._invertNormalMapY ? -1.0 : 1.0);
  45348. }
  45349. }
  45350. if (refractionTexture && BABYLON.StandardMaterial.RefractionTextureEnabled) {
  45351. this._uniformBuffer.updateMatrix("refractionMatrix", refractionTexture.getReflectionTextureMatrix());
  45352. var depth = 1.0;
  45353. if (!refractionTexture.isCube) {
  45354. if (refractionTexture.depth) {
  45355. depth = refractionTexture.depth;
  45356. }
  45357. }
  45358. this._uniformBuffer.updateFloat4("vRefractionInfos", refractionTexture.level, this._indexOfRefraction, depth, this._invertRefractionY ? -1 : 1);
  45359. this._uniformBuffer.updateFloat3("vRefractionMicrosurfaceInfos", refractionTexture.getSize().width, refractionTexture.lodGenerationScale, refractionTexture.lodGenerationOffset);
  45360. }
  45361. }
  45362. // Point size
  45363. if (this.pointsCloud) {
  45364. this._uniformBuffer.updateFloat("pointSize", this.pointSize);
  45365. }
  45366. // Colors
  45367. if (defines.METALLICWORKFLOW) {
  45368. BABYLON.PBRMaterial._scaledReflectivity.r = (this._metallic === undefined || this._metallic === null) ? 1 : this._metallic;
  45369. BABYLON.PBRMaterial._scaledReflectivity.g = (this._roughness === undefined || this._roughness === null) ? 1 : this._roughness;
  45370. this._uniformBuffer.updateColor4("vReflectivityColor", BABYLON.PBRMaterial._scaledReflectivity, 0);
  45371. }
  45372. else {
  45373. this._uniformBuffer.updateColor4("vReflectivityColor", this._reflectivityColor, this._microSurface);
  45374. }
  45375. this._uniformBuffer.updateColor3("vEmissiveColor", this._emissiveColor);
  45376. this._uniformBuffer.updateColor3("vReflectionColor", this._reflectionColor);
  45377. this._uniformBuffer.updateColor4("vAlbedoColor", this._albedoColor, this.alpha * mesh.visibility);
  45378. // Misc
  45379. this._lightingInfos.x = this._directIntensity;
  45380. this._lightingInfos.y = this._emissiveIntensity;
  45381. this._lightingInfos.z = this._environmentIntensity;
  45382. this._lightingInfos.w = this._specularIntensity;
  45383. this._uniformBuffer.updateVector4("vLightingIntensity", this._lightingInfos);
  45384. }
  45385. // Textures
  45386. if (scene.texturesEnabled) {
  45387. if (this._albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  45388. this._uniformBuffer.setTexture("albedoSampler", this._albedoTexture);
  45389. }
  45390. if (this._ambientTexture && BABYLON.StandardMaterial.AmbientTextureEnabled) {
  45391. this._uniformBuffer.setTexture("ambientSampler", this._ambientTexture);
  45392. }
  45393. if (this._opacityTexture && BABYLON.StandardMaterial.OpacityTextureEnabled) {
  45394. this._uniformBuffer.setTexture("opacitySampler", this._opacityTexture);
  45395. }
  45396. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  45397. if (defines.LODBASEDMICROSFURACE) {
  45398. this._uniformBuffer.setTexture("reflectionSampler", reflectionTexture);
  45399. }
  45400. else {
  45401. this._uniformBuffer.setTexture("reflectionSampler", reflectionTexture._lodTextureMid || reflectionTexture);
  45402. this._uniformBuffer.setTexture("reflectionSamplerLow", reflectionTexture._lodTextureLow || reflectionTexture);
  45403. this._uniformBuffer.setTexture("reflectionSamplerHigh", reflectionTexture._lodTextureHigh || reflectionTexture);
  45404. }
  45405. }
  45406. if (defines.ENVIRONMENTBRDF) {
  45407. this._uniformBuffer.setTexture("environmentBrdfSampler", this._environmentBRDFTexture);
  45408. }
  45409. if (refractionTexture && BABYLON.StandardMaterial.RefractionTextureEnabled) {
  45410. if (defines.LODBASEDMICROSFURACE) {
  45411. this._uniformBuffer.setTexture("refractionSampler", refractionTexture);
  45412. }
  45413. else {
  45414. this._uniformBuffer.setTexture("refractionSampler", refractionTexture._lodTextureMid || refractionTexture);
  45415. this._uniformBuffer.setTexture("refractionSamplerLow", refractionTexture._lodTextureLow || refractionTexture);
  45416. this._uniformBuffer.setTexture("refractionSamplerHigh", refractionTexture._lodTextureHigh || refractionTexture);
  45417. }
  45418. }
  45419. if (this._emissiveTexture && BABYLON.StandardMaterial.EmissiveTextureEnabled) {
  45420. this._uniformBuffer.setTexture("emissiveSampler", this._emissiveTexture);
  45421. }
  45422. if (this._lightmapTexture && BABYLON.StandardMaterial.LightmapTextureEnabled) {
  45423. this._uniformBuffer.setTexture("lightmapSampler", this._lightmapTexture);
  45424. }
  45425. if (BABYLON.StandardMaterial.SpecularTextureEnabled) {
  45426. if (this._metallicTexture) {
  45427. this._uniformBuffer.setTexture("reflectivitySampler", this._metallicTexture);
  45428. }
  45429. else if (this._reflectivityTexture) {
  45430. this._uniformBuffer.setTexture("reflectivitySampler", this._reflectivityTexture);
  45431. }
  45432. if (this._microSurfaceTexture) {
  45433. this._uniformBuffer.setTexture("microSurfaceSampler", this._microSurfaceTexture);
  45434. }
  45435. }
  45436. if (this._bumpTexture && scene.getEngine().getCaps().standardDerivatives && BABYLON.StandardMaterial.BumpTextureEnabled && !this._disableBumpMap) {
  45437. this._uniformBuffer.setTexture("bumpSampler", this._bumpTexture);
  45438. }
  45439. }
  45440. // Clip plane
  45441. BABYLON.MaterialHelper.BindClipPlane(this._activeEffect, scene);
  45442. // Colors
  45443. scene.ambientColor.multiplyToRef(this._ambientColor, this._globalAmbientColor);
  45444. var eyePosition = scene._forcedViewPosition ? scene._forcedViewPosition : (scene._mirroredCameraPosition ? scene._mirroredCameraPosition : scene.activeCamera.globalPosition);
  45445. var invertNormal = (scene.useRightHandedSystem === (scene._mirroredCameraPosition != null));
  45446. effect.setFloat4("vEyePosition", eyePosition.x, eyePosition.y, eyePosition.z, invertNormal ? -1 : 1);
  45447. effect.setColor3("vAmbientColor", this._globalAmbientColor);
  45448. }
  45449. if (mustRebind || !this.isFrozen) {
  45450. // Lights
  45451. if (scene.lightsEnabled && !this._disableLighting) {
  45452. BABYLON.MaterialHelper.BindLights(scene, mesh, this._activeEffect, defines, this._maxSimultaneousLights, this._usePhysicalLightFalloff);
  45453. }
  45454. // View
  45455. if (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE || reflectionTexture) {
  45456. this.bindView(effect);
  45457. }
  45458. // Fog
  45459. BABYLON.MaterialHelper.BindFogParameters(scene, mesh, this._activeEffect);
  45460. // Morph targets
  45461. if (defines.NUM_MORPH_INFLUENCERS) {
  45462. BABYLON.MaterialHelper.BindMorphTargetParameters(mesh, this._activeEffect);
  45463. }
  45464. // image processing
  45465. this._imageProcessingConfiguration.bind(this._activeEffect);
  45466. // Log. depth
  45467. BABYLON.MaterialHelper.BindLogDepth(defines, this._activeEffect, scene);
  45468. }
  45469. this._uniformBuffer.update();
  45470. this._afterBind(mesh);
  45471. };
  45472. /**
  45473. * Returns the animatable textures.
  45474. * @returns - Array of animatable textures.
  45475. */
  45476. PBRBaseMaterial.prototype.getAnimatables = function () {
  45477. var results = [];
  45478. if (this._albedoTexture && this._albedoTexture.animations && this._albedoTexture.animations.length > 0) {
  45479. results.push(this._albedoTexture);
  45480. }
  45481. if (this._ambientTexture && this._ambientTexture.animations && this._ambientTexture.animations.length > 0) {
  45482. results.push(this._ambientTexture);
  45483. }
  45484. if (this._opacityTexture && this._opacityTexture.animations && this._opacityTexture.animations.length > 0) {
  45485. results.push(this._opacityTexture);
  45486. }
  45487. if (this._reflectionTexture && this._reflectionTexture.animations && this._reflectionTexture.animations.length > 0) {
  45488. results.push(this._reflectionTexture);
  45489. }
  45490. if (this._emissiveTexture && this._emissiveTexture.animations && this._emissiveTexture.animations.length > 0) {
  45491. results.push(this._emissiveTexture);
  45492. }
  45493. if (this._metallicTexture && this._metallicTexture.animations && this._metallicTexture.animations.length > 0) {
  45494. results.push(this._metallicTexture);
  45495. }
  45496. else if (this._reflectivityTexture && this._reflectivityTexture.animations && this._reflectivityTexture.animations.length > 0) {
  45497. results.push(this._reflectivityTexture);
  45498. }
  45499. if (this._bumpTexture && this._bumpTexture.animations && this._bumpTexture.animations.length > 0) {
  45500. results.push(this._bumpTexture);
  45501. }
  45502. if (this._lightmapTexture && this._lightmapTexture.animations && this._lightmapTexture.animations.length > 0) {
  45503. results.push(this._lightmapTexture);
  45504. }
  45505. if (this._refractionTexture && this._refractionTexture.animations && this._refractionTexture.animations.length > 0) {
  45506. results.push(this._refractionTexture);
  45507. }
  45508. return results;
  45509. };
  45510. /**
  45511. * Returns the texture used for reflections.
  45512. * @returns - Reflection texture if present. Otherwise, returns the environment texture.
  45513. */
  45514. PBRBaseMaterial.prototype._getReflectionTexture = function () {
  45515. if (this._reflectionTexture) {
  45516. return this._reflectionTexture;
  45517. }
  45518. return this.getScene().environmentTexture;
  45519. };
  45520. /**
  45521. * Returns the texture used for refraction or null if none is used.
  45522. * @returns - Refection texture if present. If no refraction texture and refraction
  45523. * is linked with transparency, returns environment texture. Otherwise, returns null.
  45524. */
  45525. PBRBaseMaterial.prototype._getRefractionTexture = function () {
  45526. if (this._refractionTexture) {
  45527. return this._refractionTexture;
  45528. }
  45529. if (this._linkRefractionWithTransparency) {
  45530. return this.getScene().environmentTexture;
  45531. }
  45532. return null;
  45533. };
  45534. /**
  45535. * Disposes the resources of the material.
  45536. * @param forceDisposeEffect - Forces the disposal of effects.
  45537. * @param forceDisposeTextures - Forces the disposal of all textures.
  45538. */
  45539. PBRBaseMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  45540. if (forceDisposeTextures) {
  45541. if (this._albedoTexture) {
  45542. this._albedoTexture.dispose();
  45543. }
  45544. if (this._ambientTexture) {
  45545. this._ambientTexture.dispose();
  45546. }
  45547. if (this._opacityTexture) {
  45548. this._opacityTexture.dispose();
  45549. }
  45550. if (this._reflectionTexture) {
  45551. this._reflectionTexture.dispose();
  45552. }
  45553. if (this._environmentBRDFTexture && this.getScene()._environmentBRDFTexture !== this._environmentBRDFTexture) {
  45554. this._environmentBRDFTexture.dispose();
  45555. }
  45556. if (this._emissiveTexture) {
  45557. this._emissiveTexture.dispose();
  45558. }
  45559. if (this._metallicTexture) {
  45560. this._metallicTexture.dispose();
  45561. }
  45562. if (this._reflectivityTexture) {
  45563. this._reflectivityTexture.dispose();
  45564. }
  45565. if (this._bumpTexture) {
  45566. this._bumpTexture.dispose();
  45567. }
  45568. if (this._lightmapTexture) {
  45569. this._lightmapTexture.dispose();
  45570. }
  45571. if (this._refractionTexture) {
  45572. this._refractionTexture.dispose();
  45573. }
  45574. }
  45575. this._renderTargets.dispose();
  45576. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  45577. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  45578. }
  45579. _super.prototype.dispose.call(this, forceDisposeEffect, forceDisposeTextures);
  45580. };
  45581. /**
  45582. * Stores the reflectivity values based on metallic roughness workflow.
  45583. */
  45584. PBRBaseMaterial._scaledReflectivity = new BABYLON.Color3();
  45585. __decorate([
  45586. BABYLON.serializeAsImageProcessingConfiguration()
  45587. ], PBRBaseMaterial.prototype, "_imageProcessingConfiguration", void 0);
  45588. __decorate([
  45589. BABYLON.serialize()
  45590. ], PBRBaseMaterial.prototype, "useLogarithmicDepth", null);
  45591. __decorate([
  45592. BABYLON.serialize()
  45593. ], PBRBaseMaterial.prototype, "transparencyMode", null);
  45594. return PBRBaseMaterial;
  45595. }(BABYLON.PushMaterial));
  45596. BABYLON.PBRBaseMaterial = PBRBaseMaterial;
  45597. })(BABYLON || (BABYLON = {}));
  45598. //# sourceMappingURL=babylon.pbrBaseMaterial.js.map
  45599. var BABYLON;
  45600. (function (BABYLON) {
  45601. /**
  45602. * The Physically based simple base material of BJS.
  45603. *
  45604. * This enables better naming and convention enforcements on top of the pbrMaterial.
  45605. * It is used as the base class for both the specGloss and metalRough conventions.
  45606. */
  45607. var PBRBaseSimpleMaterial = /** @class */ (function (_super) {
  45608. __extends(PBRBaseSimpleMaterial, _super);
  45609. /**
  45610. * Instantiates a new PBRMaterial instance.
  45611. *
  45612. * @param name The material name
  45613. * @param scene The scene the material will be use in.
  45614. */
  45615. function PBRBaseSimpleMaterial(name, scene) {
  45616. var _this = _super.call(this, name, scene) || this;
  45617. /**
  45618. * Number of Simultaneous lights allowed on the material.
  45619. */
  45620. _this.maxSimultaneousLights = 4;
  45621. /**
  45622. * If sets to true, disables all the lights affecting the material.
  45623. */
  45624. _this.disableLighting = false;
  45625. /**
  45626. * If sets to true, x component of normal map value will invert (x = 1.0 - x).
  45627. */
  45628. _this.invertNormalMapX = false;
  45629. /**
  45630. * If sets to true, y component of normal map value will invert (y = 1.0 - y).
  45631. */
  45632. _this.invertNormalMapY = false;
  45633. /**
  45634. * Emissivie color used to self-illuminate the model.
  45635. */
  45636. _this.emissiveColor = new BABYLON.Color3(0, 0, 0);
  45637. /**
  45638. * Occlusion Channel Strenght.
  45639. */
  45640. _this.occlusionStrength = 1.0;
  45641. _this.useLightmapAsShadowmap = false;
  45642. _this._useAlphaFromAlbedoTexture = true;
  45643. _this._useAmbientInGrayScale = true;
  45644. return _this;
  45645. }
  45646. Object.defineProperty(PBRBaseSimpleMaterial.prototype, "doubleSided", {
  45647. /**
  45648. * Gets the current double sided mode.
  45649. */
  45650. get: function () {
  45651. return this._twoSidedLighting;
  45652. },
  45653. /**
  45654. * If sets to true and backfaceCulling is false, normals will be flipped on the backside.
  45655. */
  45656. set: function (value) {
  45657. if (this._twoSidedLighting === value) {
  45658. return;
  45659. }
  45660. this._twoSidedLighting = value;
  45661. this.backFaceCulling = !value;
  45662. this._markAllSubMeshesAsTexturesDirty();
  45663. },
  45664. enumerable: true,
  45665. configurable: true
  45666. });
  45667. /**
  45668. * Return the active textures of the material.
  45669. */
  45670. PBRBaseSimpleMaterial.prototype.getActiveTextures = function () {
  45671. var activeTextures = _super.prototype.getActiveTextures.call(this);
  45672. if (this.environmentTexture) {
  45673. activeTextures.push(this.environmentTexture);
  45674. }
  45675. if (this.normalTexture) {
  45676. activeTextures.push(this.normalTexture);
  45677. }
  45678. if (this.emissiveTexture) {
  45679. activeTextures.push(this.emissiveTexture);
  45680. }
  45681. if (this.occlusionTexture) {
  45682. activeTextures.push(this.occlusionTexture);
  45683. }
  45684. if (this.lightmapTexture) {
  45685. activeTextures.push(this.lightmapTexture);
  45686. }
  45687. return activeTextures;
  45688. };
  45689. PBRBaseSimpleMaterial.prototype.hasTexture = function (texture) {
  45690. if (_super.prototype.hasTexture.call(this, texture)) {
  45691. return true;
  45692. }
  45693. if (this.lightmapTexture === texture) {
  45694. return true;
  45695. }
  45696. return false;
  45697. };
  45698. PBRBaseSimpleMaterial.prototype.getClassName = function () {
  45699. return "PBRBaseSimpleMaterial";
  45700. };
  45701. __decorate([
  45702. BABYLON.serialize(),
  45703. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  45704. ], PBRBaseSimpleMaterial.prototype, "maxSimultaneousLights", void 0);
  45705. __decorate([
  45706. BABYLON.serialize(),
  45707. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  45708. ], PBRBaseSimpleMaterial.prototype, "disableLighting", void 0);
  45709. __decorate([
  45710. BABYLON.serializeAsTexture(),
  45711. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_reflectionTexture")
  45712. ], PBRBaseSimpleMaterial.prototype, "environmentTexture", void 0);
  45713. __decorate([
  45714. BABYLON.serialize(),
  45715. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45716. ], PBRBaseSimpleMaterial.prototype, "invertNormalMapX", void 0);
  45717. __decorate([
  45718. BABYLON.serialize(),
  45719. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45720. ], PBRBaseSimpleMaterial.prototype, "invertNormalMapY", void 0);
  45721. __decorate([
  45722. BABYLON.serializeAsTexture(),
  45723. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_bumpTexture")
  45724. ], PBRBaseSimpleMaterial.prototype, "normalTexture", void 0);
  45725. __decorate([
  45726. BABYLON.serializeAsColor3("emissive"),
  45727. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45728. ], PBRBaseSimpleMaterial.prototype, "emissiveColor", void 0);
  45729. __decorate([
  45730. BABYLON.serializeAsTexture(),
  45731. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45732. ], PBRBaseSimpleMaterial.prototype, "emissiveTexture", void 0);
  45733. __decorate([
  45734. BABYLON.serialize(),
  45735. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_ambientTextureStrength")
  45736. ], PBRBaseSimpleMaterial.prototype, "occlusionStrength", void 0);
  45737. __decorate([
  45738. BABYLON.serializeAsTexture(),
  45739. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_ambientTexture")
  45740. ], PBRBaseSimpleMaterial.prototype, "occlusionTexture", void 0);
  45741. __decorate([
  45742. BABYLON.serialize(),
  45743. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_alphaCutOff")
  45744. ], PBRBaseSimpleMaterial.prototype, "alphaCutOff", void 0);
  45745. __decorate([
  45746. BABYLON.serialize()
  45747. ], PBRBaseSimpleMaterial.prototype, "doubleSided", null);
  45748. __decorate([
  45749. BABYLON.serializeAsTexture(),
  45750. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", null)
  45751. ], PBRBaseSimpleMaterial.prototype, "lightmapTexture", void 0);
  45752. __decorate([
  45753. BABYLON.serialize(),
  45754. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45755. ], PBRBaseSimpleMaterial.prototype, "useLightmapAsShadowmap", void 0);
  45756. return PBRBaseSimpleMaterial;
  45757. }(BABYLON.PBRBaseMaterial));
  45758. BABYLON.PBRBaseSimpleMaterial = PBRBaseSimpleMaterial;
  45759. })(BABYLON || (BABYLON = {}));
  45760. //# sourceMappingURL=babylon.pbrBaseSimpleMaterial.js.map
  45761. var BABYLON;
  45762. (function (BABYLON) {
  45763. /**
  45764. * The Physically based material of BJS.
  45765. *
  45766. * This offers the main features of a standard PBR material.
  45767. * For more information, please refer to the documentation :
  45768. * http://doc.babylonjs.com/extensions/Physically_Based_Rendering
  45769. */
  45770. var PBRMaterial = /** @class */ (function (_super) {
  45771. __extends(PBRMaterial, _super);
  45772. /**
  45773. * Instantiates a new PBRMaterial instance.
  45774. *
  45775. * @param name The material name
  45776. * @param scene The scene the material will be use in.
  45777. */
  45778. function PBRMaterial(name, scene) {
  45779. var _this = _super.call(this, name, scene) || this;
  45780. /**
  45781. * Intensity of the direct lights e.g. the four lights available in your scene.
  45782. * This impacts both the direct diffuse and specular highlights.
  45783. */
  45784. _this.directIntensity = 1.0;
  45785. /**
  45786. * Intensity of the emissive part of the material.
  45787. * This helps controlling the emissive effect without modifying the emissive color.
  45788. */
  45789. _this.emissiveIntensity = 1.0;
  45790. /**
  45791. * Intensity of the environment e.g. how much the environment will light the object
  45792. * either through harmonics for rough material or through the refelction for shiny ones.
  45793. */
  45794. _this.environmentIntensity = 1.0;
  45795. /**
  45796. * This is a special control allowing the reduction of the specular highlights coming from the
  45797. * four lights of the scene. Those highlights may not be needed in full environment lighting.
  45798. */
  45799. _this.specularIntensity = 1.0;
  45800. /**
  45801. * Debug Control allowing disabling the bump map on this material.
  45802. */
  45803. _this.disableBumpMap = false;
  45804. /**
  45805. * AKA Occlusion Texture Intensity in other nomenclature.
  45806. */
  45807. _this.ambientTextureStrength = 1.0;
  45808. /**
  45809. * The color of a material in ambient lighting.
  45810. */
  45811. _this.ambientColor = new BABYLON.Color3(0, 0, 0);
  45812. /**
  45813. * AKA Diffuse Color in other nomenclature.
  45814. */
  45815. _this.albedoColor = new BABYLON.Color3(1, 1, 1);
  45816. /**
  45817. * AKA Specular Color in other nomenclature.
  45818. */
  45819. _this.reflectivityColor = new BABYLON.Color3(1, 1, 1);
  45820. /**
  45821. * The color reflected from the material.
  45822. */
  45823. _this.reflectionColor = new BABYLON.Color3(1.0, 1.0, 1.0);
  45824. /**
  45825. * The color emitted from the material.
  45826. */
  45827. _this.emissiveColor = new BABYLON.Color3(0, 0, 0);
  45828. /**
  45829. * AKA Glossiness in other nomenclature.
  45830. */
  45831. _this.microSurface = 1.0;
  45832. /**
  45833. * source material index of refraction (IOR)' / 'destination material IOR.
  45834. */
  45835. _this.indexOfRefraction = 0.66;
  45836. /**
  45837. * Controls if refraction needs to be inverted on Y. This could be usefull for procedural texture.
  45838. */
  45839. _this.invertRefractionY = false;
  45840. /**
  45841. * This parameters will make the material used its opacity to control how much it is refracting aginst not.
  45842. * Materials half opaque for instance using refraction could benefit from this control.
  45843. */
  45844. _this.linkRefractionWithTransparency = false;
  45845. _this.useLightmapAsShadowmap = false;
  45846. /**
  45847. * Specifies that the alpha is coming form the albedo channel alpha channel for alpha blending.
  45848. */
  45849. _this.useAlphaFromAlbedoTexture = false;
  45850. /**
  45851. * Enforces alpha test in opaque or blend mode in order to improve the performances of some situations.
  45852. */
  45853. _this.forceAlphaTest = false;
  45854. /**
  45855. * Defines the alpha limits in alpha test mode.
  45856. */
  45857. _this.alphaCutOff = 0.4;
  45858. /**
  45859. * Specifies that the material will keeps the specular highlights over a transparent surface (only the most limunous ones).
  45860. * A car glass is a good exemple of that. When sun reflects on it you can not see what is behind.
  45861. */
  45862. _this.useSpecularOverAlpha = true;
  45863. /**
  45864. * Specifies if the reflectivity texture contains the glossiness information in its alpha channel.
  45865. */
  45866. _this.useMicroSurfaceFromReflectivityMapAlpha = false;
  45867. /**
  45868. * Specifies if the metallic texture contains the roughness information in its alpha channel.
  45869. */
  45870. _this.useRoughnessFromMetallicTextureAlpha = true;
  45871. /**
  45872. * Specifies if the metallic texture contains the roughness information in its green channel.
  45873. */
  45874. _this.useRoughnessFromMetallicTextureGreen = false;
  45875. /**
  45876. * Specifies if the metallic texture contains the metallness information in its blue channel.
  45877. */
  45878. _this.useMetallnessFromMetallicTextureBlue = false;
  45879. /**
  45880. * Specifies if the metallic texture contains the ambient occlusion information in its red channel.
  45881. */
  45882. _this.useAmbientOcclusionFromMetallicTextureRed = false;
  45883. /**
  45884. * Specifies if the ambient texture contains the ambient occlusion information in its red channel only.
  45885. */
  45886. _this.useAmbientInGrayScale = false;
  45887. /**
  45888. * In case the reflectivity map does not contain the microsurface information in its alpha channel,
  45889. * The material will try to infer what glossiness each pixel should be.
  45890. */
  45891. _this.useAutoMicroSurfaceFromReflectivityMap = false;
  45892. /**
  45893. * BJS is using an harcoded light falloff based on a manually sets up range.
  45894. * In PBR, one way to represents the fallof is to use the inverse squared root algorythm.
  45895. * This parameter can help you switch back to the BJS mode in order to create scenes using both materials.
  45896. */
  45897. _this.usePhysicalLightFalloff = true;
  45898. /**
  45899. * Specifies that the material will keeps the reflection highlights over a transparent surface (only the most limunous ones).
  45900. * A car glass is a good exemple of that. When the street lights reflects on it you can not see what is behind.
  45901. */
  45902. _this.useRadianceOverAlpha = true;
  45903. /**
  45904. * Allows using an object space normal map (instead of tangent space).
  45905. */
  45906. _this.useObjectSpaceNormalMap = false;
  45907. /**
  45908. * Allows using the bump map in parallax mode.
  45909. */
  45910. _this.useParallax = false;
  45911. /**
  45912. * Allows using the bump map in parallax occlusion mode.
  45913. */
  45914. _this.useParallaxOcclusion = false;
  45915. /**
  45916. * Controls the scale bias of the parallax mode.
  45917. */
  45918. _this.parallaxScaleBias = 0.05;
  45919. /**
  45920. * If sets to true, disables all the lights affecting the material.
  45921. */
  45922. _this.disableLighting = false;
  45923. /**
  45924. * Force the shader to compute irradiance in the fragment shader in order to take bump in account.
  45925. */
  45926. _this.forceIrradianceInFragment = false;
  45927. /**
  45928. * Number of Simultaneous lights allowed on the material.
  45929. */
  45930. _this.maxSimultaneousLights = 4;
  45931. /**
  45932. * If sets to true, x component of normal map value will invert (x = 1.0 - x).
  45933. */
  45934. _this.invertNormalMapX = false;
  45935. /**
  45936. * If sets to true, y component of normal map value will invert (y = 1.0 - y).
  45937. */
  45938. _this.invertNormalMapY = false;
  45939. /**
  45940. * If sets to true and backfaceCulling is false, normals will be flipped on the backside.
  45941. */
  45942. _this.twoSidedLighting = false;
  45943. /**
  45944. * A fresnel is applied to the alpha of the model to ensure grazing angles edges are not alpha tested.
  45945. * And/Or occlude the blended part. (alpha is converted to gamma to compute the fresnel)
  45946. */
  45947. _this.useAlphaFresnel = false;
  45948. /**
  45949. * A fresnel is applied to the alpha of the model to ensure grazing angles edges are not alpha tested.
  45950. * And/Or occlude the blended part. (alpha stays linear to compute the fresnel)
  45951. */
  45952. _this.useLinearAlphaFresnel = false;
  45953. /**
  45954. * A fresnel is applied to the alpha of the model to ensure grazing angles edges are not alpha tested.
  45955. * And/Or occlude the blended part.
  45956. */
  45957. _this.environmentBRDFTexture = null;
  45958. /**
  45959. * Force normal to face away from face.
  45960. */
  45961. _this.forceNormalForward = false;
  45962. /**
  45963. * Enables specular anti aliasing in the PBR shader.
  45964. * It will both interacts on the Geometry for analytical and IBL lighting.
  45965. * It also prefilter the roughness map based on the bump values.
  45966. */
  45967. _this.enableSpecularAntiAliasing = false;
  45968. /**
  45969. * This parameters will enable/disable Horizon occlusion to prevent normal maps to look shiny when the normal
  45970. * makes the reflect vector face the model (under horizon).
  45971. */
  45972. _this.useHorizonOcclusion = true;
  45973. /**
  45974. * This parameters will enable/disable radiance occlusion by preventing the radiance to lit
  45975. * too much the area relying on ambient texture to define their ambient occlusion.
  45976. */
  45977. _this.useRadianceOcclusion = true;
  45978. /**
  45979. * If set to true, no lighting calculations will be applied.
  45980. */
  45981. _this.unlit = false;
  45982. _this._environmentBRDFTexture = BABYLON.TextureTools.GetEnvironmentBRDFTexture(scene);
  45983. return _this;
  45984. }
  45985. Object.defineProperty(PBRMaterial, "PBRMATERIAL_OPAQUE", {
  45986. /**
  45987. * PBRMaterialTransparencyMode: No transparency mode, Alpha channel is not use.
  45988. */
  45989. get: function () {
  45990. return this._PBRMATERIAL_OPAQUE;
  45991. },
  45992. enumerable: true,
  45993. configurable: true
  45994. });
  45995. Object.defineProperty(PBRMaterial, "PBRMATERIAL_ALPHATEST", {
  45996. /**
  45997. * PBRMaterialTransparencyMode: Alpha Test mode, pixel are discarded below a certain threshold defined by the alpha cutoff value.
  45998. */
  45999. get: function () {
  46000. return this._PBRMATERIAL_ALPHATEST;
  46001. },
  46002. enumerable: true,
  46003. configurable: true
  46004. });
  46005. Object.defineProperty(PBRMaterial, "PBRMATERIAL_ALPHABLEND", {
  46006. /**
  46007. * PBRMaterialTransparencyMode: Pixels are blended (according to the alpha mode) with the already drawn pixels in the current frame buffer.
  46008. */
  46009. get: function () {
  46010. return this._PBRMATERIAL_ALPHABLEND;
  46011. },
  46012. enumerable: true,
  46013. configurable: true
  46014. });
  46015. Object.defineProperty(PBRMaterial, "PBRMATERIAL_ALPHATESTANDBLEND", {
  46016. /**
  46017. * PBRMaterialTransparencyMode: Pixels are blended (according to the alpha mode) with the already drawn pixels in the current frame buffer.
  46018. * They are also discarded below the alpha cutoff threshold to improve performances.
  46019. */
  46020. get: function () {
  46021. return this._PBRMATERIAL_ALPHATESTANDBLEND;
  46022. },
  46023. enumerable: true,
  46024. configurable: true
  46025. });
  46026. Object.defineProperty(PBRMaterial.prototype, "imageProcessingConfiguration", {
  46027. /**
  46028. * Gets the image processing configuration used either in this material.
  46029. */
  46030. get: function () {
  46031. return this._imageProcessingConfiguration;
  46032. },
  46033. /**
  46034. * Sets the Default image processing configuration used either in the this material.
  46035. *
  46036. * If sets to null, the scene one is in use.
  46037. */
  46038. set: function (value) {
  46039. this._attachImageProcessingConfiguration(value);
  46040. // Ensure the effect will be rebuilt.
  46041. this._markAllSubMeshesAsTexturesDirty();
  46042. },
  46043. enumerable: true,
  46044. configurable: true
  46045. });
  46046. Object.defineProperty(PBRMaterial.prototype, "cameraColorCurvesEnabled", {
  46047. /**
  46048. * Gets wether the color curves effect is enabled.
  46049. */
  46050. get: function () {
  46051. return this.imageProcessingConfiguration.colorCurvesEnabled;
  46052. },
  46053. /**
  46054. * Sets wether the color curves effect is enabled.
  46055. */
  46056. set: function (value) {
  46057. this.imageProcessingConfiguration.colorCurvesEnabled = value;
  46058. },
  46059. enumerable: true,
  46060. configurable: true
  46061. });
  46062. Object.defineProperty(PBRMaterial.prototype, "cameraColorGradingEnabled", {
  46063. /**
  46064. * Gets wether the color grading effect is enabled.
  46065. */
  46066. get: function () {
  46067. return this.imageProcessingConfiguration.colorGradingEnabled;
  46068. },
  46069. /**
  46070. * Gets wether the color grading effect is enabled.
  46071. */
  46072. set: function (value) {
  46073. this.imageProcessingConfiguration.colorGradingEnabled = value;
  46074. },
  46075. enumerable: true,
  46076. configurable: true
  46077. });
  46078. Object.defineProperty(PBRMaterial.prototype, "cameraToneMappingEnabled", {
  46079. /**
  46080. * Gets wether tonemapping is enabled or not.
  46081. */
  46082. get: function () {
  46083. return this._imageProcessingConfiguration.toneMappingEnabled;
  46084. },
  46085. /**
  46086. * Sets wether tonemapping is enabled or not
  46087. */
  46088. set: function (value) {
  46089. this._imageProcessingConfiguration.toneMappingEnabled = value;
  46090. },
  46091. enumerable: true,
  46092. configurable: true
  46093. });
  46094. ;
  46095. ;
  46096. Object.defineProperty(PBRMaterial.prototype, "cameraExposure", {
  46097. /**
  46098. * The camera exposure used on this material.
  46099. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  46100. * This corresponds to a photographic exposure.
  46101. */
  46102. get: function () {
  46103. return this._imageProcessingConfiguration.exposure;
  46104. },
  46105. /**
  46106. * The camera exposure used on this material.
  46107. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  46108. * This corresponds to a photographic exposure.
  46109. */
  46110. set: function (value) {
  46111. this._imageProcessingConfiguration.exposure = value;
  46112. },
  46113. enumerable: true,
  46114. configurable: true
  46115. });
  46116. ;
  46117. ;
  46118. Object.defineProperty(PBRMaterial.prototype, "cameraContrast", {
  46119. /**
  46120. * Gets The camera contrast used on this material.
  46121. */
  46122. get: function () {
  46123. return this._imageProcessingConfiguration.contrast;
  46124. },
  46125. /**
  46126. * Sets The camera contrast used on this material.
  46127. */
  46128. set: function (value) {
  46129. this._imageProcessingConfiguration.contrast = value;
  46130. },
  46131. enumerable: true,
  46132. configurable: true
  46133. });
  46134. Object.defineProperty(PBRMaterial.prototype, "cameraColorGradingTexture", {
  46135. /**
  46136. * Gets the Color Grading 2D Lookup Texture.
  46137. */
  46138. get: function () {
  46139. return this._imageProcessingConfiguration.colorGradingTexture;
  46140. },
  46141. /**
  46142. * Sets the Color Grading 2D Lookup Texture.
  46143. */
  46144. set: function (value) {
  46145. this._imageProcessingConfiguration.colorGradingTexture = value;
  46146. },
  46147. enumerable: true,
  46148. configurable: true
  46149. });
  46150. Object.defineProperty(PBRMaterial.prototype, "cameraColorCurves", {
  46151. /**
  46152. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  46153. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  46154. * 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;
  46155. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  46156. */
  46157. get: function () {
  46158. return this._imageProcessingConfiguration.colorCurves;
  46159. },
  46160. /**
  46161. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  46162. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  46163. * 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;
  46164. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  46165. */
  46166. set: function (value) {
  46167. this._imageProcessingConfiguration.colorCurves = value;
  46168. },
  46169. enumerable: true,
  46170. configurable: true
  46171. });
  46172. /**
  46173. * Returns the name of this material class.
  46174. */
  46175. PBRMaterial.prototype.getClassName = function () {
  46176. return "PBRMaterial";
  46177. };
  46178. /**
  46179. * Returns an array of the actively used textures.
  46180. * @returns - Array of BaseTextures
  46181. */
  46182. PBRMaterial.prototype.getActiveTextures = function () {
  46183. var activeTextures = _super.prototype.getActiveTextures.call(this);
  46184. if (this._albedoTexture) {
  46185. activeTextures.push(this._albedoTexture);
  46186. }
  46187. if (this._ambientTexture) {
  46188. activeTextures.push(this._ambientTexture);
  46189. }
  46190. if (this._opacityTexture) {
  46191. activeTextures.push(this._opacityTexture);
  46192. }
  46193. if (this._reflectionTexture) {
  46194. activeTextures.push(this._reflectionTexture);
  46195. }
  46196. if (this._emissiveTexture) {
  46197. activeTextures.push(this._emissiveTexture);
  46198. }
  46199. if (this._reflectivityTexture) {
  46200. activeTextures.push(this._reflectivityTexture);
  46201. }
  46202. if (this._metallicTexture) {
  46203. activeTextures.push(this._metallicTexture);
  46204. }
  46205. if (this._microSurfaceTexture) {
  46206. activeTextures.push(this._microSurfaceTexture);
  46207. }
  46208. if (this._bumpTexture) {
  46209. activeTextures.push(this._bumpTexture);
  46210. }
  46211. if (this._lightmapTexture) {
  46212. activeTextures.push(this._lightmapTexture);
  46213. }
  46214. if (this._refractionTexture) {
  46215. activeTextures.push(this._refractionTexture);
  46216. }
  46217. return activeTextures;
  46218. };
  46219. /**
  46220. * Checks to see if a texture is used in the material.
  46221. * @param texture - Base texture to use.
  46222. * @returns - Boolean specifying if a texture is used in the material.
  46223. */
  46224. PBRMaterial.prototype.hasTexture = function (texture) {
  46225. if (_super.prototype.hasTexture.call(this, texture)) {
  46226. return true;
  46227. }
  46228. if (this._albedoTexture === texture) {
  46229. return true;
  46230. }
  46231. if (this._ambientTexture === texture) {
  46232. return true;
  46233. }
  46234. if (this._opacityTexture === texture) {
  46235. return true;
  46236. }
  46237. if (this._reflectionTexture === texture) {
  46238. return true;
  46239. }
  46240. if (this._reflectivityTexture === texture) {
  46241. return true;
  46242. }
  46243. if (this._metallicTexture === texture) {
  46244. return true;
  46245. }
  46246. if (this._microSurfaceTexture === texture) {
  46247. return true;
  46248. }
  46249. if (this._bumpTexture === texture) {
  46250. return true;
  46251. }
  46252. if (this._lightmapTexture === texture) {
  46253. return true;
  46254. }
  46255. if (this._refractionTexture === texture) {
  46256. return true;
  46257. }
  46258. return false;
  46259. };
  46260. /**
  46261. * Makes a duplicate of the current material.
  46262. * @param name - name to use for the new material.
  46263. */
  46264. PBRMaterial.prototype.clone = function (name) {
  46265. var _this = this;
  46266. var clone = BABYLON.SerializationHelper.Clone(function () { return new PBRMaterial(name, _this.getScene()); }, this);
  46267. clone.id = name;
  46268. clone.name = name;
  46269. return clone;
  46270. };
  46271. /**
  46272. * Serializes this PBR Material.
  46273. * @returns - An object with the serialized material.
  46274. */
  46275. PBRMaterial.prototype.serialize = function () {
  46276. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  46277. serializationObject.customType = "BABYLON.PBRMaterial";
  46278. return serializationObject;
  46279. };
  46280. // Statics
  46281. /**
  46282. * Parses a PBR Material from a serialized object.
  46283. * @param source - Serialized object.
  46284. * @param scene - BJS scene instance.
  46285. * @param rootUrl - url for the scene object
  46286. * @returns - PBRMaterial
  46287. */
  46288. PBRMaterial.Parse = function (source, scene, rootUrl) {
  46289. return BABYLON.SerializationHelper.Parse(function () { return new PBRMaterial(source.name, scene); }, source, scene, rootUrl);
  46290. };
  46291. PBRMaterial._PBRMATERIAL_OPAQUE = 0;
  46292. /**
  46293. * Alpha Test mode, pixel are discarded below a certain threshold defined by the alpha cutoff value.
  46294. */
  46295. PBRMaterial._PBRMATERIAL_ALPHATEST = 1;
  46296. /**
  46297. * Represents the value for Alpha Blend. Pixels are blended (according to the alpha mode) with the already drawn pixels in the current frame buffer.
  46298. */
  46299. PBRMaterial._PBRMATERIAL_ALPHABLEND = 2;
  46300. /**
  46301. * 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.
  46302. * They are also discarded below the alpha cutoff threshold to improve performances.
  46303. */
  46304. PBRMaterial._PBRMATERIAL_ALPHATESTANDBLEND = 3;
  46305. __decorate([
  46306. BABYLON.serialize(),
  46307. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46308. ], PBRMaterial.prototype, "directIntensity", void 0);
  46309. __decorate([
  46310. BABYLON.serialize(),
  46311. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46312. ], PBRMaterial.prototype, "emissiveIntensity", void 0);
  46313. __decorate([
  46314. BABYLON.serialize(),
  46315. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46316. ], PBRMaterial.prototype, "environmentIntensity", void 0);
  46317. __decorate([
  46318. BABYLON.serialize(),
  46319. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46320. ], PBRMaterial.prototype, "specularIntensity", void 0);
  46321. __decorate([
  46322. BABYLON.serialize(),
  46323. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46324. ], PBRMaterial.prototype, "disableBumpMap", void 0);
  46325. __decorate([
  46326. BABYLON.serializeAsTexture(),
  46327. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46328. ], PBRMaterial.prototype, "albedoTexture", void 0);
  46329. __decorate([
  46330. BABYLON.serializeAsTexture(),
  46331. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46332. ], PBRMaterial.prototype, "ambientTexture", void 0);
  46333. __decorate([
  46334. BABYLON.serialize(),
  46335. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46336. ], PBRMaterial.prototype, "ambientTextureStrength", void 0);
  46337. __decorate([
  46338. BABYLON.serializeAsTexture(),
  46339. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesAndMiscDirty")
  46340. ], PBRMaterial.prototype, "opacityTexture", void 0);
  46341. __decorate([
  46342. BABYLON.serializeAsTexture(),
  46343. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46344. ], PBRMaterial.prototype, "reflectionTexture", void 0);
  46345. __decorate([
  46346. BABYLON.serializeAsTexture(),
  46347. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46348. ], PBRMaterial.prototype, "emissiveTexture", void 0);
  46349. __decorate([
  46350. BABYLON.serializeAsTexture(),
  46351. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46352. ], PBRMaterial.prototype, "reflectivityTexture", void 0);
  46353. __decorate([
  46354. BABYLON.serializeAsTexture(),
  46355. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46356. ], PBRMaterial.prototype, "metallicTexture", void 0);
  46357. __decorate([
  46358. BABYLON.serialize(),
  46359. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46360. ], PBRMaterial.prototype, "metallic", void 0);
  46361. __decorate([
  46362. BABYLON.serialize(),
  46363. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46364. ], PBRMaterial.prototype, "roughness", void 0);
  46365. __decorate([
  46366. BABYLON.serializeAsTexture(),
  46367. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46368. ], PBRMaterial.prototype, "microSurfaceTexture", void 0);
  46369. __decorate([
  46370. BABYLON.serializeAsTexture(),
  46371. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46372. ], PBRMaterial.prototype, "bumpTexture", void 0);
  46373. __decorate([
  46374. BABYLON.serializeAsTexture(),
  46375. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", null)
  46376. ], PBRMaterial.prototype, "lightmapTexture", void 0);
  46377. __decorate([
  46378. BABYLON.serializeAsTexture(),
  46379. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46380. ], PBRMaterial.prototype, "refractionTexture", void 0);
  46381. __decorate([
  46382. BABYLON.serializeAsColor3("ambient"),
  46383. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46384. ], PBRMaterial.prototype, "ambientColor", void 0);
  46385. __decorate([
  46386. BABYLON.serializeAsColor3("albedo"),
  46387. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46388. ], PBRMaterial.prototype, "albedoColor", void 0);
  46389. __decorate([
  46390. BABYLON.serializeAsColor3("reflectivity"),
  46391. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46392. ], PBRMaterial.prototype, "reflectivityColor", void 0);
  46393. __decorate([
  46394. BABYLON.serializeAsColor3("reflection"),
  46395. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46396. ], PBRMaterial.prototype, "reflectionColor", void 0);
  46397. __decorate([
  46398. BABYLON.serializeAsColor3("emissive"),
  46399. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46400. ], PBRMaterial.prototype, "emissiveColor", void 0);
  46401. __decorate([
  46402. BABYLON.serialize(),
  46403. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46404. ], PBRMaterial.prototype, "microSurface", void 0);
  46405. __decorate([
  46406. BABYLON.serialize(),
  46407. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46408. ], PBRMaterial.prototype, "indexOfRefraction", void 0);
  46409. __decorate([
  46410. BABYLON.serialize(),
  46411. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46412. ], PBRMaterial.prototype, "invertRefractionY", void 0);
  46413. __decorate([
  46414. BABYLON.serialize(),
  46415. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46416. ], PBRMaterial.prototype, "linkRefractionWithTransparency", void 0);
  46417. __decorate([
  46418. BABYLON.serialize(),
  46419. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46420. ], PBRMaterial.prototype, "useLightmapAsShadowmap", void 0);
  46421. __decorate([
  46422. BABYLON.serialize(),
  46423. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesAndMiscDirty")
  46424. ], PBRMaterial.prototype, "useAlphaFromAlbedoTexture", void 0);
  46425. __decorate([
  46426. BABYLON.serialize(),
  46427. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesAndMiscDirty")
  46428. ], PBRMaterial.prototype, "forceAlphaTest", void 0);
  46429. __decorate([
  46430. BABYLON.serialize(),
  46431. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesAndMiscDirty")
  46432. ], PBRMaterial.prototype, "alphaCutOff", void 0);
  46433. __decorate([
  46434. BABYLON.serialize(),
  46435. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46436. ], PBRMaterial.prototype, "useSpecularOverAlpha", void 0);
  46437. __decorate([
  46438. BABYLON.serialize(),
  46439. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46440. ], PBRMaterial.prototype, "useMicroSurfaceFromReflectivityMapAlpha", void 0);
  46441. __decorate([
  46442. BABYLON.serialize(),
  46443. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46444. ], PBRMaterial.prototype, "useRoughnessFromMetallicTextureAlpha", void 0);
  46445. __decorate([
  46446. BABYLON.serialize(),
  46447. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46448. ], PBRMaterial.prototype, "useRoughnessFromMetallicTextureGreen", void 0);
  46449. __decorate([
  46450. BABYLON.serialize(),
  46451. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46452. ], PBRMaterial.prototype, "useMetallnessFromMetallicTextureBlue", void 0);
  46453. __decorate([
  46454. BABYLON.serialize(),
  46455. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46456. ], PBRMaterial.prototype, "useAmbientOcclusionFromMetallicTextureRed", void 0);
  46457. __decorate([
  46458. BABYLON.serialize(),
  46459. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46460. ], PBRMaterial.prototype, "useAmbientInGrayScale", void 0);
  46461. __decorate([
  46462. BABYLON.serialize(),
  46463. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46464. ], PBRMaterial.prototype, "useAutoMicroSurfaceFromReflectivityMap", void 0);
  46465. __decorate([
  46466. BABYLON.serialize(),
  46467. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46468. ], PBRMaterial.prototype, "usePhysicalLightFalloff", void 0);
  46469. __decorate([
  46470. BABYLON.serialize(),
  46471. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46472. ], PBRMaterial.prototype, "useRadianceOverAlpha", void 0);
  46473. __decorate([
  46474. BABYLON.serialize(),
  46475. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46476. ], PBRMaterial.prototype, "useObjectSpaceNormalMap", void 0);
  46477. __decorate([
  46478. BABYLON.serialize(),
  46479. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46480. ], PBRMaterial.prototype, "useParallax", void 0);
  46481. __decorate([
  46482. BABYLON.serialize(),
  46483. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46484. ], PBRMaterial.prototype, "useParallaxOcclusion", void 0);
  46485. __decorate([
  46486. BABYLON.serialize(),
  46487. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46488. ], PBRMaterial.prototype, "parallaxScaleBias", void 0);
  46489. __decorate([
  46490. BABYLON.serialize(),
  46491. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  46492. ], PBRMaterial.prototype, "disableLighting", void 0);
  46493. __decorate([
  46494. BABYLON.serialize(),
  46495. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46496. ], PBRMaterial.prototype, "forceIrradianceInFragment", void 0);
  46497. __decorate([
  46498. BABYLON.serialize(),
  46499. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  46500. ], PBRMaterial.prototype, "maxSimultaneousLights", void 0);
  46501. __decorate([
  46502. BABYLON.serialize(),
  46503. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46504. ], PBRMaterial.prototype, "invertNormalMapX", void 0);
  46505. __decorate([
  46506. BABYLON.serialize(),
  46507. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46508. ], PBRMaterial.prototype, "invertNormalMapY", void 0);
  46509. __decorate([
  46510. BABYLON.serialize(),
  46511. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46512. ], PBRMaterial.prototype, "twoSidedLighting", void 0);
  46513. __decorate([
  46514. BABYLON.serialize(),
  46515. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46516. ], PBRMaterial.prototype, "useAlphaFresnel", void 0);
  46517. __decorate([
  46518. BABYLON.serialize(),
  46519. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46520. ], PBRMaterial.prototype, "useLinearAlphaFresnel", void 0);
  46521. __decorate([
  46522. BABYLON.serializeAsTexture(),
  46523. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46524. ], PBRMaterial.prototype, "environmentBRDFTexture", void 0);
  46525. __decorate([
  46526. BABYLON.serialize(),
  46527. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46528. ], PBRMaterial.prototype, "forceNormalForward", void 0);
  46529. __decorate([
  46530. BABYLON.serialize(),
  46531. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46532. ], PBRMaterial.prototype, "enableSpecularAntiAliasing", void 0);
  46533. __decorate([
  46534. BABYLON.serialize(),
  46535. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46536. ], PBRMaterial.prototype, "useHorizonOcclusion", void 0);
  46537. __decorate([
  46538. BABYLON.serialize(),
  46539. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46540. ], PBRMaterial.prototype, "useRadianceOcclusion", void 0);
  46541. __decorate([
  46542. BABYLON.serialize(),
  46543. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  46544. ], PBRMaterial.prototype, "unlit", void 0);
  46545. return PBRMaterial;
  46546. }(BABYLON.PBRBaseMaterial));
  46547. BABYLON.PBRMaterial = PBRMaterial;
  46548. })(BABYLON || (BABYLON = {}));
  46549. //# sourceMappingURL=babylon.pbrMaterial.js.map
  46550. var BABYLON;
  46551. (function (BABYLON) {
  46552. /**
  46553. * The PBR material of BJS following the metal roughness convention.
  46554. *
  46555. * This fits to the PBR convention in the GLTF definition:
  46556. * https://github.com/KhronosGroup/glTF/tree/2.0/specification/2.0
  46557. */
  46558. var PBRMetallicRoughnessMaterial = /** @class */ (function (_super) {
  46559. __extends(PBRMetallicRoughnessMaterial, _super);
  46560. /**
  46561. * Instantiates a new PBRMetalRoughnessMaterial instance.
  46562. *
  46563. * @param name The material name
  46564. * @param scene The scene the material will be use in.
  46565. */
  46566. function PBRMetallicRoughnessMaterial(name, scene) {
  46567. var _this = _super.call(this, name, scene) || this;
  46568. _this._useRoughnessFromMetallicTextureAlpha = false;
  46569. _this._useRoughnessFromMetallicTextureGreen = true;
  46570. _this._useMetallnessFromMetallicTextureBlue = true;
  46571. _this.metallic = 1.0;
  46572. _this.roughness = 1.0;
  46573. return _this;
  46574. }
  46575. /**
  46576. * Return the currrent class name of the material.
  46577. */
  46578. PBRMetallicRoughnessMaterial.prototype.getClassName = function () {
  46579. return "PBRMetallicRoughnessMaterial";
  46580. };
  46581. /**
  46582. * Return the active textures of the material.
  46583. */
  46584. PBRMetallicRoughnessMaterial.prototype.getActiveTextures = function () {
  46585. var activeTextures = _super.prototype.getActiveTextures.call(this);
  46586. if (this.baseTexture) {
  46587. activeTextures.push(this.baseTexture);
  46588. }
  46589. if (this.metallicRoughnessTexture) {
  46590. activeTextures.push(this.metallicRoughnessTexture);
  46591. }
  46592. return activeTextures;
  46593. };
  46594. /**
  46595. * Checks to see if a texture is used in the material.
  46596. * @param texture - Base texture to use.
  46597. * @returns - Boolean specifying if a texture is used in the material.
  46598. */
  46599. PBRMetallicRoughnessMaterial.prototype.hasTexture = function (texture) {
  46600. if (_super.prototype.hasTexture.call(this, texture)) {
  46601. return true;
  46602. }
  46603. if (this.baseTexture === texture) {
  46604. return true;
  46605. }
  46606. if (this.metallicRoughnessTexture === texture) {
  46607. return true;
  46608. }
  46609. return false;
  46610. };
  46611. /**
  46612. * Makes a duplicate of the current material.
  46613. * @param name - name to use for the new material.
  46614. */
  46615. PBRMetallicRoughnessMaterial.prototype.clone = function (name) {
  46616. var _this = this;
  46617. var clone = BABYLON.SerializationHelper.Clone(function () { return new PBRMetallicRoughnessMaterial(name, _this.getScene()); }, this);
  46618. clone.id = name;
  46619. clone.name = name;
  46620. return clone;
  46621. };
  46622. /**
  46623. * Serialize the material to a parsable JSON object.
  46624. */
  46625. PBRMetallicRoughnessMaterial.prototype.serialize = function () {
  46626. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  46627. serializationObject.customType = "BABYLON.PBRMetallicRoughnessMaterial";
  46628. return serializationObject;
  46629. };
  46630. /**
  46631. * Parses a JSON object correponding to the serialize function.
  46632. */
  46633. PBRMetallicRoughnessMaterial.Parse = function (source, scene, rootUrl) {
  46634. return BABYLON.SerializationHelper.Parse(function () { return new PBRMetallicRoughnessMaterial(source.name, scene); }, source, scene, rootUrl);
  46635. };
  46636. __decorate([
  46637. BABYLON.serializeAsColor3(),
  46638. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_albedoColor")
  46639. ], PBRMetallicRoughnessMaterial.prototype, "baseColor", void 0);
  46640. __decorate([
  46641. BABYLON.serializeAsTexture(),
  46642. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_albedoTexture")
  46643. ], PBRMetallicRoughnessMaterial.prototype, "baseTexture", void 0);
  46644. __decorate([
  46645. BABYLON.serialize(),
  46646. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46647. ], PBRMetallicRoughnessMaterial.prototype, "metallic", void 0);
  46648. __decorate([
  46649. BABYLON.serialize(),
  46650. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46651. ], PBRMetallicRoughnessMaterial.prototype, "roughness", void 0);
  46652. __decorate([
  46653. BABYLON.serializeAsTexture(),
  46654. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_metallicTexture")
  46655. ], PBRMetallicRoughnessMaterial.prototype, "metallicRoughnessTexture", void 0);
  46656. return PBRMetallicRoughnessMaterial;
  46657. }(BABYLON.PBRBaseSimpleMaterial));
  46658. BABYLON.PBRMetallicRoughnessMaterial = PBRMetallicRoughnessMaterial;
  46659. })(BABYLON || (BABYLON = {}));
  46660. //# sourceMappingURL=babylon.pbrMetallicRoughnessMaterial.js.map
  46661. var BABYLON;
  46662. (function (BABYLON) {
  46663. /**
  46664. * The PBR material of BJS following the specular glossiness convention.
  46665. *
  46666. * This fits to the PBR convention in the GLTF definition:
  46667. * https://github.com/KhronosGroup/glTF/tree/2.0/extensions/Khronos/KHR_materials_pbrSpecularGlossiness
  46668. */
  46669. var PBRSpecularGlossinessMaterial = /** @class */ (function (_super) {
  46670. __extends(PBRSpecularGlossinessMaterial, _super);
  46671. /**
  46672. * Instantiates a new PBRSpecularGlossinessMaterial instance.
  46673. *
  46674. * @param name The material name
  46675. * @param scene The scene the material will be use in.
  46676. */
  46677. function PBRSpecularGlossinessMaterial(name, scene) {
  46678. var _this = _super.call(this, name, scene) || this;
  46679. _this._useMicroSurfaceFromReflectivityMapAlpha = true;
  46680. return _this;
  46681. }
  46682. /**
  46683. * Return the currrent class name of the material.
  46684. */
  46685. PBRSpecularGlossinessMaterial.prototype.getClassName = function () {
  46686. return "PBRSpecularGlossinessMaterial";
  46687. };
  46688. /**
  46689. * Return the active textures of the material.
  46690. */
  46691. PBRSpecularGlossinessMaterial.prototype.getActiveTextures = function () {
  46692. var activeTextures = _super.prototype.getActiveTextures.call(this);
  46693. if (this.diffuseTexture) {
  46694. activeTextures.push(this.diffuseTexture);
  46695. }
  46696. if (this.specularGlossinessTexture) {
  46697. activeTextures.push(this.specularGlossinessTexture);
  46698. }
  46699. return activeTextures;
  46700. };
  46701. /**
  46702. * Checks to see if a texture is used in the material.
  46703. * @param texture - Base texture to use.
  46704. * @returns - Boolean specifying if a texture is used in the material.
  46705. */
  46706. PBRSpecularGlossinessMaterial.prototype.hasTexture = function (texture) {
  46707. if (_super.prototype.hasTexture.call(this, texture)) {
  46708. return true;
  46709. }
  46710. if (this.diffuseTexture === texture) {
  46711. return true;
  46712. }
  46713. if (this.specularGlossinessTexture === texture) {
  46714. return true;
  46715. }
  46716. return false;
  46717. };
  46718. /**
  46719. * Makes a duplicate of the current material.
  46720. * @param name - name to use for the new material.
  46721. */
  46722. PBRSpecularGlossinessMaterial.prototype.clone = function (name) {
  46723. var _this = this;
  46724. var clone = BABYLON.SerializationHelper.Clone(function () { return new PBRSpecularGlossinessMaterial(name, _this.getScene()); }, this);
  46725. clone.id = name;
  46726. clone.name = name;
  46727. return clone;
  46728. };
  46729. /**
  46730. * Serialize the material to a parsable JSON object.
  46731. */
  46732. PBRSpecularGlossinessMaterial.prototype.serialize = function () {
  46733. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  46734. serializationObject.customType = "BABYLON.PBRSpecularGlossinessMaterial";
  46735. return serializationObject;
  46736. };
  46737. /**
  46738. * Parses a JSON object correponding to the serialize function.
  46739. */
  46740. PBRSpecularGlossinessMaterial.Parse = function (source, scene, rootUrl) {
  46741. return BABYLON.SerializationHelper.Parse(function () { return new PBRSpecularGlossinessMaterial(source.name, scene); }, source, scene, rootUrl);
  46742. };
  46743. __decorate([
  46744. BABYLON.serializeAsColor3("diffuse"),
  46745. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_albedoColor")
  46746. ], PBRSpecularGlossinessMaterial.prototype, "diffuseColor", void 0);
  46747. __decorate([
  46748. BABYLON.serializeAsTexture(),
  46749. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_albedoTexture")
  46750. ], PBRSpecularGlossinessMaterial.prototype, "diffuseTexture", void 0);
  46751. __decorate([
  46752. BABYLON.serializeAsColor3("specular"),
  46753. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_reflectivityColor")
  46754. ], PBRSpecularGlossinessMaterial.prototype, "specularColor", void 0);
  46755. __decorate([
  46756. BABYLON.serialize(),
  46757. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_microSurface")
  46758. ], PBRSpecularGlossinessMaterial.prototype, "glossiness", void 0);
  46759. __decorate([
  46760. BABYLON.serializeAsTexture(),
  46761. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_reflectivityTexture")
  46762. ], PBRSpecularGlossinessMaterial.prototype, "specularGlossinessTexture", void 0);
  46763. return PBRSpecularGlossinessMaterial;
  46764. }(BABYLON.PBRBaseSimpleMaterial));
  46765. BABYLON.PBRSpecularGlossinessMaterial = PBRSpecularGlossinessMaterial;
  46766. })(BABYLON || (BABYLON = {}));
  46767. //# sourceMappingURL=babylon.pbrSpecularGlossinessMaterial.js.map
  46768. var BABYLON;
  46769. (function (BABYLON) {
  46770. BABYLON.CameraInputTypes = {};
  46771. var CameraInputsManager = /** @class */ (function () {
  46772. function CameraInputsManager(camera) {
  46773. this.attached = {};
  46774. this.camera = camera;
  46775. this.checkInputs = function () { };
  46776. }
  46777. /**
  46778. * Add an input method to a camera.
  46779. * builtin inputs example: camera.inputs.addGamepad();
  46780. * custom inputs example: camera.inputs.add(new BABYLON.FreeCameraGamepadInput());
  46781. * @param input camera input method
  46782. */
  46783. CameraInputsManager.prototype.add = function (input) {
  46784. var type = input.getSimpleName();
  46785. if (this.attached[type]) {
  46786. BABYLON.Tools.Warn("camera input of type " + type + " already exists on camera");
  46787. return;
  46788. }
  46789. this.attached[type] = input;
  46790. input.camera = this.camera;
  46791. //for checkInputs, we are dynamically creating a function
  46792. //the goal is to avoid the performance penalty of looping for inputs in the render loop
  46793. if (input.checkInputs) {
  46794. this.checkInputs = this._addCheckInputs(input.checkInputs.bind(input));
  46795. }
  46796. if (this.attachedElement) {
  46797. input.attachControl(this.attachedElement);
  46798. }
  46799. };
  46800. /**
  46801. * Remove a specific input method from a camera
  46802. * example: camera.inputs.remove(camera.inputs.attached.mouse);
  46803. * @param inputToRemove camera input method
  46804. */
  46805. CameraInputsManager.prototype.remove = function (inputToRemove) {
  46806. for (var cam in this.attached) {
  46807. var input = this.attached[cam];
  46808. if (input === inputToRemove) {
  46809. input.detachControl(this.attachedElement);
  46810. input.camera = null;
  46811. delete this.attached[cam];
  46812. this.rebuildInputCheck();
  46813. }
  46814. }
  46815. };
  46816. CameraInputsManager.prototype.removeByType = function (inputType) {
  46817. for (var cam in this.attached) {
  46818. var input = this.attached[cam];
  46819. if (input.getClassName() === inputType) {
  46820. input.detachControl(this.attachedElement);
  46821. input.camera = null;
  46822. delete this.attached[cam];
  46823. this.rebuildInputCheck();
  46824. }
  46825. }
  46826. };
  46827. CameraInputsManager.prototype._addCheckInputs = function (fn) {
  46828. var current = this.checkInputs;
  46829. return function () {
  46830. current();
  46831. fn();
  46832. };
  46833. };
  46834. CameraInputsManager.prototype.attachInput = function (input) {
  46835. if (this.attachedElement) {
  46836. input.attachControl(this.attachedElement, this.noPreventDefault);
  46837. }
  46838. };
  46839. CameraInputsManager.prototype.attachElement = function (element, noPreventDefault) {
  46840. if (noPreventDefault === void 0) { noPreventDefault = false; }
  46841. if (this.attachedElement) {
  46842. return;
  46843. }
  46844. noPreventDefault = BABYLON.Camera.ForceAttachControlToAlwaysPreventDefault ? false : noPreventDefault;
  46845. this.attachedElement = element;
  46846. this.noPreventDefault = noPreventDefault;
  46847. for (var cam in this.attached) {
  46848. this.attached[cam].attachControl(element, noPreventDefault);
  46849. }
  46850. };
  46851. CameraInputsManager.prototype.detachElement = function (element, disconnect) {
  46852. if (disconnect === void 0) { disconnect = false; }
  46853. if (this.attachedElement !== element) {
  46854. return;
  46855. }
  46856. for (var cam in this.attached) {
  46857. this.attached[cam].detachControl(element);
  46858. if (disconnect) {
  46859. this.attached[cam].camera = null;
  46860. }
  46861. }
  46862. this.attachedElement = null;
  46863. };
  46864. CameraInputsManager.prototype.rebuildInputCheck = function () {
  46865. this.checkInputs = function () { };
  46866. for (var cam in this.attached) {
  46867. var input = this.attached[cam];
  46868. if (input.checkInputs) {
  46869. this.checkInputs = this._addCheckInputs(input.checkInputs.bind(input));
  46870. }
  46871. }
  46872. };
  46873. /**
  46874. * Remove all attached input methods from a camera
  46875. */
  46876. CameraInputsManager.prototype.clear = function () {
  46877. if (this.attachedElement) {
  46878. this.detachElement(this.attachedElement, true);
  46879. }
  46880. this.attached = {};
  46881. this.attachedElement = null;
  46882. this.checkInputs = function () { };
  46883. };
  46884. CameraInputsManager.prototype.serialize = function (serializedCamera) {
  46885. var inputs = {};
  46886. for (var cam in this.attached) {
  46887. var input = this.attached[cam];
  46888. var res = BABYLON.SerializationHelper.Serialize(input);
  46889. inputs[input.getClassName()] = res;
  46890. }
  46891. serializedCamera.inputsmgr = inputs;
  46892. };
  46893. CameraInputsManager.prototype.parse = function (parsedCamera) {
  46894. var parsedInputs = parsedCamera.inputsmgr;
  46895. if (parsedInputs) {
  46896. this.clear();
  46897. for (var n in parsedInputs) {
  46898. var construct = BABYLON.CameraInputTypes[n];
  46899. if (construct) {
  46900. var parsedinput = parsedInputs[n];
  46901. var input = BABYLON.SerializationHelper.Parse(function () { return new construct(); }, parsedinput, null);
  46902. this.add(input);
  46903. }
  46904. }
  46905. }
  46906. else {
  46907. //2016-03-08 this part is for managing backward compatibility
  46908. for (var n in this.attached) {
  46909. var construct = BABYLON.CameraInputTypes[this.attached[n].getClassName()];
  46910. if (construct) {
  46911. var input = BABYLON.SerializationHelper.Parse(function () { return new construct(); }, parsedCamera, null);
  46912. this.remove(this.attached[n]);
  46913. this.add(input);
  46914. }
  46915. }
  46916. }
  46917. };
  46918. return CameraInputsManager;
  46919. }());
  46920. BABYLON.CameraInputsManager = CameraInputsManager;
  46921. })(BABYLON || (BABYLON = {}));
  46922. //# sourceMappingURL=babylon.cameraInputsManager.js.map
  46923. var BABYLON;
  46924. (function (BABYLON) {
  46925. var TargetCamera = /** @class */ (function (_super) {
  46926. __extends(TargetCamera, _super);
  46927. function TargetCamera(name, position, scene, setActiveOnSceneIfNoneActive) {
  46928. if (setActiveOnSceneIfNoneActive === void 0) { setActiveOnSceneIfNoneActive = true; }
  46929. var _this = _super.call(this, name, position, scene, setActiveOnSceneIfNoneActive) || this;
  46930. _this.cameraDirection = new BABYLON.Vector3(0, 0, 0);
  46931. _this.cameraRotation = new BABYLON.Vector2(0, 0);
  46932. _this.rotation = new BABYLON.Vector3(0, 0, 0);
  46933. _this.speed = 2.0;
  46934. _this.noRotationConstraint = false;
  46935. _this.lockedTarget = null;
  46936. _this._currentTarget = BABYLON.Vector3.Zero();
  46937. _this._viewMatrix = BABYLON.Matrix.Zero();
  46938. _this._camMatrix = BABYLON.Matrix.Zero();
  46939. _this._cameraTransformMatrix = BABYLON.Matrix.Zero();
  46940. _this._cameraRotationMatrix = BABYLON.Matrix.Zero();
  46941. _this._referencePoint = new BABYLON.Vector3(0, 0, 1);
  46942. _this._currentUpVector = new BABYLON.Vector3(0, 1, 0);
  46943. _this._transformedReferencePoint = BABYLON.Vector3.Zero();
  46944. _this._globalCurrentTarget = BABYLON.Vector3.Zero();
  46945. _this._globalCurrentUpVector = BABYLON.Vector3.Zero();
  46946. return _this;
  46947. }
  46948. TargetCamera.prototype.getFrontPosition = function (distance) {
  46949. this.getWorldMatrix();
  46950. var direction = this.getTarget().subtract(this.position);
  46951. direction.normalize();
  46952. direction.scaleInPlace(distance);
  46953. return this.globalPosition.add(direction);
  46954. };
  46955. TargetCamera.prototype._getLockedTargetPosition = function () {
  46956. if (!this.lockedTarget) {
  46957. return null;
  46958. }
  46959. if (this.lockedTarget.absolutePosition) {
  46960. this.lockedTarget.computeWorldMatrix();
  46961. }
  46962. return this.lockedTarget.absolutePosition || this.lockedTarget;
  46963. };
  46964. TargetCamera.prototype.storeState = function () {
  46965. this._storedPosition = this.position.clone();
  46966. this._storedRotation = this.rotation.clone();
  46967. if (this.rotationQuaternion) {
  46968. this._storedRotationQuaternion = this.rotationQuaternion.clone();
  46969. }
  46970. return _super.prototype.storeState.call(this);
  46971. };
  46972. /**
  46973. * Restored camera state. You must call storeState() first
  46974. */
  46975. TargetCamera.prototype._restoreStateValues = function () {
  46976. if (!_super.prototype._restoreStateValues.call(this)) {
  46977. return false;
  46978. }
  46979. this.position = this._storedPosition.clone();
  46980. this.rotation = this._storedRotation.clone();
  46981. if (this.rotationQuaternion) {
  46982. this.rotationQuaternion = this._storedRotationQuaternion.clone();
  46983. }
  46984. this.cameraDirection.copyFromFloats(0, 0, 0);
  46985. this.cameraRotation.copyFromFloats(0, 0);
  46986. return true;
  46987. };
  46988. // Cache
  46989. TargetCamera.prototype._initCache = function () {
  46990. _super.prototype._initCache.call(this);
  46991. this._cache.lockedTarget = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  46992. this._cache.rotation = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  46993. this._cache.rotationQuaternion = new BABYLON.Quaternion(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  46994. };
  46995. TargetCamera.prototype._updateCache = function (ignoreParentClass) {
  46996. if (!ignoreParentClass) {
  46997. _super.prototype._updateCache.call(this);
  46998. }
  46999. var lockedTargetPosition = this._getLockedTargetPosition();
  47000. if (!lockedTargetPosition) {
  47001. this._cache.lockedTarget = null;
  47002. }
  47003. else {
  47004. if (!this._cache.lockedTarget) {
  47005. this._cache.lockedTarget = lockedTargetPosition.clone();
  47006. }
  47007. else {
  47008. this._cache.lockedTarget.copyFrom(lockedTargetPosition);
  47009. }
  47010. }
  47011. this._cache.rotation.copyFrom(this.rotation);
  47012. if (this.rotationQuaternion)
  47013. this._cache.rotationQuaternion.copyFrom(this.rotationQuaternion);
  47014. };
  47015. // Synchronized
  47016. TargetCamera.prototype._isSynchronizedViewMatrix = function () {
  47017. if (!_super.prototype._isSynchronizedViewMatrix.call(this)) {
  47018. return false;
  47019. }
  47020. var lockedTargetPosition = this._getLockedTargetPosition();
  47021. return (this._cache.lockedTarget ? this._cache.lockedTarget.equals(lockedTargetPosition) : !lockedTargetPosition)
  47022. && (this.rotationQuaternion ? this.rotationQuaternion.equals(this._cache.rotationQuaternion) : this._cache.rotation.equals(this.rotation));
  47023. };
  47024. // Methods
  47025. TargetCamera.prototype._computeLocalCameraSpeed = function () {
  47026. var engine = this.getEngine();
  47027. return this.speed * Math.sqrt((engine.getDeltaTime() / (engine.getFps() * 100.0)));
  47028. };
  47029. // Target
  47030. TargetCamera.prototype.setTarget = function (target) {
  47031. this.upVector.normalize();
  47032. BABYLON.Matrix.LookAtLHToRef(this.position, target, this.upVector, this._camMatrix);
  47033. this._camMatrix.invert();
  47034. this.rotation.x = Math.atan(this._camMatrix.m[6] / this._camMatrix.m[10]);
  47035. var vDir = target.subtract(this.position);
  47036. if (vDir.x >= 0.0) {
  47037. this.rotation.y = (-Math.atan(vDir.z / vDir.x) + Math.PI / 2.0);
  47038. }
  47039. else {
  47040. this.rotation.y = (-Math.atan(vDir.z / vDir.x) - Math.PI / 2.0);
  47041. }
  47042. this.rotation.z = 0;
  47043. if (isNaN(this.rotation.x)) {
  47044. this.rotation.x = 0;
  47045. }
  47046. if (isNaN(this.rotation.y)) {
  47047. this.rotation.y = 0;
  47048. }
  47049. if (isNaN(this.rotation.z)) {
  47050. this.rotation.z = 0;
  47051. }
  47052. if (this.rotationQuaternion) {
  47053. BABYLON.Quaternion.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this.rotationQuaternion);
  47054. }
  47055. };
  47056. /**
  47057. * Return the current target position of the camera. This value is expressed in local space.
  47058. */
  47059. TargetCamera.prototype.getTarget = function () {
  47060. return this._currentTarget;
  47061. };
  47062. TargetCamera.prototype._decideIfNeedsToMove = function () {
  47063. return Math.abs(this.cameraDirection.x) > 0 || Math.abs(this.cameraDirection.y) > 0 || Math.abs(this.cameraDirection.z) > 0;
  47064. };
  47065. TargetCamera.prototype._updatePosition = function () {
  47066. if (this.parent) {
  47067. this.parent.getWorldMatrix().invertToRef(BABYLON.Tmp.Matrix[0]);
  47068. BABYLON.Vector3.TransformNormalToRef(this.cameraDirection, BABYLON.Tmp.Matrix[0], BABYLON.Tmp.Vector3[0]);
  47069. this.position.addInPlace(BABYLON.Tmp.Vector3[0]);
  47070. return;
  47071. }
  47072. this.position.addInPlace(this.cameraDirection);
  47073. };
  47074. TargetCamera.prototype._checkInputs = function () {
  47075. var needToMove = this._decideIfNeedsToMove();
  47076. var needToRotate = Math.abs(this.cameraRotation.x) > 0 || Math.abs(this.cameraRotation.y) > 0;
  47077. // Move
  47078. if (needToMove) {
  47079. this._updatePosition();
  47080. }
  47081. // Rotate
  47082. if (needToRotate) {
  47083. this.rotation.x += this.cameraRotation.x;
  47084. this.rotation.y += this.cameraRotation.y;
  47085. //rotate, if quaternion is set and rotation was used
  47086. if (this.rotationQuaternion) {
  47087. var len = this.rotation.lengthSquared();
  47088. if (len) {
  47089. BABYLON.Quaternion.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this.rotationQuaternion);
  47090. }
  47091. }
  47092. if (!this.noRotationConstraint) {
  47093. var limit = (Math.PI / 2) * 0.95;
  47094. if (this.rotation.x > limit)
  47095. this.rotation.x = limit;
  47096. if (this.rotation.x < -limit)
  47097. this.rotation.x = -limit;
  47098. }
  47099. }
  47100. // Inertia
  47101. if (needToMove) {
  47102. if (Math.abs(this.cameraDirection.x) < this.speed * BABYLON.Epsilon) {
  47103. this.cameraDirection.x = 0;
  47104. }
  47105. if (Math.abs(this.cameraDirection.y) < this.speed * BABYLON.Epsilon) {
  47106. this.cameraDirection.y = 0;
  47107. }
  47108. if (Math.abs(this.cameraDirection.z) < this.speed * BABYLON.Epsilon) {
  47109. this.cameraDirection.z = 0;
  47110. }
  47111. this.cameraDirection.scaleInPlace(this.inertia);
  47112. }
  47113. if (needToRotate) {
  47114. if (Math.abs(this.cameraRotation.x) < this.speed * BABYLON.Epsilon) {
  47115. this.cameraRotation.x = 0;
  47116. }
  47117. if (Math.abs(this.cameraRotation.y) < this.speed * BABYLON.Epsilon) {
  47118. this.cameraRotation.y = 0;
  47119. }
  47120. this.cameraRotation.scaleInPlace(this.inertia);
  47121. }
  47122. _super.prototype._checkInputs.call(this);
  47123. };
  47124. TargetCamera.prototype._updateCameraRotationMatrix = function () {
  47125. if (this.rotationQuaternion) {
  47126. this.rotationQuaternion.toRotationMatrix(this._cameraRotationMatrix);
  47127. }
  47128. else {
  47129. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this._cameraRotationMatrix);
  47130. }
  47131. //update the up vector!
  47132. BABYLON.Vector3.TransformNormalToRef(this.upVector, this._cameraRotationMatrix, this._currentUpVector);
  47133. };
  47134. TargetCamera.prototype._getViewMatrix = function () {
  47135. if (this.lockedTarget) {
  47136. this.setTarget(this._getLockedTargetPosition());
  47137. }
  47138. // Compute
  47139. this._updateCameraRotationMatrix();
  47140. BABYLON.Vector3.TransformCoordinatesToRef(this._referencePoint, this._cameraRotationMatrix, this._transformedReferencePoint);
  47141. // Computing target and final matrix
  47142. this.position.addToRef(this._transformedReferencePoint, this._currentTarget);
  47143. this._computeViewMatrix(this.position, this._currentTarget, this._currentUpVector);
  47144. return this._viewMatrix;
  47145. };
  47146. TargetCamera.prototype._computeViewMatrix = function (position, target, up) {
  47147. if (this.parent) {
  47148. var parentWorldMatrix = this.parent.getWorldMatrix();
  47149. BABYLON.Vector3.TransformCoordinatesToRef(this.position, parentWorldMatrix, this._globalPosition);
  47150. BABYLON.Vector3.TransformCoordinatesToRef(target, parentWorldMatrix, this._globalCurrentTarget);
  47151. BABYLON.Vector3.TransformNormalToRef(up, parentWorldMatrix, this._globalCurrentUpVector);
  47152. this._markSyncedWithParent();
  47153. }
  47154. else {
  47155. this._globalPosition.copyFrom(this.position);
  47156. this._globalCurrentTarget.copyFrom(target);
  47157. this._globalCurrentUpVector.copyFrom(up);
  47158. }
  47159. if (this.getScene().useRightHandedSystem) {
  47160. BABYLON.Matrix.LookAtRHToRef(this._globalPosition, this._globalCurrentTarget, this._globalCurrentUpVector, this._viewMatrix);
  47161. }
  47162. else {
  47163. BABYLON.Matrix.LookAtLHToRef(this._globalPosition, this._globalCurrentTarget, this._globalCurrentUpVector, this._viewMatrix);
  47164. }
  47165. };
  47166. /**
  47167. * @override
  47168. * Override Camera.createRigCamera
  47169. */
  47170. TargetCamera.prototype.createRigCamera = function (name, cameraIndex) {
  47171. if (this.cameraRigMode !== BABYLON.Camera.RIG_MODE_NONE) {
  47172. var rigCamera = new TargetCamera(name, this.position.clone(), this.getScene());
  47173. if (this.cameraRigMode === BABYLON.Camera.RIG_MODE_VR || this.cameraRigMode === BABYLON.Camera.RIG_MODE_WEBVR) {
  47174. if (!this.rotationQuaternion) {
  47175. this.rotationQuaternion = new BABYLON.Quaternion();
  47176. }
  47177. rigCamera._cameraRigParams = {};
  47178. rigCamera.rotationQuaternion = new BABYLON.Quaternion();
  47179. }
  47180. return rigCamera;
  47181. }
  47182. return null;
  47183. };
  47184. /**
  47185. * @override
  47186. * Override Camera._updateRigCameras
  47187. */
  47188. TargetCamera.prototype._updateRigCameras = function () {
  47189. var camLeft = this._rigCameras[0];
  47190. var camRight = this._rigCameras[1];
  47191. switch (this.cameraRigMode) {
  47192. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  47193. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  47194. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  47195. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  47196. //provisionnaly using _cameraRigParams.stereoHalfAngle instead of calculations based on _cameraRigParams.interaxialDistance:
  47197. var leftSign = (this.cameraRigMode === BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED) ? 1 : -1;
  47198. var rightSign = (this.cameraRigMode === BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED) ? -1 : 1;
  47199. this._getRigCamPosition(this._cameraRigParams.stereoHalfAngle * leftSign, camLeft.position);
  47200. this._getRigCamPosition(this._cameraRigParams.stereoHalfAngle * rightSign, camRight.position);
  47201. camLeft.setTarget(this.getTarget());
  47202. camRight.setTarget(this.getTarget());
  47203. break;
  47204. case BABYLON.Camera.RIG_MODE_VR:
  47205. if (camLeft.rotationQuaternion) {
  47206. camLeft.rotationQuaternion.copyFrom(this.rotationQuaternion);
  47207. camRight.rotationQuaternion.copyFrom(this.rotationQuaternion);
  47208. }
  47209. else {
  47210. camLeft.rotation.copyFrom(this.rotation);
  47211. camRight.rotation.copyFrom(this.rotation);
  47212. }
  47213. camLeft.position.copyFrom(this.position);
  47214. camRight.position.copyFrom(this.position);
  47215. break;
  47216. }
  47217. _super.prototype._updateRigCameras.call(this);
  47218. };
  47219. TargetCamera.prototype._getRigCamPosition = function (halfSpace, result) {
  47220. if (!this._rigCamTransformMatrix) {
  47221. this._rigCamTransformMatrix = new BABYLON.Matrix();
  47222. }
  47223. var target = this.getTarget();
  47224. BABYLON.Matrix.Translation(-target.x, -target.y, -target.z).multiplyToRef(BABYLON.Matrix.RotationY(halfSpace), this._rigCamTransformMatrix);
  47225. this._rigCamTransformMatrix = this._rigCamTransformMatrix.multiply(BABYLON.Matrix.Translation(target.x, target.y, target.z));
  47226. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this._rigCamTransformMatrix, result);
  47227. };
  47228. TargetCamera.prototype.getClassName = function () {
  47229. return "TargetCamera";
  47230. };
  47231. __decorate([
  47232. BABYLON.serializeAsVector3()
  47233. ], TargetCamera.prototype, "rotation", void 0);
  47234. __decorate([
  47235. BABYLON.serialize()
  47236. ], TargetCamera.prototype, "speed", void 0);
  47237. __decorate([
  47238. BABYLON.serializeAsMeshReference("lockedTargetId")
  47239. ], TargetCamera.prototype, "lockedTarget", void 0);
  47240. return TargetCamera;
  47241. }(BABYLON.Camera));
  47242. BABYLON.TargetCamera = TargetCamera;
  47243. })(BABYLON || (BABYLON = {}));
  47244. //# sourceMappingURL=babylon.targetCamera.js.map
  47245. var BABYLON;
  47246. (function (BABYLON) {
  47247. var FreeCameraMouseInput = /** @class */ (function () {
  47248. function FreeCameraMouseInput(touchEnabled) {
  47249. if (touchEnabled === void 0) { touchEnabled = true; }
  47250. this.touchEnabled = touchEnabled;
  47251. this.buttons = [0, 1, 2];
  47252. this.angularSensibility = 2000.0;
  47253. this.previousPosition = null;
  47254. }
  47255. FreeCameraMouseInput.prototype.attachControl = function (element, noPreventDefault) {
  47256. var _this = this;
  47257. var engine = this.camera.getEngine();
  47258. if (!this._pointerInput) {
  47259. this._pointerInput = function (p, s) {
  47260. var evt = p.event;
  47261. if (engine.isInVRExclusivePointerMode) {
  47262. return;
  47263. }
  47264. if (!_this.touchEnabled && evt.pointerType === "touch") {
  47265. return;
  47266. }
  47267. if (p.type !== BABYLON.PointerEventTypes.POINTERMOVE && _this.buttons.indexOf(evt.button) === -1) {
  47268. return;
  47269. }
  47270. var srcElement = (evt.srcElement || evt.target);
  47271. if (p.type === BABYLON.PointerEventTypes.POINTERDOWN && srcElement) {
  47272. try {
  47273. srcElement.setPointerCapture(evt.pointerId);
  47274. }
  47275. catch (e) {
  47276. //Nothing to do with the error. Execution will continue.
  47277. }
  47278. _this.previousPosition = {
  47279. x: evt.clientX,
  47280. y: evt.clientY
  47281. };
  47282. if (!noPreventDefault) {
  47283. evt.preventDefault();
  47284. element.focus();
  47285. }
  47286. }
  47287. else if (p.type === BABYLON.PointerEventTypes.POINTERUP && srcElement) {
  47288. try {
  47289. srcElement.releasePointerCapture(evt.pointerId);
  47290. }
  47291. catch (e) {
  47292. //Nothing to do with the error.
  47293. }
  47294. _this.previousPosition = null;
  47295. if (!noPreventDefault) {
  47296. evt.preventDefault();
  47297. }
  47298. }
  47299. else if (p.type === BABYLON.PointerEventTypes.POINTERMOVE) {
  47300. if (!_this.previousPosition || engine.isPointerLock) {
  47301. return;
  47302. }
  47303. var offsetX = evt.clientX - _this.previousPosition.x;
  47304. if (_this.camera.getScene().useRightHandedSystem)
  47305. offsetX *= -1;
  47306. if (_this.camera.parent && _this.camera.parent._getWorldMatrixDeterminant() < 0)
  47307. offsetX *= -1;
  47308. _this.camera.cameraRotation.y += offsetX / _this.angularSensibility;
  47309. var offsetY = evt.clientY - _this.previousPosition.y;
  47310. _this.camera.cameraRotation.x += offsetY / _this.angularSensibility;
  47311. _this.previousPosition = {
  47312. x: evt.clientX,
  47313. y: evt.clientY
  47314. };
  47315. if (!noPreventDefault) {
  47316. evt.preventDefault();
  47317. }
  47318. }
  47319. };
  47320. }
  47321. this._onMouseMove = function (evt) {
  47322. if (!engine.isPointerLock) {
  47323. return;
  47324. }
  47325. if (engine.isInVRExclusivePointerMode) {
  47326. return;
  47327. }
  47328. var offsetX = evt.movementX || evt.mozMovementX || evt.webkitMovementX || evt.msMovementX || 0;
  47329. if (_this.camera.getScene().useRightHandedSystem)
  47330. offsetX *= -1;
  47331. if (_this.camera.parent && _this.camera.parent._getWorldMatrixDeterminant() < 0)
  47332. offsetX *= -1;
  47333. _this.camera.cameraRotation.y += offsetX / _this.angularSensibility;
  47334. var offsetY = evt.movementY || evt.mozMovementY || evt.webkitMovementY || evt.msMovementY || 0;
  47335. _this.camera.cameraRotation.x += offsetY / _this.angularSensibility;
  47336. _this.previousPosition = null;
  47337. if (!noPreventDefault) {
  47338. evt.preventDefault();
  47339. }
  47340. };
  47341. this._observer = this.camera.getScene().onPointerObservable.add(this._pointerInput, BABYLON.PointerEventTypes.POINTERDOWN | BABYLON.PointerEventTypes.POINTERUP | BABYLON.PointerEventTypes.POINTERMOVE);
  47342. element.addEventListener("mousemove", this._onMouseMove, false);
  47343. };
  47344. FreeCameraMouseInput.prototype.detachControl = function (element) {
  47345. if (this._observer && element) {
  47346. this.camera.getScene().onPointerObservable.remove(this._observer);
  47347. if (this._onMouseMove) {
  47348. element.removeEventListener("mousemove", this._onMouseMove);
  47349. }
  47350. this._observer = null;
  47351. this._onMouseMove = null;
  47352. this.previousPosition = null;
  47353. }
  47354. };
  47355. FreeCameraMouseInput.prototype.getClassName = function () {
  47356. return "FreeCameraMouseInput";
  47357. };
  47358. FreeCameraMouseInput.prototype.getSimpleName = function () {
  47359. return "mouse";
  47360. };
  47361. __decorate([
  47362. BABYLON.serialize()
  47363. ], FreeCameraMouseInput.prototype, "buttons", void 0);
  47364. __decorate([
  47365. BABYLON.serialize()
  47366. ], FreeCameraMouseInput.prototype, "angularSensibility", void 0);
  47367. return FreeCameraMouseInput;
  47368. }());
  47369. BABYLON.FreeCameraMouseInput = FreeCameraMouseInput;
  47370. BABYLON.CameraInputTypes["FreeCameraMouseInput"] = FreeCameraMouseInput;
  47371. })(BABYLON || (BABYLON = {}));
  47372. //# sourceMappingURL=babylon.freeCameraMouseInput.js.map
  47373. var BABYLON;
  47374. (function (BABYLON) {
  47375. var FreeCameraKeyboardMoveInput = /** @class */ (function () {
  47376. function FreeCameraKeyboardMoveInput() {
  47377. this._keys = new Array();
  47378. this.keysUp = [38];
  47379. this.keysDown = [40];
  47380. this.keysLeft = [37];
  47381. this.keysRight = [39];
  47382. }
  47383. FreeCameraKeyboardMoveInput.prototype.attachControl = function (element, noPreventDefault) {
  47384. var _this = this;
  47385. if (this._onCanvasBlurObserver) {
  47386. return;
  47387. }
  47388. this._scene = this.camera.getScene();
  47389. this._engine = this._scene.getEngine();
  47390. this._onCanvasBlurObserver = this._engine.onCanvasBlurObservable.add(function () {
  47391. _this._keys = [];
  47392. });
  47393. this._onKeyboardObserver = this._scene.onKeyboardObservable.add(function (info) {
  47394. var evt = info.event;
  47395. if (info.type === BABYLON.KeyboardEventTypes.KEYDOWN) {
  47396. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  47397. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  47398. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  47399. _this.keysRight.indexOf(evt.keyCode) !== -1) {
  47400. var index = _this._keys.indexOf(evt.keyCode);
  47401. if (index === -1) {
  47402. _this._keys.push(evt.keyCode);
  47403. }
  47404. if (!noPreventDefault) {
  47405. evt.preventDefault();
  47406. }
  47407. }
  47408. }
  47409. else {
  47410. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  47411. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  47412. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  47413. _this.keysRight.indexOf(evt.keyCode) !== -1) {
  47414. var index = _this._keys.indexOf(evt.keyCode);
  47415. if (index >= 0) {
  47416. _this._keys.splice(index, 1);
  47417. }
  47418. if (!noPreventDefault) {
  47419. evt.preventDefault();
  47420. }
  47421. }
  47422. }
  47423. });
  47424. };
  47425. FreeCameraKeyboardMoveInput.prototype.detachControl = function (element) {
  47426. if (this._scene) {
  47427. if (this._onKeyboardObserver) {
  47428. this._scene.onKeyboardObservable.remove(this._onKeyboardObserver);
  47429. }
  47430. if (this._onCanvasBlurObserver) {
  47431. this._engine.onCanvasBlurObservable.remove(this._onCanvasBlurObserver);
  47432. }
  47433. this._onKeyboardObserver = null;
  47434. this._onCanvasBlurObserver = null;
  47435. }
  47436. this._keys = [];
  47437. };
  47438. FreeCameraKeyboardMoveInput.prototype.checkInputs = function () {
  47439. if (this._onKeyboardObserver) {
  47440. var camera = this.camera;
  47441. // Keyboard
  47442. for (var index = 0; index < this._keys.length; index++) {
  47443. var keyCode = this._keys[index];
  47444. var speed = camera._computeLocalCameraSpeed();
  47445. if (this.keysLeft.indexOf(keyCode) !== -1) {
  47446. camera._localDirection.copyFromFloats(-speed, 0, 0);
  47447. }
  47448. else if (this.keysUp.indexOf(keyCode) !== -1) {
  47449. camera._localDirection.copyFromFloats(0, 0, speed);
  47450. }
  47451. else if (this.keysRight.indexOf(keyCode) !== -1) {
  47452. camera._localDirection.copyFromFloats(speed, 0, 0);
  47453. }
  47454. else if (this.keysDown.indexOf(keyCode) !== -1) {
  47455. camera._localDirection.copyFromFloats(0, 0, -speed);
  47456. }
  47457. if (camera.getScene().useRightHandedSystem) {
  47458. camera._localDirection.z *= -1;
  47459. }
  47460. camera.getViewMatrix().invertToRef(camera._cameraTransformMatrix);
  47461. BABYLON.Vector3.TransformNormalToRef(camera._localDirection, camera._cameraTransformMatrix, camera._transformedDirection);
  47462. camera.cameraDirection.addInPlace(camera._transformedDirection);
  47463. }
  47464. }
  47465. };
  47466. FreeCameraKeyboardMoveInput.prototype.getClassName = function () {
  47467. return "FreeCameraKeyboardMoveInput";
  47468. };
  47469. FreeCameraKeyboardMoveInput.prototype._onLostFocus = function (e) {
  47470. this._keys = [];
  47471. };
  47472. FreeCameraKeyboardMoveInput.prototype.getSimpleName = function () {
  47473. return "keyboard";
  47474. };
  47475. __decorate([
  47476. BABYLON.serialize()
  47477. ], FreeCameraKeyboardMoveInput.prototype, "keysUp", void 0);
  47478. __decorate([
  47479. BABYLON.serialize()
  47480. ], FreeCameraKeyboardMoveInput.prototype, "keysDown", void 0);
  47481. __decorate([
  47482. BABYLON.serialize()
  47483. ], FreeCameraKeyboardMoveInput.prototype, "keysLeft", void 0);
  47484. __decorate([
  47485. BABYLON.serialize()
  47486. ], FreeCameraKeyboardMoveInput.prototype, "keysRight", void 0);
  47487. return FreeCameraKeyboardMoveInput;
  47488. }());
  47489. BABYLON.FreeCameraKeyboardMoveInput = FreeCameraKeyboardMoveInput;
  47490. BABYLON.CameraInputTypes["FreeCameraKeyboardMoveInput"] = FreeCameraKeyboardMoveInput;
  47491. })(BABYLON || (BABYLON = {}));
  47492. //# sourceMappingURL=babylon.freeCameraKeyboardMoveInput.js.map
  47493. var BABYLON;
  47494. (function (BABYLON) {
  47495. var FreeCameraInputsManager = /** @class */ (function (_super) {
  47496. __extends(FreeCameraInputsManager, _super);
  47497. function FreeCameraInputsManager(camera) {
  47498. return _super.call(this, camera) || this;
  47499. }
  47500. FreeCameraInputsManager.prototype.addKeyboard = function () {
  47501. this.add(new BABYLON.FreeCameraKeyboardMoveInput());
  47502. return this;
  47503. };
  47504. FreeCameraInputsManager.prototype.addMouse = function (touchEnabled) {
  47505. if (touchEnabled === void 0) { touchEnabled = true; }
  47506. this.add(new BABYLON.FreeCameraMouseInput(touchEnabled));
  47507. return this;
  47508. };
  47509. FreeCameraInputsManager.prototype.addGamepad = function () {
  47510. this.add(new BABYLON.FreeCameraGamepadInput());
  47511. return this;
  47512. };
  47513. FreeCameraInputsManager.prototype.addDeviceOrientation = function () {
  47514. this.add(new BABYLON.FreeCameraDeviceOrientationInput());
  47515. return this;
  47516. };
  47517. FreeCameraInputsManager.prototype.addTouch = function () {
  47518. this.add(new BABYLON.FreeCameraTouchInput());
  47519. return this;
  47520. };
  47521. FreeCameraInputsManager.prototype.addVirtualJoystick = function () {
  47522. this.add(new BABYLON.FreeCameraVirtualJoystickInput());
  47523. return this;
  47524. };
  47525. return FreeCameraInputsManager;
  47526. }(BABYLON.CameraInputsManager));
  47527. BABYLON.FreeCameraInputsManager = FreeCameraInputsManager;
  47528. })(BABYLON || (BABYLON = {}));
  47529. //# sourceMappingURL=babylon.freeCameraInputsManager.js.map
  47530. var BABYLON;
  47531. (function (BABYLON) {
  47532. var FreeCamera = /** @class */ (function (_super) {
  47533. __extends(FreeCamera, _super);
  47534. function FreeCamera(name, position, scene, setActiveOnSceneIfNoneActive) {
  47535. if (setActiveOnSceneIfNoneActive === void 0) { setActiveOnSceneIfNoneActive = true; }
  47536. var _this = _super.call(this, name, position, scene, setActiveOnSceneIfNoneActive) || this;
  47537. _this.ellipsoid = new BABYLON.Vector3(0.5, 1, 0.5);
  47538. _this.ellipsoidOffset = new BABYLON.Vector3(0, 0, 0);
  47539. _this.checkCollisions = false;
  47540. _this.applyGravity = false;
  47541. _this._needMoveForGravity = false;
  47542. _this._oldPosition = BABYLON.Vector3.Zero();
  47543. _this._diffPosition = BABYLON.Vector3.Zero();
  47544. _this._newPosition = BABYLON.Vector3.Zero();
  47545. // Collisions
  47546. _this._collisionMask = -1;
  47547. _this._onCollisionPositionChange = function (collisionId, newPosition, collidedMesh) {
  47548. if (collidedMesh === void 0) { collidedMesh = null; }
  47549. //TODO move this to the collision coordinator!
  47550. if (_this.getScene().workerCollisions)
  47551. newPosition.multiplyInPlace(_this._collider._radius);
  47552. var updatePosition = function (newPos) {
  47553. _this._newPosition.copyFrom(newPos);
  47554. _this._newPosition.subtractToRef(_this._oldPosition, _this._diffPosition);
  47555. if (_this._diffPosition.length() > BABYLON.Engine.CollisionsEpsilon) {
  47556. _this.position.addInPlace(_this._diffPosition);
  47557. if (_this.onCollide && collidedMesh) {
  47558. _this.onCollide(collidedMesh);
  47559. }
  47560. }
  47561. };
  47562. updatePosition(newPosition);
  47563. };
  47564. _this.inputs = new BABYLON.FreeCameraInputsManager(_this);
  47565. _this.inputs.addKeyboard().addMouse();
  47566. return _this;
  47567. }
  47568. Object.defineProperty(FreeCamera.prototype, "angularSensibility", {
  47569. //-- begin properties for backward compatibility for inputs
  47570. /**
  47571. * Gets the input sensibility for a mouse input. (default is 2000.0)
  47572. * Higher values reduce sensitivity.
  47573. */
  47574. get: function () {
  47575. var mouse = this.inputs.attached["mouse"];
  47576. if (mouse)
  47577. return mouse.angularSensibility;
  47578. return 0;
  47579. },
  47580. /**
  47581. * Sets the input sensibility for a mouse input. (default is 2000.0)
  47582. * Higher values reduce sensitivity.
  47583. */
  47584. set: function (value) {
  47585. var mouse = this.inputs.attached["mouse"];
  47586. if (mouse)
  47587. mouse.angularSensibility = value;
  47588. },
  47589. enumerable: true,
  47590. configurable: true
  47591. });
  47592. Object.defineProperty(FreeCamera.prototype, "keysUp", {
  47593. get: function () {
  47594. var keyboard = this.inputs.attached["keyboard"];
  47595. if (keyboard)
  47596. return keyboard.keysUp;
  47597. return [];
  47598. },
  47599. set: function (value) {
  47600. var keyboard = this.inputs.attached["keyboard"];
  47601. if (keyboard)
  47602. keyboard.keysUp = value;
  47603. },
  47604. enumerable: true,
  47605. configurable: true
  47606. });
  47607. Object.defineProperty(FreeCamera.prototype, "keysDown", {
  47608. get: function () {
  47609. var keyboard = this.inputs.attached["keyboard"];
  47610. if (keyboard)
  47611. return keyboard.keysDown;
  47612. return [];
  47613. },
  47614. set: function (value) {
  47615. var keyboard = this.inputs.attached["keyboard"];
  47616. if (keyboard)
  47617. keyboard.keysDown = value;
  47618. },
  47619. enumerable: true,
  47620. configurable: true
  47621. });
  47622. Object.defineProperty(FreeCamera.prototype, "keysLeft", {
  47623. get: function () {
  47624. var keyboard = this.inputs.attached["keyboard"];
  47625. if (keyboard)
  47626. return keyboard.keysLeft;
  47627. return [];
  47628. },
  47629. set: function (value) {
  47630. var keyboard = this.inputs.attached["keyboard"];
  47631. if (keyboard)
  47632. keyboard.keysLeft = value;
  47633. },
  47634. enumerable: true,
  47635. configurable: true
  47636. });
  47637. Object.defineProperty(FreeCamera.prototype, "keysRight", {
  47638. get: function () {
  47639. var keyboard = this.inputs.attached["keyboard"];
  47640. if (keyboard)
  47641. return keyboard.keysRight;
  47642. return [];
  47643. },
  47644. set: function (value) {
  47645. var keyboard = this.inputs.attached["keyboard"];
  47646. if (keyboard)
  47647. keyboard.keysRight = value;
  47648. },
  47649. enumerable: true,
  47650. configurable: true
  47651. });
  47652. // Controls
  47653. FreeCamera.prototype.attachControl = function (element, noPreventDefault) {
  47654. this.inputs.attachElement(element, noPreventDefault);
  47655. };
  47656. FreeCamera.prototype.detachControl = function (element) {
  47657. this.inputs.detachElement(element);
  47658. this.cameraDirection = new BABYLON.Vector3(0, 0, 0);
  47659. this.cameraRotation = new BABYLON.Vector2(0, 0);
  47660. };
  47661. Object.defineProperty(FreeCamera.prototype, "collisionMask", {
  47662. get: function () {
  47663. return this._collisionMask;
  47664. },
  47665. set: function (mask) {
  47666. this._collisionMask = !isNaN(mask) ? mask : -1;
  47667. },
  47668. enumerable: true,
  47669. configurable: true
  47670. });
  47671. FreeCamera.prototype._collideWithWorld = function (displacement) {
  47672. var globalPosition;
  47673. if (this.parent) {
  47674. globalPosition = BABYLON.Vector3.TransformCoordinates(this.position, this.parent.getWorldMatrix());
  47675. }
  47676. else {
  47677. globalPosition = this.position;
  47678. }
  47679. globalPosition.subtractFromFloatsToRef(0, this.ellipsoid.y, 0, this._oldPosition);
  47680. this._oldPosition.addInPlace(this.ellipsoidOffset);
  47681. if (!this._collider) {
  47682. this._collider = new BABYLON.Collider();
  47683. }
  47684. this._collider._radius = this.ellipsoid;
  47685. this._collider.collisionMask = this._collisionMask;
  47686. //no need for clone, as long as gravity is not on.
  47687. var actualDisplacement = displacement;
  47688. //add gravity to the direction to prevent the dual-collision checking
  47689. if (this.applyGravity) {
  47690. //this prevents mending with cameraDirection, a global variable of the free camera class.
  47691. actualDisplacement = displacement.add(this.getScene().gravity);
  47692. }
  47693. this.getScene().collisionCoordinator.getNewPosition(this._oldPosition, actualDisplacement, this._collider, 3, null, this._onCollisionPositionChange, this.uniqueId);
  47694. };
  47695. FreeCamera.prototype._checkInputs = function () {
  47696. if (!this._localDirection) {
  47697. this._localDirection = BABYLON.Vector3.Zero();
  47698. this._transformedDirection = BABYLON.Vector3.Zero();
  47699. }
  47700. this.inputs.checkInputs();
  47701. _super.prototype._checkInputs.call(this);
  47702. };
  47703. FreeCamera.prototype._decideIfNeedsToMove = function () {
  47704. return this._needMoveForGravity || Math.abs(this.cameraDirection.x) > 0 || Math.abs(this.cameraDirection.y) > 0 || Math.abs(this.cameraDirection.z) > 0;
  47705. };
  47706. FreeCamera.prototype._updatePosition = function () {
  47707. if (this.checkCollisions && this.getScene().collisionsEnabled) {
  47708. this._collideWithWorld(this.cameraDirection);
  47709. }
  47710. else {
  47711. _super.prototype._updatePosition.call(this);
  47712. }
  47713. };
  47714. FreeCamera.prototype.dispose = function () {
  47715. this.inputs.clear();
  47716. _super.prototype.dispose.call(this);
  47717. };
  47718. FreeCamera.prototype.getClassName = function () {
  47719. return "FreeCamera";
  47720. };
  47721. __decorate([
  47722. BABYLON.serializeAsVector3()
  47723. ], FreeCamera.prototype, "ellipsoid", void 0);
  47724. __decorate([
  47725. BABYLON.serializeAsVector3()
  47726. ], FreeCamera.prototype, "ellipsoidOffset", void 0);
  47727. __decorate([
  47728. BABYLON.serialize()
  47729. ], FreeCamera.prototype, "checkCollisions", void 0);
  47730. __decorate([
  47731. BABYLON.serialize()
  47732. ], FreeCamera.prototype, "applyGravity", void 0);
  47733. return FreeCamera;
  47734. }(BABYLON.TargetCamera));
  47735. BABYLON.FreeCamera = FreeCamera;
  47736. })(BABYLON || (BABYLON = {}));
  47737. //# sourceMappingURL=babylon.freeCamera.js.map
  47738. var BABYLON;
  47739. (function (BABYLON) {
  47740. var ArcRotateCameraKeyboardMoveInput = /** @class */ (function () {
  47741. function ArcRotateCameraKeyboardMoveInput() {
  47742. this._keys = new Array();
  47743. this.keysUp = [38];
  47744. this.keysDown = [40];
  47745. this.keysLeft = [37];
  47746. this.keysRight = [39];
  47747. this.keysReset = [220];
  47748. this.panningSensibility = 50.0;
  47749. this.zoomingSensibility = 25.0;
  47750. this.useAltToZoom = true;
  47751. }
  47752. ArcRotateCameraKeyboardMoveInput.prototype.attachControl = function (element, noPreventDefault) {
  47753. var _this = this;
  47754. if (this._onCanvasBlurObserver) {
  47755. return;
  47756. }
  47757. this._scene = this.camera.getScene();
  47758. this._engine = this._scene.getEngine();
  47759. this._onCanvasBlurObserver = this._engine.onCanvasBlurObservable.add(function () {
  47760. _this._keys = [];
  47761. });
  47762. this._onKeyboardObserver = this._scene.onKeyboardObservable.add(function (info) {
  47763. var evt = info.event;
  47764. if (info.type === BABYLON.KeyboardEventTypes.KEYDOWN) {
  47765. _this._ctrlPressed = evt.ctrlKey;
  47766. _this._altPressed = evt.altKey;
  47767. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  47768. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  47769. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  47770. _this.keysRight.indexOf(evt.keyCode) !== -1 ||
  47771. _this.keysReset.indexOf(evt.keyCode) !== -1) {
  47772. var index = _this._keys.indexOf(evt.keyCode);
  47773. if (index === -1) {
  47774. _this._keys.push(evt.keyCode);
  47775. }
  47776. if (evt.preventDefault) {
  47777. if (!noPreventDefault) {
  47778. evt.preventDefault();
  47779. }
  47780. }
  47781. }
  47782. }
  47783. else {
  47784. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  47785. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  47786. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  47787. _this.keysRight.indexOf(evt.keyCode) !== -1 ||
  47788. _this.keysReset.indexOf(evt.keyCode) !== -1) {
  47789. var index = _this._keys.indexOf(evt.keyCode);
  47790. if (index >= 0) {
  47791. _this._keys.splice(index, 1);
  47792. }
  47793. if (evt.preventDefault) {
  47794. if (!noPreventDefault) {
  47795. evt.preventDefault();
  47796. }
  47797. }
  47798. }
  47799. }
  47800. });
  47801. };
  47802. ArcRotateCameraKeyboardMoveInput.prototype.detachControl = function (element) {
  47803. if (this._scene) {
  47804. if (this._onKeyboardObserver) {
  47805. this._scene.onKeyboardObservable.remove(this._onKeyboardObserver);
  47806. }
  47807. if (this._onCanvasBlurObserver) {
  47808. this._engine.onCanvasBlurObservable.remove(this._onCanvasBlurObserver);
  47809. }
  47810. this._onKeyboardObserver = null;
  47811. this._onCanvasBlurObserver = null;
  47812. }
  47813. this._keys = [];
  47814. };
  47815. ArcRotateCameraKeyboardMoveInput.prototype.checkInputs = function () {
  47816. if (this._onKeyboardObserver) {
  47817. var camera = this.camera;
  47818. for (var index = 0; index < this._keys.length; index++) {
  47819. var keyCode = this._keys[index];
  47820. if (this.keysLeft.indexOf(keyCode) !== -1) {
  47821. if (this._ctrlPressed && this.camera._useCtrlForPanning) {
  47822. camera.inertialPanningX -= 1 / this.panningSensibility;
  47823. }
  47824. else {
  47825. camera.inertialAlphaOffset -= 0.01;
  47826. }
  47827. }
  47828. else if (this.keysUp.indexOf(keyCode) !== -1) {
  47829. if (this._ctrlPressed && this.camera._useCtrlForPanning) {
  47830. camera.inertialPanningY += 1 / this.panningSensibility;
  47831. }
  47832. else if (this._altPressed && this.useAltToZoom) {
  47833. camera.inertialRadiusOffset += 1 / this.zoomingSensibility;
  47834. }
  47835. else {
  47836. camera.inertialBetaOffset -= 0.01;
  47837. }
  47838. }
  47839. else if (this.keysRight.indexOf(keyCode) !== -1) {
  47840. if (this._ctrlPressed && this.camera._useCtrlForPanning) {
  47841. camera.inertialPanningX += 1 / this.panningSensibility;
  47842. }
  47843. else {
  47844. camera.inertialAlphaOffset += 0.01;
  47845. }
  47846. }
  47847. else if (this.keysDown.indexOf(keyCode) !== -1) {
  47848. if (this._ctrlPressed && this.camera._useCtrlForPanning) {
  47849. camera.inertialPanningY -= 1 / this.panningSensibility;
  47850. }
  47851. else if (this._altPressed && this.useAltToZoom) {
  47852. camera.inertialRadiusOffset -= 1 / this.zoomingSensibility;
  47853. }
  47854. else {
  47855. camera.inertialBetaOffset += 0.01;
  47856. }
  47857. }
  47858. else if (this.keysReset.indexOf(keyCode) !== -1) {
  47859. camera.restoreState();
  47860. }
  47861. }
  47862. }
  47863. };
  47864. ArcRotateCameraKeyboardMoveInput.prototype.getClassName = function () {
  47865. return "ArcRotateCameraKeyboardMoveInput";
  47866. };
  47867. ArcRotateCameraKeyboardMoveInput.prototype.getSimpleName = function () {
  47868. return "keyboard";
  47869. };
  47870. __decorate([
  47871. BABYLON.serialize()
  47872. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysUp", void 0);
  47873. __decorate([
  47874. BABYLON.serialize()
  47875. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysDown", void 0);
  47876. __decorate([
  47877. BABYLON.serialize()
  47878. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysLeft", void 0);
  47879. __decorate([
  47880. BABYLON.serialize()
  47881. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysRight", void 0);
  47882. __decorate([
  47883. BABYLON.serialize()
  47884. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysReset", void 0);
  47885. __decorate([
  47886. BABYLON.serialize()
  47887. ], ArcRotateCameraKeyboardMoveInput.prototype, "panningSensibility", void 0);
  47888. __decorate([
  47889. BABYLON.serialize()
  47890. ], ArcRotateCameraKeyboardMoveInput.prototype, "zoomingSensibility", void 0);
  47891. __decorate([
  47892. BABYLON.serialize()
  47893. ], ArcRotateCameraKeyboardMoveInput.prototype, "useAltToZoom", void 0);
  47894. return ArcRotateCameraKeyboardMoveInput;
  47895. }());
  47896. BABYLON.ArcRotateCameraKeyboardMoveInput = ArcRotateCameraKeyboardMoveInput;
  47897. BABYLON.CameraInputTypes["ArcRotateCameraKeyboardMoveInput"] = ArcRotateCameraKeyboardMoveInput;
  47898. })(BABYLON || (BABYLON = {}));
  47899. //# sourceMappingURL=babylon.arcRotateCameraKeyboardMoveInput.js.map
  47900. var BABYLON;
  47901. (function (BABYLON) {
  47902. var ArcRotateCameraMouseWheelInput = /** @class */ (function () {
  47903. function ArcRotateCameraMouseWheelInput() {
  47904. this.wheelPrecision = 3.0;
  47905. /**
  47906. * wheelDeltaPercentage will be used instead of wheelPrecision if different from 0.
  47907. * It defines the percentage of current camera.radius to use as delta when wheel is used.
  47908. */
  47909. this.wheelDeltaPercentage = 0;
  47910. }
  47911. ArcRotateCameraMouseWheelInput.prototype.attachControl = function (element, noPreventDefault) {
  47912. var _this = this;
  47913. this._wheel = function (p, s) {
  47914. //sanity check - this should be a PointerWheel event.
  47915. if (p.type !== BABYLON.PointerEventTypes.POINTERWHEEL)
  47916. return;
  47917. var event = p.event;
  47918. var delta = 0;
  47919. if (event.wheelDelta) {
  47920. if (_this.wheelDeltaPercentage) {
  47921. var wheelDelta = (event.wheelDelta * 0.01 * _this.wheelDeltaPercentage) * _this.camera.radius;
  47922. if (event.wheelDelta > 0) {
  47923. delta = wheelDelta / (1.0 + _this.wheelDeltaPercentage);
  47924. }
  47925. else {
  47926. delta = wheelDelta * (1.0 + _this.wheelDeltaPercentage);
  47927. }
  47928. }
  47929. else {
  47930. delta = event.wheelDelta / (_this.wheelPrecision * 40);
  47931. }
  47932. }
  47933. else if (event.detail) {
  47934. delta = -event.detail / _this.wheelPrecision;
  47935. }
  47936. if (delta)
  47937. _this.camera.inertialRadiusOffset += delta;
  47938. if (event.preventDefault) {
  47939. if (!noPreventDefault) {
  47940. event.preventDefault();
  47941. }
  47942. }
  47943. };
  47944. this._observer = this.camera.getScene().onPointerObservable.add(this._wheel, BABYLON.PointerEventTypes.POINTERWHEEL);
  47945. };
  47946. ArcRotateCameraMouseWheelInput.prototype.detachControl = function (element) {
  47947. if (this._observer && element) {
  47948. this.camera.getScene().onPointerObservable.remove(this._observer);
  47949. this._observer = null;
  47950. this._wheel = null;
  47951. }
  47952. };
  47953. ArcRotateCameraMouseWheelInput.prototype.getClassName = function () {
  47954. return "ArcRotateCameraMouseWheelInput";
  47955. };
  47956. ArcRotateCameraMouseWheelInput.prototype.getSimpleName = function () {
  47957. return "mousewheel";
  47958. };
  47959. __decorate([
  47960. BABYLON.serialize()
  47961. ], ArcRotateCameraMouseWheelInput.prototype, "wheelPrecision", void 0);
  47962. __decorate([
  47963. BABYLON.serialize()
  47964. ], ArcRotateCameraMouseWheelInput.prototype, "wheelDeltaPercentage", void 0);
  47965. return ArcRotateCameraMouseWheelInput;
  47966. }());
  47967. BABYLON.ArcRotateCameraMouseWheelInput = ArcRotateCameraMouseWheelInput;
  47968. BABYLON.CameraInputTypes["ArcRotateCameraMouseWheelInput"] = ArcRotateCameraMouseWheelInput;
  47969. })(BABYLON || (BABYLON = {}));
  47970. //# sourceMappingURL=babylon.arcRotateCameraMouseWheelInput.js.map
  47971. var BABYLON;
  47972. (function (BABYLON) {
  47973. var ArcRotateCameraPointersInput = /** @class */ (function () {
  47974. function ArcRotateCameraPointersInput() {
  47975. this.buttons = [0, 1, 2];
  47976. this.angularSensibilityX = 1000.0;
  47977. this.angularSensibilityY = 1000.0;
  47978. this.pinchPrecision = 12.0;
  47979. /**
  47980. * pinchDeltaPercentage will be used instead of pinchPrecision if different from 0.
  47981. * It defines the percentage of current camera.radius to use as delta when pinch zoom is used.
  47982. */
  47983. this.pinchDeltaPercentage = 0;
  47984. this.panningSensibility = 1000.0;
  47985. this.multiTouchPanning = true;
  47986. this.multiTouchPanAndZoom = true;
  47987. this._isPanClick = false;
  47988. this.pinchInwards = true;
  47989. }
  47990. ArcRotateCameraPointersInput.prototype.attachControl = function (element, noPreventDefault) {
  47991. var _this = this;
  47992. var engine = this.camera.getEngine();
  47993. var cacheSoloPointer; // cache pointer object for better perf on camera rotation
  47994. var pointA = null;
  47995. var pointB = null;
  47996. var previousPinchSquaredDistance = 0;
  47997. var initialDistance = 0;
  47998. var twoFingerActivityCount = 0;
  47999. var previousMultiTouchPanPosition = { x: 0, y: 0, isPaning: false, isPinching: false };
  48000. this._pointerInput = function (p, s) {
  48001. var evt = p.event;
  48002. var isTouch = p.event.pointerType === "touch";
  48003. if (engine.isInVRExclusivePointerMode) {
  48004. return;
  48005. }
  48006. if (p.type !== BABYLON.PointerEventTypes.POINTERMOVE && _this.buttons.indexOf(evt.button) === -1) {
  48007. return;
  48008. }
  48009. var srcElement = (evt.srcElement || evt.target);
  48010. if (p.type === BABYLON.PointerEventTypes.POINTERDOWN && srcElement) {
  48011. try {
  48012. srcElement.setPointerCapture(evt.pointerId);
  48013. }
  48014. catch (e) {
  48015. //Nothing to do with the error. Execution will continue.
  48016. }
  48017. // Manage panning with pan button click
  48018. _this._isPanClick = evt.button === _this.camera._panningMouseButton;
  48019. // manage pointers
  48020. cacheSoloPointer = { x: evt.clientX, y: evt.clientY, pointerId: evt.pointerId, type: evt.pointerType };
  48021. if (pointA === null) {
  48022. pointA = cacheSoloPointer;
  48023. }
  48024. else if (pointB === null) {
  48025. pointB = cacheSoloPointer;
  48026. }
  48027. if (!noPreventDefault) {
  48028. evt.preventDefault();
  48029. element.focus();
  48030. }
  48031. }
  48032. else if (p.type === BABYLON.PointerEventTypes.POINTERDOUBLETAP) {
  48033. _this.camera.restoreState();
  48034. }
  48035. else if (p.type === BABYLON.PointerEventTypes.POINTERUP && srcElement) {
  48036. try {
  48037. srcElement.releasePointerCapture(evt.pointerId);
  48038. }
  48039. catch (e) {
  48040. //Nothing to do with the error.
  48041. }
  48042. cacheSoloPointer = null;
  48043. previousPinchSquaredDistance = 0;
  48044. previousMultiTouchPanPosition.isPaning = false;
  48045. previousMultiTouchPanPosition.isPinching = false;
  48046. twoFingerActivityCount = 0;
  48047. initialDistance = 0;
  48048. if (!isTouch) {
  48049. pointB = null; // Mouse and pen are mono pointer
  48050. }
  48051. //would be better to use pointers.remove(evt.pointerId) for multitouch gestures,
  48052. //but emptying completly pointers collection is required to fix a bug on iPhone :
  48053. //when changing orientation while pinching camera, one pointer stay pressed forever if we don't release all pointers
  48054. //will be ok to put back pointers.remove(evt.pointerId); when iPhone bug corrected
  48055. if (engine._badOS) {
  48056. pointA = pointB = null;
  48057. }
  48058. else {
  48059. //only remove the impacted pointer in case of multitouch allowing on most
  48060. //platforms switching from rotate to zoom and pan seamlessly.
  48061. if (pointB && pointA && pointA.pointerId == evt.pointerId) {
  48062. pointA = pointB;
  48063. pointB = null;
  48064. cacheSoloPointer = { x: pointA.x, y: pointA.y, pointerId: pointA.pointerId, type: evt.pointerType };
  48065. }
  48066. else if (pointA && pointB && pointB.pointerId == evt.pointerId) {
  48067. pointB = null;
  48068. cacheSoloPointer = { x: pointA.x, y: pointA.y, pointerId: pointA.pointerId, type: evt.pointerType };
  48069. }
  48070. else {
  48071. pointA = pointB = null;
  48072. }
  48073. }
  48074. if (!noPreventDefault) {
  48075. evt.preventDefault();
  48076. }
  48077. }
  48078. else if (p.type === BABYLON.PointerEventTypes.POINTERMOVE) {
  48079. if (!noPreventDefault) {
  48080. evt.preventDefault();
  48081. }
  48082. // One button down
  48083. if (pointA && pointB === null && cacheSoloPointer) {
  48084. if (_this.panningSensibility !== 0 &&
  48085. ((evt.ctrlKey && _this.camera._useCtrlForPanning) || _this._isPanClick)) {
  48086. _this.camera.inertialPanningX += -(evt.clientX - cacheSoloPointer.x) / _this.panningSensibility;
  48087. _this.camera.inertialPanningY += (evt.clientY - cacheSoloPointer.y) / _this.panningSensibility;
  48088. }
  48089. else {
  48090. var offsetX = evt.clientX - cacheSoloPointer.x;
  48091. var offsetY = evt.clientY - cacheSoloPointer.y;
  48092. _this.camera.inertialAlphaOffset -= offsetX / _this.angularSensibilityX;
  48093. _this.camera.inertialBetaOffset -= offsetY / _this.angularSensibilityY;
  48094. }
  48095. cacheSoloPointer.x = evt.clientX;
  48096. cacheSoloPointer.y = evt.clientY;
  48097. }
  48098. // Two buttons down: pinch/pan
  48099. else if (pointA && pointB) {
  48100. //if (noPreventDefault) { evt.preventDefault(); } //if pinch gesture, could be useful to force preventDefault to avoid html page scroll/zoom in some mobile browsers
  48101. var ed = (pointA.pointerId === evt.pointerId) ? pointA : pointB;
  48102. ed.x = evt.clientX;
  48103. ed.y = evt.clientY;
  48104. var direction = _this.pinchInwards ? 1 : -1;
  48105. var distX = pointA.x - pointB.x;
  48106. var distY = pointA.y - pointB.y;
  48107. var pinchSquaredDistance = (distX * distX) + (distY * distY);
  48108. var pinchDistance = Math.sqrt(pinchSquaredDistance);
  48109. if (previousPinchSquaredDistance === 0) {
  48110. initialDistance = pinchDistance;
  48111. previousPinchSquaredDistance = pinchSquaredDistance;
  48112. previousMultiTouchPanPosition.x = (pointA.x + pointB.x) / 2;
  48113. previousMultiTouchPanPosition.y = (pointA.y + pointB.y) / 2;
  48114. return;
  48115. }
  48116. if (_this.multiTouchPanAndZoom) {
  48117. if (_this.pinchDeltaPercentage) {
  48118. _this.camera.inertialRadiusOffset += ((pinchSquaredDistance - previousPinchSquaredDistance) * 0.001) * _this.camera.radius * _this.pinchDeltaPercentage;
  48119. }
  48120. else {
  48121. _this.camera.inertialRadiusOffset += (pinchSquaredDistance - previousPinchSquaredDistance) /
  48122. (_this.pinchPrecision *
  48123. ((_this.angularSensibilityX + _this.angularSensibilityY) / 2) *
  48124. direction);
  48125. }
  48126. if (_this.panningSensibility !== 0) {
  48127. var pointersCenterX = (pointA.x + pointB.x) / 2;
  48128. var pointersCenterY = (pointA.y + pointB.y) / 2;
  48129. var pointersCenterDistX = pointersCenterX - previousMultiTouchPanPosition.x;
  48130. var pointersCenterDistY = pointersCenterY - previousMultiTouchPanPosition.y;
  48131. previousMultiTouchPanPosition.x = pointersCenterX;
  48132. previousMultiTouchPanPosition.y = pointersCenterY;
  48133. _this.camera.inertialPanningX += -(pointersCenterDistX) / (_this.panningSensibility);
  48134. _this.camera.inertialPanningY += (pointersCenterDistY) / (_this.panningSensibility);
  48135. }
  48136. }
  48137. else {
  48138. twoFingerActivityCount++;
  48139. if (previousMultiTouchPanPosition.isPinching || (twoFingerActivityCount < 20 && Math.abs(pinchDistance - initialDistance) > _this.camera.pinchToPanMaxDistance)) {
  48140. if (_this.pinchDeltaPercentage) {
  48141. _this.camera.inertialRadiusOffset += ((pinchSquaredDistance - previousPinchSquaredDistance) * 0.001) * _this.camera.radius * _this.pinchDeltaPercentage;
  48142. }
  48143. else {
  48144. _this.camera.inertialRadiusOffset += (pinchSquaredDistance - previousPinchSquaredDistance) /
  48145. (_this.pinchPrecision *
  48146. ((_this.angularSensibilityX + _this.angularSensibilityY) / 2) *
  48147. direction);
  48148. }
  48149. previousMultiTouchPanPosition.isPaning = false;
  48150. previousMultiTouchPanPosition.isPinching = true;
  48151. }
  48152. else {
  48153. if (cacheSoloPointer && cacheSoloPointer.pointerId === ed.pointerId && _this.panningSensibility !== 0 && _this.multiTouchPanning) {
  48154. if (!previousMultiTouchPanPosition.isPaning) {
  48155. previousMultiTouchPanPosition.isPaning = true;
  48156. previousMultiTouchPanPosition.isPinching = false;
  48157. previousMultiTouchPanPosition.x = ed.x;
  48158. previousMultiTouchPanPosition.y = ed.y;
  48159. return;
  48160. }
  48161. _this.camera.inertialPanningX += -(ed.x - previousMultiTouchPanPosition.x) / (_this.panningSensibility);
  48162. _this.camera.inertialPanningY += (ed.y - previousMultiTouchPanPosition.y) / (_this.panningSensibility);
  48163. }
  48164. }
  48165. if (cacheSoloPointer && cacheSoloPointer.pointerId === evt.pointerId) {
  48166. previousMultiTouchPanPosition.x = ed.x;
  48167. previousMultiTouchPanPosition.y = ed.y;
  48168. }
  48169. }
  48170. previousPinchSquaredDistance = pinchSquaredDistance;
  48171. }
  48172. }
  48173. };
  48174. this._observer = this.camera.getScene().onPointerObservable.add(this._pointerInput, BABYLON.PointerEventTypes.POINTERDOWN | BABYLON.PointerEventTypes.POINTERUP | BABYLON.PointerEventTypes.POINTERMOVE | BABYLON.PointerEventTypes._POINTERDOUBLETAP);
  48175. this._onContextMenu = function (evt) {
  48176. evt.preventDefault();
  48177. };
  48178. if (!this.camera._useCtrlForPanning) {
  48179. element.addEventListener("contextmenu", this._onContextMenu, false);
  48180. }
  48181. this._onLostFocus = function () {
  48182. //this._keys = [];
  48183. pointA = pointB = null;
  48184. previousPinchSquaredDistance = 0;
  48185. previousMultiTouchPanPosition.isPaning = false;
  48186. previousMultiTouchPanPosition.isPinching = false;
  48187. twoFingerActivityCount = 0;
  48188. cacheSoloPointer = null;
  48189. initialDistance = 0;
  48190. };
  48191. this._onMouseMove = function (evt) {
  48192. if (!engine.isPointerLock) {
  48193. return;
  48194. }
  48195. var offsetX = evt.movementX || evt.mozMovementX || evt.webkitMovementX || evt.msMovementX || 0;
  48196. var offsetY = evt.movementY || evt.mozMovementY || evt.webkitMovementY || evt.msMovementY || 0;
  48197. _this.camera.inertialAlphaOffset -= offsetX / _this.angularSensibilityX;
  48198. _this.camera.inertialBetaOffset -= offsetY / _this.angularSensibilityY;
  48199. if (!noPreventDefault) {
  48200. evt.preventDefault();
  48201. }
  48202. };
  48203. this._onGestureStart = function (e) {
  48204. if (window.MSGesture === undefined) {
  48205. return;
  48206. }
  48207. if (!_this._MSGestureHandler) {
  48208. _this._MSGestureHandler = new MSGesture();
  48209. _this._MSGestureHandler.target = element;
  48210. }
  48211. _this._MSGestureHandler.addPointer(e.pointerId);
  48212. };
  48213. this._onGesture = function (e) {
  48214. _this.camera.radius *= e.scale;
  48215. if (e.preventDefault) {
  48216. if (!noPreventDefault) {
  48217. e.stopPropagation();
  48218. e.preventDefault();
  48219. }
  48220. }
  48221. };
  48222. element.addEventListener("mousemove", this._onMouseMove, false);
  48223. element.addEventListener("MSPointerDown", this._onGestureStart, false);
  48224. element.addEventListener("MSGestureChange", this._onGesture, false);
  48225. BABYLON.Tools.RegisterTopRootEvents([
  48226. { name: "blur", handler: this._onLostFocus }
  48227. ]);
  48228. };
  48229. ArcRotateCameraPointersInput.prototype.detachControl = function (element) {
  48230. if (this._onLostFocus) {
  48231. BABYLON.Tools.UnregisterTopRootEvents([
  48232. { name: "blur", handler: this._onLostFocus }
  48233. ]);
  48234. }
  48235. if (element && this._observer) {
  48236. this.camera.getScene().onPointerObservable.remove(this._observer);
  48237. this._observer = null;
  48238. if (this._onContextMenu) {
  48239. element.removeEventListener("contextmenu", this._onContextMenu);
  48240. }
  48241. if (this._onMouseMove) {
  48242. element.removeEventListener("mousemove", this._onMouseMove);
  48243. }
  48244. if (this._onGestureStart) {
  48245. element.removeEventListener("MSPointerDown", this._onGestureStart);
  48246. }
  48247. if (this._onGesture) {
  48248. element.removeEventListener("MSGestureChange", this._onGesture);
  48249. }
  48250. this._isPanClick = false;
  48251. this.pinchInwards = true;
  48252. this._onMouseMove = null;
  48253. this._onGestureStart = null;
  48254. this._onGesture = null;
  48255. this._MSGestureHandler = null;
  48256. this._onLostFocus = null;
  48257. this._onContextMenu = null;
  48258. }
  48259. };
  48260. ArcRotateCameraPointersInput.prototype.getClassName = function () {
  48261. return "ArcRotateCameraPointersInput";
  48262. };
  48263. ArcRotateCameraPointersInput.prototype.getSimpleName = function () {
  48264. return "pointers";
  48265. };
  48266. __decorate([
  48267. BABYLON.serialize()
  48268. ], ArcRotateCameraPointersInput.prototype, "buttons", void 0);
  48269. __decorate([
  48270. BABYLON.serialize()
  48271. ], ArcRotateCameraPointersInput.prototype, "angularSensibilityX", void 0);
  48272. __decorate([
  48273. BABYLON.serialize()
  48274. ], ArcRotateCameraPointersInput.prototype, "angularSensibilityY", void 0);
  48275. __decorate([
  48276. BABYLON.serialize()
  48277. ], ArcRotateCameraPointersInput.prototype, "pinchPrecision", void 0);
  48278. __decorate([
  48279. BABYLON.serialize()
  48280. ], ArcRotateCameraPointersInput.prototype, "pinchDeltaPercentage", void 0);
  48281. __decorate([
  48282. BABYLON.serialize()
  48283. ], ArcRotateCameraPointersInput.prototype, "panningSensibility", void 0);
  48284. __decorate([
  48285. BABYLON.serialize()
  48286. ], ArcRotateCameraPointersInput.prototype, "multiTouchPanning", void 0);
  48287. __decorate([
  48288. BABYLON.serialize()
  48289. ], ArcRotateCameraPointersInput.prototype, "multiTouchPanAndZoom", void 0);
  48290. return ArcRotateCameraPointersInput;
  48291. }());
  48292. BABYLON.ArcRotateCameraPointersInput = ArcRotateCameraPointersInput;
  48293. BABYLON.CameraInputTypes["ArcRotateCameraPointersInput"] = ArcRotateCameraPointersInput;
  48294. })(BABYLON || (BABYLON = {}));
  48295. //# sourceMappingURL=babylon.arcRotateCameraPointersInput.js.map
  48296. var BABYLON;
  48297. (function (BABYLON) {
  48298. var ArcRotateCameraInputsManager = /** @class */ (function (_super) {
  48299. __extends(ArcRotateCameraInputsManager, _super);
  48300. function ArcRotateCameraInputsManager(camera) {
  48301. return _super.call(this, camera) || this;
  48302. }
  48303. ArcRotateCameraInputsManager.prototype.addMouseWheel = function () {
  48304. this.add(new BABYLON.ArcRotateCameraMouseWheelInput());
  48305. return this;
  48306. };
  48307. ArcRotateCameraInputsManager.prototype.addPointers = function () {
  48308. this.add(new BABYLON.ArcRotateCameraPointersInput());
  48309. return this;
  48310. };
  48311. ArcRotateCameraInputsManager.prototype.addKeyboard = function () {
  48312. this.add(new BABYLON.ArcRotateCameraKeyboardMoveInput());
  48313. return this;
  48314. };
  48315. ArcRotateCameraInputsManager.prototype.addGamepad = function () {
  48316. this.add(new BABYLON.ArcRotateCameraGamepadInput());
  48317. return this;
  48318. };
  48319. ArcRotateCameraInputsManager.prototype.addVRDeviceOrientation = function () {
  48320. this.add(new BABYLON.ArcRotateCameraVRDeviceOrientationInput());
  48321. return this;
  48322. };
  48323. return ArcRotateCameraInputsManager;
  48324. }(BABYLON.CameraInputsManager));
  48325. BABYLON.ArcRotateCameraInputsManager = ArcRotateCameraInputsManager;
  48326. })(BABYLON || (BABYLON = {}));
  48327. //# sourceMappingURL=babylon.arcRotateCameraInputsManager.js.map
  48328. var BABYLON;
  48329. (function (BABYLON) {
  48330. var ArcRotateCamera = /** @class */ (function (_super) {
  48331. __extends(ArcRotateCamera, _super);
  48332. function ArcRotateCamera(name, alpha, beta, radius, target, scene, setActiveOnSceneIfNoneActive) {
  48333. if (setActiveOnSceneIfNoneActive === void 0) { setActiveOnSceneIfNoneActive = true; }
  48334. var _this = _super.call(this, name, BABYLON.Vector3.Zero(), scene, setActiveOnSceneIfNoneActive) || this;
  48335. _this.inertialAlphaOffset = 0;
  48336. _this.inertialBetaOffset = 0;
  48337. _this.inertialRadiusOffset = 0;
  48338. _this.lowerAlphaLimit = null;
  48339. _this.upperAlphaLimit = null;
  48340. _this.lowerBetaLimit = 0.01;
  48341. _this.upperBetaLimit = Math.PI;
  48342. _this.lowerRadiusLimit = null;
  48343. _this.upperRadiusLimit = null;
  48344. _this.inertialPanningX = 0;
  48345. _this.inertialPanningY = 0;
  48346. _this.pinchToPanMaxDistance = 20;
  48347. _this.panningDistanceLimit = null;
  48348. _this.panningOriginTarget = BABYLON.Vector3.Zero();
  48349. _this.panningInertia = 0.9;
  48350. //-- end properties for backward compatibility for inputs
  48351. _this.zoomOnFactor = 1;
  48352. _this.targetScreenOffset = BABYLON.Vector2.Zero();
  48353. _this.allowUpsideDown = true;
  48354. _this._viewMatrix = new BABYLON.Matrix();
  48355. // Panning
  48356. _this.panningAxis = new BABYLON.Vector3(1, 1, 0);
  48357. _this.onMeshTargetChangedObservable = new BABYLON.Observable();
  48358. _this.checkCollisions = false;
  48359. _this.collisionRadius = new BABYLON.Vector3(0.5, 0.5, 0.5);
  48360. _this._previousPosition = BABYLON.Vector3.Zero();
  48361. _this._collisionVelocity = BABYLON.Vector3.Zero();
  48362. _this._newPosition = BABYLON.Vector3.Zero();
  48363. _this._computationVector = BABYLON.Vector3.Zero();
  48364. _this._onCollisionPositionChange = function (collisionId, newPosition, collidedMesh) {
  48365. if (collidedMesh === void 0) { collidedMesh = null; }
  48366. if (_this.getScene().workerCollisions && _this.checkCollisions) {
  48367. newPosition.multiplyInPlace(_this._collider._radius);
  48368. }
  48369. if (!collidedMesh) {
  48370. _this._previousPosition.copyFrom(_this.position);
  48371. }
  48372. else {
  48373. _this.setPosition(newPosition);
  48374. if (_this.onCollide) {
  48375. _this.onCollide(collidedMesh);
  48376. }
  48377. }
  48378. // Recompute because of constraints
  48379. var cosa = Math.cos(_this.alpha);
  48380. var sina = Math.sin(_this.alpha);
  48381. var cosb = Math.cos(_this.beta);
  48382. var sinb = Math.sin(_this.beta);
  48383. if (sinb === 0) {
  48384. sinb = 0.0001;
  48385. }
  48386. var target = _this._getTargetPosition();
  48387. _this._computationVector.copyFromFloats(_this.radius * cosa * sinb, _this.radius * cosb, _this.radius * sina * sinb);
  48388. target.addToRef(_this._computationVector, _this._newPosition);
  48389. _this.position.copyFrom(_this._newPosition);
  48390. var up = _this.upVector;
  48391. if (_this.allowUpsideDown && _this.beta < 0) {
  48392. up = up.clone();
  48393. up = up.negate();
  48394. }
  48395. BABYLON.Matrix.LookAtLHToRef(_this.position, target, up, _this._viewMatrix);
  48396. _this._viewMatrix.m[12] += _this.targetScreenOffset.x;
  48397. _this._viewMatrix.m[13] += _this.targetScreenOffset.y;
  48398. _this._collisionTriggered = false;
  48399. };
  48400. _this._target = BABYLON.Vector3.Zero();
  48401. if (target) {
  48402. _this.setTarget(target);
  48403. }
  48404. _this.alpha = alpha;
  48405. _this.beta = beta;
  48406. _this.radius = radius;
  48407. _this.getViewMatrix();
  48408. _this.inputs = new BABYLON.ArcRotateCameraInputsManager(_this);
  48409. _this.inputs.addKeyboard().addMouseWheel().addPointers();
  48410. return _this;
  48411. }
  48412. Object.defineProperty(ArcRotateCamera.prototype, "target", {
  48413. get: function () {
  48414. return this._target;
  48415. },
  48416. set: function (value) {
  48417. this.setTarget(value);
  48418. },
  48419. enumerable: true,
  48420. configurable: true
  48421. });
  48422. Object.defineProperty(ArcRotateCamera.prototype, "angularSensibilityX", {
  48423. //-- begin properties for backward compatibility for inputs
  48424. get: function () {
  48425. var pointers = this.inputs.attached["pointers"];
  48426. if (pointers)
  48427. return pointers.angularSensibilityX;
  48428. return 0;
  48429. },
  48430. set: function (value) {
  48431. var pointers = this.inputs.attached["pointers"];
  48432. if (pointers) {
  48433. pointers.angularSensibilityX = value;
  48434. }
  48435. },
  48436. enumerable: true,
  48437. configurable: true
  48438. });
  48439. Object.defineProperty(ArcRotateCamera.prototype, "angularSensibilityY", {
  48440. get: function () {
  48441. var pointers = this.inputs.attached["pointers"];
  48442. if (pointers)
  48443. return pointers.angularSensibilityY;
  48444. return 0;
  48445. },
  48446. set: function (value) {
  48447. var pointers = this.inputs.attached["pointers"];
  48448. if (pointers) {
  48449. pointers.angularSensibilityY = value;
  48450. }
  48451. },
  48452. enumerable: true,
  48453. configurable: true
  48454. });
  48455. Object.defineProperty(ArcRotateCamera.prototype, "pinchPrecision", {
  48456. get: function () {
  48457. var pointers = this.inputs.attached["pointers"];
  48458. if (pointers)
  48459. return pointers.pinchPrecision;
  48460. return 0;
  48461. },
  48462. set: function (value) {
  48463. var pointers = this.inputs.attached["pointers"];
  48464. if (pointers) {
  48465. pointers.pinchPrecision = value;
  48466. }
  48467. },
  48468. enumerable: true,
  48469. configurable: true
  48470. });
  48471. Object.defineProperty(ArcRotateCamera.prototype, "pinchDeltaPercentage", {
  48472. get: function () {
  48473. var pointers = this.inputs.attached["pointers"];
  48474. if (pointers)
  48475. return pointers.pinchDeltaPercentage;
  48476. return 0;
  48477. },
  48478. set: function (value) {
  48479. var pointers = this.inputs.attached["pointers"];
  48480. if (pointers) {
  48481. pointers.pinchDeltaPercentage = value;
  48482. }
  48483. },
  48484. enumerable: true,
  48485. configurable: true
  48486. });
  48487. Object.defineProperty(ArcRotateCamera.prototype, "panningSensibility", {
  48488. get: function () {
  48489. var pointers = this.inputs.attached["pointers"];
  48490. if (pointers)
  48491. return pointers.panningSensibility;
  48492. return 0;
  48493. },
  48494. set: function (value) {
  48495. var pointers = this.inputs.attached["pointers"];
  48496. if (pointers) {
  48497. pointers.panningSensibility = value;
  48498. }
  48499. },
  48500. enumerable: true,
  48501. configurable: true
  48502. });
  48503. Object.defineProperty(ArcRotateCamera.prototype, "keysUp", {
  48504. get: function () {
  48505. var keyboard = this.inputs.attached["keyboard"];
  48506. if (keyboard)
  48507. return keyboard.keysUp;
  48508. return [];
  48509. },
  48510. set: function (value) {
  48511. var keyboard = this.inputs.attached["keyboard"];
  48512. if (keyboard)
  48513. keyboard.keysUp = value;
  48514. },
  48515. enumerable: true,
  48516. configurable: true
  48517. });
  48518. Object.defineProperty(ArcRotateCamera.prototype, "keysDown", {
  48519. get: function () {
  48520. var keyboard = this.inputs.attached["keyboard"];
  48521. if (keyboard)
  48522. return keyboard.keysDown;
  48523. return [];
  48524. },
  48525. set: function (value) {
  48526. var keyboard = this.inputs.attached["keyboard"];
  48527. if (keyboard)
  48528. keyboard.keysDown = value;
  48529. },
  48530. enumerable: true,
  48531. configurable: true
  48532. });
  48533. Object.defineProperty(ArcRotateCamera.prototype, "keysLeft", {
  48534. get: function () {
  48535. var keyboard = this.inputs.attached["keyboard"];
  48536. if (keyboard)
  48537. return keyboard.keysLeft;
  48538. return [];
  48539. },
  48540. set: function (value) {
  48541. var keyboard = this.inputs.attached["keyboard"];
  48542. if (keyboard)
  48543. keyboard.keysLeft = value;
  48544. },
  48545. enumerable: true,
  48546. configurable: true
  48547. });
  48548. Object.defineProperty(ArcRotateCamera.prototype, "keysRight", {
  48549. get: function () {
  48550. var keyboard = this.inputs.attached["keyboard"];
  48551. if (keyboard)
  48552. return keyboard.keysRight;
  48553. return [];
  48554. },
  48555. set: function (value) {
  48556. var keyboard = this.inputs.attached["keyboard"];
  48557. if (keyboard)
  48558. keyboard.keysRight = value;
  48559. },
  48560. enumerable: true,
  48561. configurable: true
  48562. });
  48563. Object.defineProperty(ArcRotateCamera.prototype, "wheelPrecision", {
  48564. get: function () {
  48565. var mousewheel = this.inputs.attached["mousewheel"];
  48566. if (mousewheel)
  48567. return mousewheel.wheelPrecision;
  48568. return 0;
  48569. },
  48570. set: function (value) {
  48571. var mousewheel = this.inputs.attached["mousewheel"];
  48572. if (mousewheel)
  48573. mousewheel.wheelPrecision = value;
  48574. },
  48575. enumerable: true,
  48576. configurable: true
  48577. });
  48578. Object.defineProperty(ArcRotateCamera.prototype, "wheelDeltaPercentage", {
  48579. get: function () {
  48580. var mousewheel = this.inputs.attached["mousewheel"];
  48581. if (mousewheel)
  48582. return mousewheel.wheelDeltaPercentage;
  48583. return 0;
  48584. },
  48585. set: function (value) {
  48586. var mousewheel = this.inputs.attached["mousewheel"];
  48587. if (mousewheel)
  48588. mousewheel.wheelDeltaPercentage = value;
  48589. },
  48590. enumerable: true,
  48591. configurable: true
  48592. });
  48593. Object.defineProperty(ArcRotateCamera.prototype, "bouncingBehavior", {
  48594. get: function () {
  48595. return this._bouncingBehavior;
  48596. },
  48597. enumerable: true,
  48598. configurable: true
  48599. });
  48600. Object.defineProperty(ArcRotateCamera.prototype, "useBouncingBehavior", {
  48601. get: function () {
  48602. return this._bouncingBehavior != null;
  48603. },
  48604. set: function (value) {
  48605. if (value === this.useBouncingBehavior) {
  48606. return;
  48607. }
  48608. if (value) {
  48609. this._bouncingBehavior = new BABYLON.BouncingBehavior();
  48610. this.addBehavior(this._bouncingBehavior);
  48611. }
  48612. else if (this._bouncingBehavior) {
  48613. this.removeBehavior(this._bouncingBehavior);
  48614. this._bouncingBehavior = null;
  48615. }
  48616. },
  48617. enumerable: true,
  48618. configurable: true
  48619. });
  48620. Object.defineProperty(ArcRotateCamera.prototype, "framingBehavior", {
  48621. get: function () {
  48622. return this._framingBehavior;
  48623. },
  48624. enumerable: true,
  48625. configurable: true
  48626. });
  48627. Object.defineProperty(ArcRotateCamera.prototype, "useFramingBehavior", {
  48628. get: function () {
  48629. return this._framingBehavior != null;
  48630. },
  48631. set: function (value) {
  48632. if (value === this.useFramingBehavior) {
  48633. return;
  48634. }
  48635. if (value) {
  48636. this._framingBehavior = new BABYLON.FramingBehavior();
  48637. this.addBehavior(this._framingBehavior);
  48638. }
  48639. else if (this._framingBehavior) {
  48640. this.removeBehavior(this._framingBehavior);
  48641. this._framingBehavior = null;
  48642. }
  48643. },
  48644. enumerable: true,
  48645. configurable: true
  48646. });
  48647. Object.defineProperty(ArcRotateCamera.prototype, "autoRotationBehavior", {
  48648. get: function () {
  48649. return this._autoRotationBehavior;
  48650. },
  48651. enumerable: true,
  48652. configurable: true
  48653. });
  48654. Object.defineProperty(ArcRotateCamera.prototype, "useAutoRotationBehavior", {
  48655. get: function () {
  48656. return this._autoRotationBehavior != null;
  48657. },
  48658. set: function (value) {
  48659. if (value === this.useAutoRotationBehavior) {
  48660. return;
  48661. }
  48662. if (value) {
  48663. this._autoRotationBehavior = new BABYLON.AutoRotationBehavior();
  48664. this.addBehavior(this._autoRotationBehavior);
  48665. }
  48666. else if (this._autoRotationBehavior) {
  48667. this.removeBehavior(this._autoRotationBehavior);
  48668. this._autoRotationBehavior = null;
  48669. }
  48670. },
  48671. enumerable: true,
  48672. configurable: true
  48673. });
  48674. // Cache
  48675. ArcRotateCamera.prototype._initCache = function () {
  48676. _super.prototype._initCache.call(this);
  48677. this._cache._target = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  48678. this._cache.alpha = undefined;
  48679. this._cache.beta = undefined;
  48680. this._cache.radius = undefined;
  48681. this._cache.targetScreenOffset = BABYLON.Vector2.Zero();
  48682. };
  48683. ArcRotateCamera.prototype._updateCache = function (ignoreParentClass) {
  48684. if (!ignoreParentClass) {
  48685. _super.prototype._updateCache.call(this);
  48686. }
  48687. this._cache._target.copyFrom(this._getTargetPosition());
  48688. this._cache.alpha = this.alpha;
  48689. this._cache.beta = this.beta;
  48690. this._cache.radius = this.radius;
  48691. this._cache.targetScreenOffset.copyFrom(this.targetScreenOffset);
  48692. };
  48693. ArcRotateCamera.prototype._getTargetPosition = function () {
  48694. if (this._targetHost && this._targetHost.getAbsolutePosition) {
  48695. var pos = this._targetHost.getAbsolutePosition();
  48696. if (this._targetBoundingCenter) {
  48697. pos.addToRef(this._targetBoundingCenter, this._target);
  48698. }
  48699. else {
  48700. this._target.copyFrom(pos);
  48701. }
  48702. }
  48703. var lockedTargetPosition = this._getLockedTargetPosition();
  48704. if (lockedTargetPosition) {
  48705. return lockedTargetPosition;
  48706. }
  48707. return this._target;
  48708. };
  48709. ArcRotateCamera.prototype.storeState = function () {
  48710. this._storedAlpha = this.alpha;
  48711. this._storedBeta = this.beta;
  48712. this._storedRadius = this.radius;
  48713. this._storedTarget = this._getTargetPosition().clone();
  48714. return _super.prototype.storeState.call(this);
  48715. };
  48716. /**
  48717. * Restored camera state. You must call storeState() first
  48718. */
  48719. ArcRotateCamera.prototype._restoreStateValues = function () {
  48720. if (!_super.prototype._restoreStateValues.call(this)) {
  48721. return false;
  48722. }
  48723. this.alpha = this._storedAlpha;
  48724. this.beta = this._storedBeta;
  48725. this.radius = this._storedRadius;
  48726. this.setTarget(this._storedTarget.clone());
  48727. this.inertialAlphaOffset = 0;
  48728. this.inertialBetaOffset = 0;
  48729. this.inertialRadiusOffset = 0;
  48730. this.inertialPanningX = 0;
  48731. this.inertialPanningY = 0;
  48732. return true;
  48733. };
  48734. // Synchronized
  48735. ArcRotateCamera.prototype._isSynchronizedViewMatrix = function () {
  48736. if (!_super.prototype._isSynchronizedViewMatrix.call(this))
  48737. return false;
  48738. return this._cache._target.equals(this._getTargetPosition())
  48739. && this._cache.alpha === this.alpha
  48740. && this._cache.beta === this.beta
  48741. && this._cache.radius === this.radius
  48742. && this._cache.targetScreenOffset.equals(this.targetScreenOffset);
  48743. };
  48744. // Methods
  48745. ArcRotateCamera.prototype.attachControl = function (element, noPreventDefault, useCtrlForPanning, panningMouseButton) {
  48746. var _this = this;
  48747. if (useCtrlForPanning === void 0) { useCtrlForPanning = true; }
  48748. if (panningMouseButton === void 0) { panningMouseButton = 2; }
  48749. this._useCtrlForPanning = useCtrlForPanning;
  48750. this._panningMouseButton = panningMouseButton;
  48751. this.inputs.attachElement(element, noPreventDefault);
  48752. this._reset = function () {
  48753. _this.inertialAlphaOffset = 0;
  48754. _this.inertialBetaOffset = 0;
  48755. _this.inertialRadiusOffset = 0;
  48756. _this.inertialPanningX = 0;
  48757. _this.inertialPanningY = 0;
  48758. };
  48759. };
  48760. ArcRotateCamera.prototype.detachControl = function (element) {
  48761. this.inputs.detachElement(element);
  48762. if (this._reset) {
  48763. this._reset();
  48764. }
  48765. };
  48766. ArcRotateCamera.prototype._checkInputs = function () {
  48767. //if (async) collision inspection was triggered, don't update the camera's position - until the collision callback was called.
  48768. if (this._collisionTriggered) {
  48769. return;
  48770. }
  48771. this.inputs.checkInputs();
  48772. // Inertia
  48773. if (this.inertialAlphaOffset !== 0 || this.inertialBetaOffset !== 0 || this.inertialRadiusOffset !== 0) {
  48774. var inertialAlphaOffset = this.inertialAlphaOffset;
  48775. if (this.beta <= 0)
  48776. inertialAlphaOffset *= -1;
  48777. if (this.getScene().useRightHandedSystem)
  48778. inertialAlphaOffset *= -1;
  48779. if (this.parent && this.parent._getWorldMatrixDeterminant() < 0)
  48780. inertialAlphaOffset *= -1;
  48781. this.alpha += inertialAlphaOffset;
  48782. this.beta += this.inertialBetaOffset;
  48783. this.radius -= this.inertialRadiusOffset;
  48784. this.inertialAlphaOffset *= this.inertia;
  48785. this.inertialBetaOffset *= this.inertia;
  48786. this.inertialRadiusOffset *= this.inertia;
  48787. if (Math.abs(this.inertialAlphaOffset) < BABYLON.Epsilon)
  48788. this.inertialAlphaOffset = 0;
  48789. if (Math.abs(this.inertialBetaOffset) < BABYLON.Epsilon)
  48790. this.inertialBetaOffset = 0;
  48791. if (Math.abs(this.inertialRadiusOffset) < this.speed * BABYLON.Epsilon)
  48792. this.inertialRadiusOffset = 0;
  48793. }
  48794. // Panning inertia
  48795. if (this.inertialPanningX !== 0 || this.inertialPanningY !== 0) {
  48796. if (!this._localDirection) {
  48797. this._localDirection = BABYLON.Vector3.Zero();
  48798. this._transformedDirection = BABYLON.Vector3.Zero();
  48799. }
  48800. this._localDirection.copyFromFloats(this.inertialPanningX, this.inertialPanningY, this.inertialPanningY);
  48801. this._localDirection.multiplyInPlace(this.panningAxis);
  48802. this._viewMatrix.invertToRef(this._cameraTransformMatrix);
  48803. BABYLON.Vector3.TransformNormalToRef(this._localDirection, this._cameraTransformMatrix, this._transformedDirection);
  48804. //Eliminate y if map panning is enabled (panningAxis == 1,0,1)
  48805. if (!this.panningAxis.y) {
  48806. this._transformedDirection.y = 0;
  48807. }
  48808. if (!this._targetHost) {
  48809. if (this.panningDistanceLimit) {
  48810. this._transformedDirection.addInPlace(this._target);
  48811. var distanceSquared = BABYLON.Vector3.DistanceSquared(this._transformedDirection, this.panningOriginTarget);
  48812. if (distanceSquared <= (this.panningDistanceLimit * this.panningDistanceLimit)) {
  48813. this._target.copyFrom(this._transformedDirection);
  48814. }
  48815. }
  48816. else {
  48817. this._target.addInPlace(this._transformedDirection);
  48818. }
  48819. }
  48820. this.inertialPanningX *= this.panningInertia;
  48821. this.inertialPanningY *= this.panningInertia;
  48822. if (Math.abs(this.inertialPanningX) < this.speed * BABYLON.Epsilon)
  48823. this.inertialPanningX = 0;
  48824. if (Math.abs(this.inertialPanningY) < this.speed * BABYLON.Epsilon)
  48825. this.inertialPanningY = 0;
  48826. }
  48827. // Limits
  48828. this._checkLimits();
  48829. _super.prototype._checkInputs.call(this);
  48830. };
  48831. ArcRotateCamera.prototype._checkLimits = function () {
  48832. if (this.lowerBetaLimit === null || this.lowerBetaLimit === undefined) {
  48833. if (this.allowUpsideDown && this.beta > Math.PI) {
  48834. this.beta = this.beta - (2 * Math.PI);
  48835. }
  48836. }
  48837. else {
  48838. if (this.beta < this.lowerBetaLimit) {
  48839. this.beta = this.lowerBetaLimit;
  48840. }
  48841. }
  48842. if (this.upperBetaLimit === null || this.upperBetaLimit === undefined) {
  48843. if (this.allowUpsideDown && this.beta < -Math.PI) {
  48844. this.beta = this.beta + (2 * Math.PI);
  48845. }
  48846. }
  48847. else {
  48848. if (this.beta > this.upperBetaLimit) {
  48849. this.beta = this.upperBetaLimit;
  48850. }
  48851. }
  48852. if (this.lowerAlphaLimit && this.alpha < this.lowerAlphaLimit) {
  48853. this.alpha = this.lowerAlphaLimit;
  48854. }
  48855. if (this.upperAlphaLimit && this.alpha > this.upperAlphaLimit) {
  48856. this.alpha = this.upperAlphaLimit;
  48857. }
  48858. if (this.lowerRadiusLimit && this.radius < this.lowerRadiusLimit) {
  48859. this.radius = this.lowerRadiusLimit;
  48860. }
  48861. if (this.upperRadiusLimit && this.radius > this.upperRadiusLimit) {
  48862. this.radius = this.upperRadiusLimit;
  48863. }
  48864. };
  48865. ArcRotateCamera.prototype.rebuildAnglesAndRadius = function () {
  48866. this.position.subtractToRef(this._getTargetPosition(), this._computationVector);
  48867. this.radius = this._computationVector.length();
  48868. if (this.radius === 0) {
  48869. this.radius = 0.0001; // Just to avoid division by zero
  48870. }
  48871. // Alpha
  48872. this.alpha = Math.acos(this._computationVector.x / Math.sqrt(Math.pow(this._computationVector.x, 2) + Math.pow(this._computationVector.z, 2)));
  48873. if (this._computationVector.z < 0) {
  48874. this.alpha = 2 * Math.PI - this.alpha;
  48875. }
  48876. // Beta
  48877. this.beta = Math.acos(this._computationVector.y / this.radius);
  48878. this._checkLimits();
  48879. };
  48880. ArcRotateCamera.prototype.setPosition = function (position) {
  48881. if (this.position.equals(position)) {
  48882. return;
  48883. }
  48884. this.position.copyFrom(position);
  48885. this.rebuildAnglesAndRadius();
  48886. };
  48887. ArcRotateCamera.prototype.setTarget = function (target, toBoundingCenter, allowSamePosition) {
  48888. if (toBoundingCenter === void 0) { toBoundingCenter = false; }
  48889. if (allowSamePosition === void 0) { allowSamePosition = false; }
  48890. if (target.getBoundingInfo) {
  48891. if (toBoundingCenter) {
  48892. this._targetBoundingCenter = target.getBoundingInfo().boundingBox.centerWorld.clone();
  48893. }
  48894. else {
  48895. this._targetBoundingCenter = null;
  48896. }
  48897. this._targetHost = target;
  48898. this._target = this._getTargetPosition();
  48899. this.onMeshTargetChangedObservable.notifyObservers(this._targetHost);
  48900. }
  48901. else {
  48902. var newTarget = target;
  48903. var currentTarget = this._getTargetPosition();
  48904. if (currentTarget && !allowSamePosition && currentTarget.equals(newTarget)) {
  48905. return;
  48906. }
  48907. this._targetHost = null;
  48908. this._target = newTarget;
  48909. this._targetBoundingCenter = null;
  48910. this.onMeshTargetChangedObservable.notifyObservers(null);
  48911. }
  48912. this.rebuildAnglesAndRadius();
  48913. };
  48914. ArcRotateCamera.prototype._getViewMatrix = function () {
  48915. // Compute
  48916. var cosa = Math.cos(this.alpha);
  48917. var sina = Math.sin(this.alpha);
  48918. var cosb = Math.cos(this.beta);
  48919. var sinb = Math.sin(this.beta);
  48920. if (sinb === 0) {
  48921. sinb = 0.0001;
  48922. }
  48923. var target = this._getTargetPosition();
  48924. this._computationVector.copyFromFloats(this.radius * cosa * sinb, this.radius * cosb, this.radius * sina * sinb);
  48925. target.addToRef(this._computationVector, this._newPosition);
  48926. if (this.getScene().collisionsEnabled && this.checkCollisions) {
  48927. if (!this._collider) {
  48928. this._collider = new BABYLON.Collider();
  48929. }
  48930. this._collider._radius = this.collisionRadius;
  48931. this._newPosition.subtractToRef(this.position, this._collisionVelocity);
  48932. this._collisionTriggered = true;
  48933. this.getScene().collisionCoordinator.getNewPosition(this.position, this._collisionVelocity, this._collider, 3, null, this._onCollisionPositionChange, this.uniqueId);
  48934. }
  48935. else {
  48936. this.position.copyFrom(this._newPosition);
  48937. var up = this.upVector;
  48938. if (this.allowUpsideDown && sinb < 0) {
  48939. up = up.clone();
  48940. up = up.negate();
  48941. }
  48942. this._computeViewMatrix(this.position, target, up);
  48943. this._viewMatrix.m[12] += this.targetScreenOffset.x;
  48944. this._viewMatrix.m[13] += this.targetScreenOffset.y;
  48945. }
  48946. this._currentTarget = target;
  48947. return this._viewMatrix;
  48948. };
  48949. ArcRotateCamera.prototype.zoomOn = function (meshes, doNotUpdateMaxZ) {
  48950. if (doNotUpdateMaxZ === void 0) { doNotUpdateMaxZ = false; }
  48951. meshes = meshes || this.getScene().meshes;
  48952. var minMaxVector = BABYLON.Mesh.MinMax(meshes);
  48953. var distance = BABYLON.Vector3.Distance(minMaxVector.min, minMaxVector.max);
  48954. this.radius = distance * this.zoomOnFactor;
  48955. this.focusOn({ min: minMaxVector.min, max: minMaxVector.max, distance: distance }, doNotUpdateMaxZ);
  48956. };
  48957. ArcRotateCamera.prototype.focusOn = function (meshesOrMinMaxVectorAndDistance, doNotUpdateMaxZ) {
  48958. if (doNotUpdateMaxZ === void 0) { doNotUpdateMaxZ = false; }
  48959. var meshesOrMinMaxVector;
  48960. var distance;
  48961. if (meshesOrMinMaxVectorAndDistance.min === undefined) { // meshes
  48962. var meshes = meshesOrMinMaxVectorAndDistance || this.getScene().meshes;
  48963. meshesOrMinMaxVector = BABYLON.Mesh.MinMax(meshes);
  48964. distance = BABYLON.Vector3.Distance(meshesOrMinMaxVector.min, meshesOrMinMaxVector.max);
  48965. }
  48966. else { //minMaxVector and distance
  48967. var minMaxVectorAndDistance = meshesOrMinMaxVectorAndDistance;
  48968. meshesOrMinMaxVector = minMaxVectorAndDistance;
  48969. distance = minMaxVectorAndDistance.distance;
  48970. }
  48971. this._target = BABYLON.Mesh.Center(meshesOrMinMaxVector);
  48972. if (!doNotUpdateMaxZ) {
  48973. this.maxZ = distance * 2;
  48974. }
  48975. };
  48976. /**
  48977. * @override
  48978. * Override Camera.createRigCamera
  48979. */
  48980. ArcRotateCamera.prototype.createRigCamera = function (name, cameraIndex) {
  48981. var alphaShift = 0;
  48982. switch (this.cameraRigMode) {
  48983. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  48984. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  48985. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  48986. case BABYLON.Camera.RIG_MODE_VR:
  48987. alphaShift = this._cameraRigParams.stereoHalfAngle * (cameraIndex === 0 ? 1 : -1);
  48988. break;
  48989. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  48990. alphaShift = this._cameraRigParams.stereoHalfAngle * (cameraIndex === 0 ? -1 : 1);
  48991. break;
  48992. }
  48993. var rigCam = new ArcRotateCamera(name, this.alpha + alphaShift, this.beta, this.radius, this._target, this.getScene());
  48994. rigCam._cameraRigParams = {};
  48995. return rigCam;
  48996. };
  48997. /**
  48998. * @override
  48999. * Override Camera._updateRigCameras
  49000. */
  49001. ArcRotateCamera.prototype._updateRigCameras = function () {
  49002. var camLeft = this._rigCameras[0];
  49003. var camRight = this._rigCameras[1];
  49004. camLeft.beta = camRight.beta = this.beta;
  49005. camLeft.radius = camRight.radius = this.radius;
  49006. switch (this.cameraRigMode) {
  49007. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  49008. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  49009. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  49010. case BABYLON.Camera.RIG_MODE_VR:
  49011. camLeft.alpha = this.alpha - this._cameraRigParams.stereoHalfAngle;
  49012. camRight.alpha = this.alpha + this._cameraRigParams.stereoHalfAngle;
  49013. break;
  49014. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  49015. camLeft.alpha = this.alpha + this._cameraRigParams.stereoHalfAngle;
  49016. camRight.alpha = this.alpha - this._cameraRigParams.stereoHalfAngle;
  49017. break;
  49018. }
  49019. _super.prototype._updateRigCameras.call(this);
  49020. };
  49021. ArcRotateCamera.prototype.dispose = function () {
  49022. this.inputs.clear();
  49023. _super.prototype.dispose.call(this);
  49024. };
  49025. ArcRotateCamera.prototype.getClassName = function () {
  49026. return "ArcRotateCamera";
  49027. };
  49028. __decorate([
  49029. BABYLON.serialize()
  49030. ], ArcRotateCamera.prototype, "alpha", void 0);
  49031. __decorate([
  49032. BABYLON.serialize()
  49033. ], ArcRotateCamera.prototype, "beta", void 0);
  49034. __decorate([
  49035. BABYLON.serialize()
  49036. ], ArcRotateCamera.prototype, "radius", void 0);
  49037. __decorate([
  49038. BABYLON.serializeAsVector3("target")
  49039. ], ArcRotateCamera.prototype, "_target", void 0);
  49040. __decorate([
  49041. BABYLON.serialize()
  49042. ], ArcRotateCamera.prototype, "inertialAlphaOffset", void 0);
  49043. __decorate([
  49044. BABYLON.serialize()
  49045. ], ArcRotateCamera.prototype, "inertialBetaOffset", void 0);
  49046. __decorate([
  49047. BABYLON.serialize()
  49048. ], ArcRotateCamera.prototype, "inertialRadiusOffset", void 0);
  49049. __decorate([
  49050. BABYLON.serialize()
  49051. ], ArcRotateCamera.prototype, "lowerAlphaLimit", void 0);
  49052. __decorate([
  49053. BABYLON.serialize()
  49054. ], ArcRotateCamera.prototype, "upperAlphaLimit", void 0);
  49055. __decorate([
  49056. BABYLON.serialize()
  49057. ], ArcRotateCamera.prototype, "lowerBetaLimit", void 0);
  49058. __decorate([
  49059. BABYLON.serialize()
  49060. ], ArcRotateCamera.prototype, "upperBetaLimit", void 0);
  49061. __decorate([
  49062. BABYLON.serialize()
  49063. ], ArcRotateCamera.prototype, "lowerRadiusLimit", void 0);
  49064. __decorate([
  49065. BABYLON.serialize()
  49066. ], ArcRotateCamera.prototype, "upperRadiusLimit", void 0);
  49067. __decorate([
  49068. BABYLON.serialize()
  49069. ], ArcRotateCamera.prototype, "inertialPanningX", void 0);
  49070. __decorate([
  49071. BABYLON.serialize()
  49072. ], ArcRotateCamera.prototype, "inertialPanningY", void 0);
  49073. __decorate([
  49074. BABYLON.serialize()
  49075. ], ArcRotateCamera.prototype, "pinchToPanMaxDistance", void 0);
  49076. __decorate([
  49077. BABYLON.serialize()
  49078. ], ArcRotateCamera.prototype, "panningDistanceLimit", void 0);
  49079. __decorate([
  49080. BABYLON.serializeAsVector3()
  49081. ], ArcRotateCamera.prototype, "panningOriginTarget", void 0);
  49082. __decorate([
  49083. BABYLON.serialize()
  49084. ], ArcRotateCamera.prototype, "panningInertia", void 0);
  49085. __decorate([
  49086. BABYLON.serialize()
  49087. ], ArcRotateCamera.prototype, "zoomOnFactor", void 0);
  49088. __decorate([
  49089. BABYLON.serialize()
  49090. ], ArcRotateCamera.prototype, "allowUpsideDown", void 0);
  49091. return ArcRotateCamera;
  49092. }(BABYLON.TargetCamera));
  49093. BABYLON.ArcRotateCamera = ArcRotateCamera;
  49094. })(BABYLON || (BABYLON = {}));
  49095. //# sourceMappingURL=babylon.arcRotateCamera.js.map
  49096. var BABYLON;
  49097. (function (BABYLON) {
  49098. /**
  49099. * The HemisphericLight simulates the ambient environment light,
  49100. * so the passed direction is the light reflection direction, not the incoming direction.
  49101. */
  49102. var HemisphericLight = /** @class */ (function (_super) {
  49103. __extends(HemisphericLight, _super);
  49104. /**
  49105. * Creates a HemisphericLight object in the scene according to the passed direction (Vector3).
  49106. * The HemisphericLight simulates the ambient environment light, so the passed direction is the light reflection direction, not the incoming direction.
  49107. * The HemisphericLight can't cast shadows.
  49108. * Documentation : http://doc.babylonjs.com/tutorials/lights
  49109. * @param name The friendly name of the light
  49110. * @param direction The direction of the light reflection
  49111. * @param scene The scene the light belongs to
  49112. */
  49113. function HemisphericLight(name, direction, scene) {
  49114. var _this = _super.call(this, name, scene) || this;
  49115. /**
  49116. * The groundColor is the light in the opposite direction to the one specified during creation.
  49117. * 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.
  49118. */
  49119. _this.groundColor = new BABYLON.Color3(0.0, 0.0, 0.0);
  49120. _this.direction = direction || BABYLON.Vector3.Up();
  49121. return _this;
  49122. }
  49123. HemisphericLight.prototype._buildUniformLayout = function () {
  49124. this._uniformBuffer.addUniform("vLightData", 4);
  49125. this._uniformBuffer.addUniform("vLightDiffuse", 4);
  49126. this._uniformBuffer.addUniform("vLightSpecular", 3);
  49127. this._uniformBuffer.addUniform("vLightGround", 3);
  49128. this._uniformBuffer.addUniform("shadowsInfo", 3);
  49129. this._uniformBuffer.addUniform("depthValues", 2);
  49130. this._uniformBuffer.create();
  49131. };
  49132. /**
  49133. * Returns the string "HemisphericLight".
  49134. * @return The class name
  49135. */
  49136. HemisphericLight.prototype.getClassName = function () {
  49137. return "HemisphericLight";
  49138. };
  49139. /**
  49140. * Sets the HemisphericLight direction towards the passed target (Vector3).
  49141. * Returns the updated direction.
  49142. * @param target The target the direction should point to
  49143. * @return The computed direction
  49144. */
  49145. HemisphericLight.prototype.setDirectionToTarget = function (target) {
  49146. this.direction = BABYLON.Vector3.Normalize(target.subtract(BABYLON.Vector3.Zero()));
  49147. return this.direction;
  49148. };
  49149. /**
  49150. * Returns the shadow generator associated to the light.
  49151. * @returns Always null for hemispheric lights because it does not support shadows.
  49152. */
  49153. HemisphericLight.prototype.getShadowGenerator = function () {
  49154. return null;
  49155. };
  49156. /**
  49157. * Sets the passed Effect object with the HemisphericLight normalized direction and color and the passed name (string).
  49158. * @param effect The effect to update
  49159. * @param lightIndex The index of the light in the effect to update
  49160. * @returns The hemispheric light
  49161. */
  49162. HemisphericLight.prototype.transferToEffect = function (effect, lightIndex) {
  49163. var normalizeDirection = BABYLON.Vector3.Normalize(this.direction);
  49164. this._uniformBuffer.updateFloat4("vLightData", normalizeDirection.x, normalizeDirection.y, normalizeDirection.z, 0.0, lightIndex);
  49165. this._uniformBuffer.updateColor3("vLightGround", this.groundColor.scale(this.intensity), lightIndex);
  49166. return this;
  49167. };
  49168. /**
  49169. * @hidden internal use only.
  49170. */
  49171. HemisphericLight.prototype._getWorldMatrix = function () {
  49172. if (!this._worldMatrix) {
  49173. this._worldMatrix = BABYLON.Matrix.Identity();
  49174. }
  49175. return this._worldMatrix;
  49176. };
  49177. /**
  49178. * Returns the integer 3.
  49179. * @return The light Type id as a constant defines in Light.LIGHTTYPEID_x
  49180. */
  49181. HemisphericLight.prototype.getTypeID = function () {
  49182. return BABYLON.Light.LIGHTTYPEID_HEMISPHERICLIGHT;
  49183. };
  49184. __decorate([
  49185. BABYLON.serializeAsColor3()
  49186. ], HemisphericLight.prototype, "groundColor", void 0);
  49187. __decorate([
  49188. BABYLON.serializeAsVector3()
  49189. ], HemisphericLight.prototype, "direction", void 0);
  49190. return HemisphericLight;
  49191. }(BABYLON.Light));
  49192. BABYLON.HemisphericLight = HemisphericLight;
  49193. })(BABYLON || (BABYLON = {}));
  49194. //# sourceMappingURL=babylon.hemisphericLight.js.map
  49195. var BABYLON;
  49196. (function (BABYLON) {
  49197. /**
  49198. * Base implementation IShadowLight
  49199. * It groups all the common behaviour in order to reduce dupplication and better follow the DRY pattern.
  49200. */
  49201. var ShadowLight = /** @class */ (function (_super) {
  49202. __extends(ShadowLight, _super);
  49203. function ShadowLight() {
  49204. var _this = _super !== null && _super.apply(this, arguments) || this;
  49205. _this._needProjectionMatrixCompute = true;
  49206. return _this;
  49207. }
  49208. ShadowLight.prototype._setPosition = function (value) {
  49209. this._position = value;
  49210. };
  49211. Object.defineProperty(ShadowLight.prototype, "position", {
  49212. /**
  49213. * Sets the position the shadow will be casted from. Also use as the light position for both
  49214. * point and spot lights.
  49215. */
  49216. get: function () {
  49217. return this._position;
  49218. },
  49219. /**
  49220. * Sets the position the shadow will be casted from. Also use as the light position for both
  49221. * point and spot lights.
  49222. */
  49223. set: function (value) {
  49224. this._setPosition(value);
  49225. },
  49226. enumerable: true,
  49227. configurable: true
  49228. });
  49229. ShadowLight.prototype._setDirection = function (value) {
  49230. this._direction = value;
  49231. };
  49232. Object.defineProperty(ShadowLight.prototype, "direction", {
  49233. /**
  49234. * In 2d mode (needCube being false), gets the direction used to cast the shadow.
  49235. * Also use as the light direction on spot and directional lights.
  49236. */
  49237. get: function () {
  49238. return this._direction;
  49239. },
  49240. /**
  49241. * In 2d mode (needCube being false), sets the direction used to cast the shadow.
  49242. * Also use as the light direction on spot and directional lights.
  49243. */
  49244. set: function (value) {
  49245. this._setDirection(value);
  49246. },
  49247. enumerable: true,
  49248. configurable: true
  49249. });
  49250. Object.defineProperty(ShadowLight.prototype, "shadowMinZ", {
  49251. /**
  49252. * Gets the shadow projection clipping minimum z value.
  49253. */
  49254. get: function () {
  49255. return this._shadowMinZ;
  49256. },
  49257. /**
  49258. * Sets the shadow projection clipping minimum z value.
  49259. */
  49260. set: function (value) {
  49261. this._shadowMinZ = value;
  49262. this.forceProjectionMatrixCompute();
  49263. },
  49264. enumerable: true,
  49265. configurable: true
  49266. });
  49267. Object.defineProperty(ShadowLight.prototype, "shadowMaxZ", {
  49268. /**
  49269. * Sets the shadow projection clipping maximum z value.
  49270. */
  49271. get: function () {
  49272. return this._shadowMaxZ;
  49273. },
  49274. /**
  49275. * Gets the shadow projection clipping maximum z value.
  49276. */
  49277. set: function (value) {
  49278. this._shadowMaxZ = value;
  49279. this.forceProjectionMatrixCompute();
  49280. },
  49281. enumerable: true,
  49282. configurable: true
  49283. });
  49284. /**
  49285. * Computes the transformed information (transformedPosition and transformedDirection in World space) of the current light
  49286. * @returns true if the information has been computed, false if it does not need to (no parenting)
  49287. */
  49288. ShadowLight.prototype.computeTransformedInformation = function () {
  49289. if (this.parent && this.parent.getWorldMatrix) {
  49290. if (!this.transformedPosition) {
  49291. this.transformedPosition = BABYLON.Vector3.Zero();
  49292. }
  49293. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this.parent.getWorldMatrix(), this.transformedPosition);
  49294. // In case the direction is present.
  49295. if (this.direction) {
  49296. if (!this.transformedDirection) {
  49297. this.transformedDirection = BABYLON.Vector3.Zero();
  49298. }
  49299. BABYLON.Vector3.TransformNormalToRef(this.direction, this.parent.getWorldMatrix(), this.transformedDirection);
  49300. }
  49301. return true;
  49302. }
  49303. return false;
  49304. };
  49305. /**
  49306. * Return the depth scale used for the shadow map.
  49307. * @returns the depth scale.
  49308. */
  49309. ShadowLight.prototype.getDepthScale = function () {
  49310. return 50.0;
  49311. };
  49312. /**
  49313. * Get the direction to use to render the shadow map. In case of cube texture, the face index can be passed.
  49314. * @param faceIndex The index of the face we are computed the direction to generate shadow
  49315. * @returns The set direction in 2d mode otherwise the direction to the cubemap face if needCube() is true
  49316. */
  49317. ShadowLight.prototype.getShadowDirection = function (faceIndex) {
  49318. return this.transformedDirection ? this.transformedDirection : this.direction;
  49319. };
  49320. /**
  49321. * Returns the ShadowLight absolute position in the World.
  49322. * @returns the position vector in world space
  49323. */
  49324. ShadowLight.prototype.getAbsolutePosition = function () {
  49325. return this.transformedPosition ? this.transformedPosition : this.position;
  49326. };
  49327. /**
  49328. * Sets the ShadowLight direction toward the passed target.
  49329. * @param target The point tot target in local space
  49330. * @returns the updated ShadowLight direction
  49331. */
  49332. ShadowLight.prototype.setDirectionToTarget = function (target) {
  49333. this.direction = BABYLON.Vector3.Normalize(target.subtract(this.position));
  49334. return this.direction;
  49335. };
  49336. /**
  49337. * Returns the light rotation in euler definition.
  49338. * @returns the x y z rotation in local space.
  49339. */
  49340. ShadowLight.prototype.getRotation = function () {
  49341. this.direction.normalize();
  49342. var xaxis = BABYLON.Vector3.Cross(this.direction, BABYLON.Axis.Y);
  49343. var yaxis = BABYLON.Vector3.Cross(xaxis, this.direction);
  49344. return BABYLON.Vector3.RotationFromAxis(xaxis, yaxis, this.direction);
  49345. };
  49346. /**
  49347. * Returns whether or not the shadow generation require a cube texture or a 2d texture.
  49348. * @returns true if a cube texture needs to be use
  49349. */
  49350. ShadowLight.prototype.needCube = function () {
  49351. return false;
  49352. };
  49353. /**
  49354. * Detects if the projection matrix requires to be recomputed this frame.
  49355. * @returns true if it requires to be recomputed otherwise, false.
  49356. */
  49357. ShadowLight.prototype.needProjectionMatrixCompute = function () {
  49358. return this._needProjectionMatrixCompute;
  49359. };
  49360. /**
  49361. * Forces the shadow generator to recompute the projection matrix even if position and direction did not changed.
  49362. */
  49363. ShadowLight.prototype.forceProjectionMatrixCompute = function () {
  49364. this._needProjectionMatrixCompute = true;
  49365. };
  49366. /**
  49367. * Get the world matrix of the sahdow lights.
  49368. * @hidden Internal Use Only
  49369. */
  49370. ShadowLight.prototype._getWorldMatrix = function () {
  49371. if (!this._worldMatrix) {
  49372. this._worldMatrix = BABYLON.Matrix.Identity();
  49373. }
  49374. BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, this._worldMatrix);
  49375. return this._worldMatrix;
  49376. };
  49377. /**
  49378. * Gets the minZ used for shadow according to both the scene and the light.
  49379. * @param activeCamera The camera we are returning the min for
  49380. * @returns the depth min z
  49381. */
  49382. ShadowLight.prototype.getDepthMinZ = function (activeCamera) {
  49383. return this.shadowMinZ !== undefined ? this.shadowMinZ : activeCamera.minZ;
  49384. };
  49385. /**
  49386. * Gets the maxZ used for shadow according to both the scene and the light.
  49387. * @param activeCamera The camera we are returning the max for
  49388. * @returns the depth max z
  49389. */
  49390. ShadowLight.prototype.getDepthMaxZ = function (activeCamera) {
  49391. return this.shadowMaxZ !== undefined ? this.shadowMaxZ : activeCamera.maxZ;
  49392. };
  49393. /**
  49394. * Sets the shadow projection matrix in parameter to the generated projection matrix.
  49395. * @param matrix The materix to updated with the projection information
  49396. * @param viewMatrix The transform matrix of the light
  49397. * @param renderList The list of mesh to render in the map
  49398. * @returns The current light
  49399. */
  49400. ShadowLight.prototype.setShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  49401. if (this.customProjectionMatrixBuilder) {
  49402. this.customProjectionMatrixBuilder(viewMatrix, renderList, matrix);
  49403. }
  49404. else {
  49405. this._setDefaultShadowProjectionMatrix(matrix, viewMatrix, renderList);
  49406. }
  49407. return this;
  49408. };
  49409. __decorate([
  49410. BABYLON.serializeAsVector3()
  49411. ], ShadowLight.prototype, "position", null);
  49412. __decorate([
  49413. BABYLON.serializeAsVector3()
  49414. ], ShadowLight.prototype, "direction", null);
  49415. __decorate([
  49416. BABYLON.serialize()
  49417. ], ShadowLight.prototype, "shadowMinZ", null);
  49418. __decorate([
  49419. BABYLON.serialize()
  49420. ], ShadowLight.prototype, "shadowMaxZ", null);
  49421. return ShadowLight;
  49422. }(BABYLON.Light));
  49423. BABYLON.ShadowLight = ShadowLight;
  49424. })(BABYLON || (BABYLON = {}));
  49425. //# sourceMappingURL=babylon.shadowLight.js.map
  49426. var BABYLON;
  49427. (function (BABYLON) {
  49428. /**
  49429. * A point light is a light defined by an unique point in world space.
  49430. * The light is emitted in every direction from this point.
  49431. * A good example of a point light is a standard light bulb.
  49432. * Documentation: https://doc.babylonjs.com/babylon101/lights
  49433. */
  49434. var PointLight = /** @class */ (function (_super) {
  49435. __extends(PointLight, _super);
  49436. /**
  49437. * Creates a PointLight object from the passed name and position (Vector3) and adds it in the scene.
  49438. * A PointLight emits the light in every direction.
  49439. * It can cast shadows.
  49440. * If the scene camera is already defined and you want to set your PointLight at the camera position, just set it :
  49441. * ```javascript
  49442. * var pointLight = new BABYLON.PointLight("pl", camera.position, scene);
  49443. * ```
  49444. * Documentation : http://doc.babylonjs.com/tutorials/lights
  49445. * @param name The light friendly name
  49446. * @param position The position of the point light in the scene
  49447. * @param scene The scene the lights belongs to
  49448. */
  49449. function PointLight(name, position, scene) {
  49450. var _this = _super.call(this, name, scene) || this;
  49451. _this._shadowAngle = Math.PI / 2;
  49452. _this.position = position;
  49453. return _this;
  49454. }
  49455. Object.defineProperty(PointLight.prototype, "shadowAngle", {
  49456. /**
  49457. * Getter: In case of direction provided, the shadow will not use a cube texture but simulate a spot shadow as a fallback
  49458. * This specifies what angle the shadow will use to be created.
  49459. *
  49460. * It default to 90 degrees to work nicely with the cube texture generation for point lights shadow maps.
  49461. */
  49462. get: function () {
  49463. return this._shadowAngle;
  49464. },
  49465. /**
  49466. * Setter: In case of direction provided, the shadow will not use a cube texture but simulate a spot shadow as a fallback
  49467. * This specifies what angle the shadow will use to be created.
  49468. *
  49469. * It default to 90 degrees to work nicely with the cube texture generation for point lights shadow maps.
  49470. */
  49471. set: function (value) {
  49472. this._shadowAngle = value;
  49473. this.forceProjectionMatrixCompute();
  49474. },
  49475. enumerable: true,
  49476. configurable: true
  49477. });
  49478. Object.defineProperty(PointLight.prototype, "direction", {
  49479. /**
  49480. * Gets the direction if it has been set.
  49481. * In case of direction provided, the shadow will not use a cube texture but simulate a spot shadow as a fallback
  49482. */
  49483. get: function () {
  49484. return this._direction;
  49485. },
  49486. /**
  49487. * In case of direction provided, the shadow will not use a cube texture but simulate a spot shadow as a fallback
  49488. */
  49489. set: function (value) {
  49490. var previousNeedCube = this.needCube();
  49491. this._direction = value;
  49492. if (this.needCube() !== previousNeedCube && this._shadowGenerator) {
  49493. this._shadowGenerator.recreateShadowMap();
  49494. }
  49495. },
  49496. enumerable: true,
  49497. configurable: true
  49498. });
  49499. /**
  49500. * Returns the string "PointLight"
  49501. * @returns the class name
  49502. */
  49503. PointLight.prototype.getClassName = function () {
  49504. return "PointLight";
  49505. };
  49506. /**
  49507. * Returns the integer 0.
  49508. * @returns The light Type id as a constant defines in Light.LIGHTTYPEID_x
  49509. */
  49510. PointLight.prototype.getTypeID = function () {
  49511. return BABYLON.Light.LIGHTTYPEID_POINTLIGHT;
  49512. };
  49513. /**
  49514. * Specifies wether or not the shadowmap should be a cube texture.
  49515. * @returns true if the shadowmap needs to be a cube texture.
  49516. */
  49517. PointLight.prototype.needCube = function () {
  49518. return !this.direction;
  49519. };
  49520. /**
  49521. * Returns a new Vector3 aligned with the PointLight cube system according to the passed cube face index (integer).
  49522. * @param faceIndex The index of the face we are computed the direction to generate shadow
  49523. * @returns The set direction in 2d mode otherwise the direction to the cubemap face if needCube() is true
  49524. */
  49525. PointLight.prototype.getShadowDirection = function (faceIndex) {
  49526. if (this.direction) {
  49527. return _super.prototype.getShadowDirection.call(this, faceIndex);
  49528. }
  49529. else {
  49530. switch (faceIndex) {
  49531. case 0:
  49532. return new BABYLON.Vector3(1.0, 0.0, 0.0);
  49533. case 1:
  49534. return new BABYLON.Vector3(-1.0, 0.0, 0.0);
  49535. case 2:
  49536. return new BABYLON.Vector3(0.0, -1.0, 0.0);
  49537. case 3:
  49538. return new BABYLON.Vector3(0.0, 1.0, 0.0);
  49539. case 4:
  49540. return new BABYLON.Vector3(0.0, 0.0, 1.0);
  49541. case 5:
  49542. return new BABYLON.Vector3(0.0, 0.0, -1.0);
  49543. }
  49544. }
  49545. return BABYLON.Vector3.Zero();
  49546. };
  49547. /**
  49548. * Sets the passed matrix "matrix" as a left-handed perspective projection matrix with the following settings :
  49549. * - fov = PI / 2
  49550. * - aspect ratio : 1.0
  49551. * - z-near and far equal to the active camera minZ and maxZ.
  49552. * Returns the PointLight.
  49553. */
  49554. PointLight.prototype._setDefaultShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  49555. var activeCamera = this.getScene().activeCamera;
  49556. if (!activeCamera) {
  49557. return;
  49558. }
  49559. BABYLON.Matrix.PerspectiveFovLHToRef(this.shadowAngle, 1.0, this.getDepthMinZ(activeCamera), this.getDepthMaxZ(activeCamera), matrix);
  49560. };
  49561. PointLight.prototype._buildUniformLayout = function () {
  49562. this._uniformBuffer.addUniform("vLightData", 4);
  49563. this._uniformBuffer.addUniform("vLightDiffuse", 4);
  49564. this._uniformBuffer.addUniform("vLightSpecular", 3);
  49565. this._uniformBuffer.addUniform("shadowsInfo", 3);
  49566. this._uniformBuffer.addUniform("depthValues", 2);
  49567. this._uniformBuffer.create();
  49568. };
  49569. /**
  49570. * Sets the passed Effect "effect" with the PointLight transformed position (or position, if none) and passed name (string).
  49571. * @param effect The effect to update
  49572. * @param lightIndex The index of the light in the effect to update
  49573. * @returns The point light
  49574. */
  49575. PointLight.prototype.transferToEffect = function (effect, lightIndex) {
  49576. if (this.computeTransformedInformation()) {
  49577. this._uniformBuffer.updateFloat4("vLightData", this.transformedPosition.x, this.transformedPosition.y, this.transformedPosition.z, 0.0, lightIndex);
  49578. return this;
  49579. }
  49580. this._uniformBuffer.updateFloat4("vLightData", this.position.x, this.position.y, this.position.z, 0, lightIndex);
  49581. return this;
  49582. };
  49583. __decorate([
  49584. BABYLON.serialize()
  49585. ], PointLight.prototype, "shadowAngle", null);
  49586. return PointLight;
  49587. }(BABYLON.ShadowLight));
  49588. BABYLON.PointLight = PointLight;
  49589. })(BABYLON || (BABYLON = {}));
  49590. //# sourceMappingURL=babylon.pointLight.js.map
  49591. var BABYLON;
  49592. (function (BABYLON) {
  49593. /**
  49594. * A directional light is defined by a direction (what a surprise!).
  49595. * The light is emitted from everywhere in the specified direction, and has an infinite range.
  49596. * 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.
  49597. * Documentation: https://doc.babylonjs.com/babylon101/lights
  49598. */
  49599. var DirectionalLight = /** @class */ (function (_super) {
  49600. __extends(DirectionalLight, _super);
  49601. /**
  49602. * Creates a DirectionalLight object in the scene, oriented towards the passed direction (Vector3).
  49603. * The directional light is emitted from everywhere in the given direction.
  49604. * It can cast shawdows.
  49605. * Documentation : http://doc.babylonjs.com/tutorials/lights
  49606. * @param name The friendly name of the light
  49607. * @param direction The direction of the light
  49608. * @param scene The scene the light belongs to
  49609. */
  49610. function DirectionalLight(name, direction, scene) {
  49611. var _this = _super.call(this, name, scene) || this;
  49612. _this._shadowFrustumSize = 0;
  49613. _this._shadowOrthoScale = 0.1;
  49614. /**
  49615. * Automatically compute the projection matrix to best fit (including all the casters)
  49616. * on each frame.
  49617. */
  49618. _this.autoUpdateExtends = true;
  49619. // Cache
  49620. _this._orthoLeft = Number.MAX_VALUE;
  49621. _this._orthoRight = Number.MIN_VALUE;
  49622. _this._orthoTop = Number.MIN_VALUE;
  49623. _this._orthoBottom = Number.MAX_VALUE;
  49624. _this.position = direction.scale(-1.0);
  49625. _this.direction = direction;
  49626. return _this;
  49627. }
  49628. Object.defineProperty(DirectionalLight.prototype, "shadowFrustumSize", {
  49629. /**
  49630. * Fix frustum size for the shadow generation. This is disabled if the value is 0.
  49631. */
  49632. get: function () {
  49633. return this._shadowFrustumSize;
  49634. },
  49635. /**
  49636. * Specifies a fix frustum size for the shadow generation.
  49637. */
  49638. set: function (value) {
  49639. this._shadowFrustumSize = value;
  49640. this.forceProjectionMatrixCompute();
  49641. },
  49642. enumerable: true,
  49643. configurable: true
  49644. });
  49645. Object.defineProperty(DirectionalLight.prototype, "shadowOrthoScale", {
  49646. /**
  49647. * Gets the shadow projection scale against the optimal computed one.
  49648. * 0.1 by default which means that the projection window is increase by 10% from the optimal size.
  49649. * This does not impact in fixed frustum size (shadowFrustumSize being set)
  49650. */
  49651. get: function () {
  49652. return this._shadowOrthoScale;
  49653. },
  49654. /**
  49655. * Sets the shadow projection scale against the optimal computed one.
  49656. * 0.1 by default which means that the projection window is increase by 10% from the optimal size.
  49657. * This does not impact in fixed frustum size (shadowFrustumSize being set)
  49658. */
  49659. set: function (value) {
  49660. this._shadowOrthoScale = value;
  49661. this.forceProjectionMatrixCompute();
  49662. },
  49663. enumerable: true,
  49664. configurable: true
  49665. });
  49666. /**
  49667. * Returns the string "DirectionalLight".
  49668. * @return The class name
  49669. */
  49670. DirectionalLight.prototype.getClassName = function () {
  49671. return "DirectionalLight";
  49672. };
  49673. /**
  49674. * Returns the integer 1.
  49675. * @return The light Type id as a constant defines in Light.LIGHTTYPEID_x
  49676. */
  49677. DirectionalLight.prototype.getTypeID = function () {
  49678. return BABYLON.Light.LIGHTTYPEID_DIRECTIONALLIGHT;
  49679. };
  49680. /**
  49681. * Sets the passed matrix "matrix" as projection matrix for the shadows cast by the light according to the passed view matrix.
  49682. * Returns the DirectionalLight Shadow projection matrix.
  49683. */
  49684. DirectionalLight.prototype._setDefaultShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  49685. if (this.shadowFrustumSize > 0) {
  49686. this._setDefaultFixedFrustumShadowProjectionMatrix(matrix, viewMatrix);
  49687. }
  49688. else {
  49689. this._setDefaultAutoExtendShadowProjectionMatrix(matrix, viewMatrix, renderList);
  49690. }
  49691. };
  49692. /**
  49693. * Sets the passed matrix "matrix" as fixed frustum projection matrix for the shadows cast by the light according to the passed view matrix.
  49694. * Returns the DirectionalLight Shadow projection matrix.
  49695. */
  49696. DirectionalLight.prototype._setDefaultFixedFrustumShadowProjectionMatrix = function (matrix, viewMatrix) {
  49697. var activeCamera = this.getScene().activeCamera;
  49698. if (!activeCamera) {
  49699. return;
  49700. }
  49701. BABYLON.Matrix.OrthoLHToRef(this.shadowFrustumSize, this.shadowFrustumSize, this.shadowMinZ !== undefined ? this.shadowMinZ : activeCamera.minZ, this.shadowMaxZ !== undefined ? this.shadowMaxZ : activeCamera.maxZ, matrix);
  49702. };
  49703. /**
  49704. * Sets the passed matrix "matrix" as auto extend projection matrix for the shadows cast by the light according to the passed view matrix.
  49705. * Returns the DirectionalLight Shadow projection matrix.
  49706. */
  49707. DirectionalLight.prototype._setDefaultAutoExtendShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  49708. var activeCamera = this.getScene().activeCamera;
  49709. if (!activeCamera) {
  49710. return;
  49711. }
  49712. // Check extends
  49713. if (this.autoUpdateExtends || this._orthoLeft === Number.MAX_VALUE) {
  49714. var tempVector3 = BABYLON.Vector3.Zero();
  49715. this._orthoLeft = Number.MAX_VALUE;
  49716. this._orthoRight = Number.MIN_VALUE;
  49717. this._orthoTop = Number.MIN_VALUE;
  49718. this._orthoBottom = Number.MAX_VALUE;
  49719. for (var meshIndex = 0; meshIndex < renderList.length; meshIndex++) {
  49720. var mesh = renderList[meshIndex];
  49721. if (!mesh) {
  49722. continue;
  49723. }
  49724. var boundingInfo = mesh.getBoundingInfo();
  49725. var boundingBox = boundingInfo.boundingBox;
  49726. for (var index = 0; index < boundingBox.vectorsWorld.length; index++) {
  49727. BABYLON.Vector3.TransformCoordinatesToRef(boundingBox.vectorsWorld[index], viewMatrix, tempVector3);
  49728. if (tempVector3.x < this._orthoLeft)
  49729. this._orthoLeft = tempVector3.x;
  49730. if (tempVector3.y < this._orthoBottom)
  49731. this._orthoBottom = tempVector3.y;
  49732. if (tempVector3.x > this._orthoRight)
  49733. this._orthoRight = tempVector3.x;
  49734. if (tempVector3.y > this._orthoTop)
  49735. this._orthoTop = tempVector3.y;
  49736. }
  49737. }
  49738. }
  49739. var xOffset = this._orthoRight - this._orthoLeft;
  49740. var yOffset = this._orthoTop - this._orthoBottom;
  49741. 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);
  49742. };
  49743. DirectionalLight.prototype._buildUniformLayout = function () {
  49744. this._uniformBuffer.addUniform("vLightData", 4);
  49745. this._uniformBuffer.addUniform("vLightDiffuse", 4);
  49746. this._uniformBuffer.addUniform("vLightSpecular", 3);
  49747. this._uniformBuffer.addUniform("shadowsInfo", 3);
  49748. this._uniformBuffer.addUniform("depthValues", 2);
  49749. this._uniformBuffer.create();
  49750. };
  49751. /**
  49752. * Sets the passed Effect object with the DirectionalLight transformed position (or position if not parented) and the passed name.
  49753. * @param effect The effect to update
  49754. * @param lightIndex The index of the light in the effect to update
  49755. * @returns The directional light
  49756. */
  49757. DirectionalLight.prototype.transferToEffect = function (effect, lightIndex) {
  49758. if (this.computeTransformedInformation()) {
  49759. this._uniformBuffer.updateFloat4("vLightData", this.transformedDirection.x, this.transformedDirection.y, this.transformedDirection.z, 1, lightIndex);
  49760. return this;
  49761. }
  49762. this._uniformBuffer.updateFloat4("vLightData", this.direction.x, this.direction.y, this.direction.z, 1, lightIndex);
  49763. return this;
  49764. };
  49765. /**
  49766. * Gets the minZ used for shadow according to both the scene and the light.
  49767. *
  49768. * Values are fixed on directional lights as it relies on an ortho projection hence the need to convert being
  49769. * -1 and 1 to 0 and 1 doing (depth + min) / (min + max) -> (depth + 1) / (1 + 1) -> (depth * 0.5) + 0.5.
  49770. * @param activeCamera The camera we are returning the min for
  49771. * @returns the depth min z
  49772. */
  49773. DirectionalLight.prototype.getDepthMinZ = function (activeCamera) {
  49774. return 1;
  49775. };
  49776. /**
  49777. * Gets the maxZ used for shadow according to both the scene and the light.
  49778. *
  49779. * Values are fixed on directional lights as it relies on an ortho projection hence the need to convert being
  49780. * -1 and 1 to 0 and 1 doing (depth + min) / (min + max) -> (depth + 1) / (1 + 1) -> (depth * 0.5) + 0.5.
  49781. * @param activeCamera The camera we are returning the max for
  49782. * @returns the depth max z
  49783. */
  49784. DirectionalLight.prototype.getDepthMaxZ = function (activeCamera) {
  49785. return 1;
  49786. };
  49787. __decorate([
  49788. BABYLON.serialize()
  49789. ], DirectionalLight.prototype, "shadowFrustumSize", null);
  49790. __decorate([
  49791. BABYLON.serialize()
  49792. ], DirectionalLight.prototype, "shadowOrthoScale", null);
  49793. __decorate([
  49794. BABYLON.serialize()
  49795. ], DirectionalLight.prototype, "autoUpdateExtends", void 0);
  49796. return DirectionalLight;
  49797. }(BABYLON.ShadowLight));
  49798. BABYLON.DirectionalLight = DirectionalLight;
  49799. })(BABYLON || (BABYLON = {}));
  49800. //# sourceMappingURL=babylon.directionalLight.js.map
  49801. var BABYLON;
  49802. (function (BABYLON) {
  49803. /**
  49804. * A spot light is defined by a position, a direction, an angle, and an exponent.
  49805. * These values define a cone of light starting from the position, emitting toward the direction.
  49806. * The angle, in radians, defines the size (field of illumination) of the spotlight's conical beam,
  49807. * and the exponent defines the speed of the decay of the light with distance (reach).
  49808. * Documentation: https://doc.babylonjs.com/babylon101/lights
  49809. */
  49810. var SpotLight = /** @class */ (function (_super) {
  49811. __extends(SpotLight, _super);
  49812. /**
  49813. * Creates a SpotLight object in the scene. A spot light is a simply light oriented cone.
  49814. * It can cast shadows.
  49815. * Documentation : http://doc.babylonjs.com/tutorials/lights
  49816. * @param name The light friendly name
  49817. * @param position The position of the spot light in the scene
  49818. * @param direction The direction of the light in the scene
  49819. * @param angle The cone angle of the light in Radians
  49820. * @param exponent The light decay speed with the distance from the emission spot
  49821. * @param scene The scene the lights belongs to
  49822. */
  49823. function SpotLight(name, position, direction, angle, exponent, scene) {
  49824. var _this = _super.call(this, name, scene) || this;
  49825. _this._projectionTextureMatrix = BABYLON.Matrix.Zero();
  49826. _this._projectionTextureLightNear = 1e-6;
  49827. _this._projectionTextureLightFar = 1000.0;
  49828. _this._projectionTextureUpDirection = BABYLON.Vector3.Up();
  49829. _this._projectionTextureViewLightDirty = true;
  49830. _this._projectionTextureProjectionLightDirty = true;
  49831. _this._projectionTextureDirty = true;
  49832. _this._projectionTextureViewTargetVector = BABYLON.Vector3.Zero();
  49833. _this._projectionTextureViewLightMatrix = BABYLON.Matrix.Zero();
  49834. _this._projectionTextureProjectionLightMatrix = BABYLON.Matrix.Zero();
  49835. _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);
  49836. _this.position = position;
  49837. _this.direction = direction;
  49838. _this.angle = angle;
  49839. _this.exponent = exponent;
  49840. return _this;
  49841. }
  49842. Object.defineProperty(SpotLight.prototype, "angle", {
  49843. /**
  49844. * Gets the cone angle of the spot light in Radians.
  49845. */
  49846. get: function () {
  49847. return this._angle;
  49848. },
  49849. /**
  49850. * Sets the cone angle of the spot light in Radians.
  49851. */
  49852. set: function (value) {
  49853. this._angle = value;
  49854. this._projectionTextureProjectionLightDirty = true;
  49855. this.forceProjectionMatrixCompute();
  49856. },
  49857. enumerable: true,
  49858. configurable: true
  49859. });
  49860. Object.defineProperty(SpotLight.prototype, "shadowAngleScale", {
  49861. /**
  49862. * Allows scaling the angle of the light for shadow generation only.
  49863. */
  49864. get: function () {
  49865. return this._shadowAngleScale;
  49866. },
  49867. /**
  49868. * Allows scaling the angle of the light for shadow generation only.
  49869. */
  49870. set: function (value) {
  49871. this._shadowAngleScale = value;
  49872. this.forceProjectionMatrixCompute();
  49873. },
  49874. enumerable: true,
  49875. configurable: true
  49876. });
  49877. Object.defineProperty(SpotLight.prototype, "projectionTextureMatrix", {
  49878. /**
  49879. * Allows reading the projecton texture
  49880. */
  49881. get: function () {
  49882. return this._projectionTextureMatrix;
  49883. },
  49884. enumerable: true,
  49885. configurable: true
  49886. });
  49887. ;
  49888. Object.defineProperty(SpotLight.prototype, "projectionTextureLightNear", {
  49889. /**
  49890. * Gets the near clip of the Spotlight for texture projection.
  49891. */
  49892. get: function () {
  49893. return this._projectionTextureLightNear;
  49894. },
  49895. /**
  49896. * Sets the near clip of the Spotlight for texture projection.
  49897. */
  49898. set: function (value) {
  49899. this._projectionTextureLightNear = value;
  49900. this._projectionTextureProjectionLightDirty = true;
  49901. },
  49902. enumerable: true,
  49903. configurable: true
  49904. });
  49905. Object.defineProperty(SpotLight.prototype, "projectionTextureLightFar", {
  49906. /**
  49907. * Gets the far clip of the Spotlight for texture projection.
  49908. */
  49909. get: function () {
  49910. return this._projectionTextureLightFar;
  49911. },
  49912. /**
  49913. * Sets the far clip of the Spotlight for texture projection.
  49914. */
  49915. set: function (value) {
  49916. this._projectionTextureLightFar = value;
  49917. this._projectionTextureProjectionLightDirty = true;
  49918. },
  49919. enumerable: true,
  49920. configurable: true
  49921. });
  49922. Object.defineProperty(SpotLight.prototype, "projectionTextureUpDirection", {
  49923. /**
  49924. * Gets the Up vector of the Spotlight for texture projection.
  49925. */
  49926. get: function () {
  49927. return this._projectionTextureUpDirection;
  49928. },
  49929. /**
  49930. * Sets the Up vector of the Spotlight for texture projection.
  49931. */
  49932. set: function (value) {
  49933. this._projectionTextureUpDirection = value;
  49934. this._projectionTextureProjectionLightDirty = true;
  49935. },
  49936. enumerable: true,
  49937. configurable: true
  49938. });
  49939. Object.defineProperty(SpotLight.prototype, "projectionTexture", {
  49940. /**
  49941. * Gets the projection texture of the light.
  49942. */
  49943. get: function () {
  49944. return this._projectionTexture;
  49945. },
  49946. /**
  49947. * Sets the projection texture of the light.
  49948. */
  49949. set: function (value) {
  49950. this._projectionTexture = value;
  49951. this._projectionTextureDirty = true;
  49952. },
  49953. enumerable: true,
  49954. configurable: true
  49955. });
  49956. /**
  49957. * Returns the string "SpotLight".
  49958. * @returns the class name
  49959. */
  49960. SpotLight.prototype.getClassName = function () {
  49961. return "SpotLight";
  49962. };
  49963. /**
  49964. * Returns the integer 2.
  49965. * @returns The light Type id as a constant defines in Light.LIGHTTYPEID_x
  49966. */
  49967. SpotLight.prototype.getTypeID = function () {
  49968. return BABYLON.Light.LIGHTTYPEID_SPOTLIGHT;
  49969. };
  49970. /**
  49971. * Overrides the direction setter to recompute the projection texture view light Matrix.
  49972. */
  49973. SpotLight.prototype._setDirection = function (value) {
  49974. _super.prototype._setDirection.call(this, value);
  49975. this._projectionTextureViewLightDirty = true;
  49976. };
  49977. /**
  49978. * Overrides the position setter to recompute the projection texture view light Matrix.
  49979. */
  49980. SpotLight.prototype._setPosition = function (value) {
  49981. _super.prototype._setPosition.call(this, value);
  49982. this._projectionTextureViewLightDirty = true;
  49983. };
  49984. /**
  49985. * 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.
  49986. * Returns the SpotLight.
  49987. */
  49988. SpotLight.prototype._setDefaultShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  49989. var activeCamera = this.getScene().activeCamera;
  49990. if (!activeCamera) {
  49991. return;
  49992. }
  49993. this._shadowAngleScale = this._shadowAngleScale || 1;
  49994. var angle = this._shadowAngleScale * this._angle;
  49995. BABYLON.Matrix.PerspectiveFovLHToRef(angle, 1.0, this.getDepthMinZ(activeCamera), this.getDepthMaxZ(activeCamera), matrix);
  49996. };
  49997. SpotLight.prototype._computeProjectionTextureViewLightMatrix = function () {
  49998. this._projectionTextureViewLightDirty = false;
  49999. this._projectionTextureDirty = true;
  50000. this.position.addToRef(this.direction, this._projectionTextureViewTargetVector);
  50001. BABYLON.Matrix.LookAtLHToRef(this.position, this._projectionTextureViewTargetVector, this._projectionTextureUpDirection, this._projectionTextureViewLightMatrix);
  50002. };
  50003. SpotLight.prototype._computeProjectionTextureProjectionLightMatrix = function () {
  50004. this._projectionTextureProjectionLightDirty = false;
  50005. this._projectionTextureDirty = true;
  50006. var light_far = this.projectionTextureLightFar;
  50007. var light_near = this.projectionTextureLightNear;
  50008. var P = light_far / (light_far - light_near);
  50009. var Q = -P * light_near;
  50010. var S = 1.0 / Math.tan(this._angle / 2.0);
  50011. var A = 1.0;
  50012. 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);
  50013. };
  50014. /**
  50015. * Main function for light texture projection matrix computing.
  50016. */
  50017. SpotLight.prototype._computeProjectionTextureMatrix = function () {
  50018. this._projectionTextureDirty = false;
  50019. this._projectionTextureViewLightMatrix.multiplyToRef(this._projectionTextureProjectionLightMatrix, this._projectionTextureMatrix);
  50020. this._projectionTextureMatrix.multiplyToRef(this._projectionTextureScalingMatrix, this._projectionTextureMatrix);
  50021. };
  50022. SpotLight.prototype._buildUniformLayout = function () {
  50023. this._uniformBuffer.addUniform("vLightData", 4);
  50024. this._uniformBuffer.addUniform("vLightDiffuse", 4);
  50025. this._uniformBuffer.addUniform("vLightSpecular", 3);
  50026. this._uniformBuffer.addUniform("vLightDirection", 3);
  50027. this._uniformBuffer.addUniform("shadowsInfo", 3);
  50028. this._uniformBuffer.addUniform("depthValues", 2);
  50029. this._uniformBuffer.create();
  50030. };
  50031. /**
  50032. * Sets the passed Effect object with the SpotLight transfomed position (or position if not parented) and normalized direction.
  50033. * @param effect The effect to update
  50034. * @param lightIndex The index of the light in the effect to update
  50035. * @returns The spot light
  50036. */
  50037. SpotLight.prototype.transferToEffect = function (effect, lightIndex) {
  50038. var normalizeDirection;
  50039. if (this.computeTransformedInformation()) {
  50040. this._uniformBuffer.updateFloat4("vLightData", this.transformedPosition.x, this.transformedPosition.y, this.transformedPosition.z, this.exponent, lightIndex);
  50041. normalizeDirection = BABYLON.Vector3.Normalize(this.transformedDirection);
  50042. }
  50043. else {
  50044. this._uniformBuffer.updateFloat4("vLightData", this.position.x, this.position.y, this.position.z, this.exponent, lightIndex);
  50045. normalizeDirection = BABYLON.Vector3.Normalize(this.direction);
  50046. }
  50047. this._uniformBuffer.updateFloat4("vLightDirection", normalizeDirection.x, normalizeDirection.y, normalizeDirection.z, Math.cos(this.angle * 0.5), lightIndex);
  50048. if (this.projectionTexture && this.projectionTexture.isReady()) {
  50049. if (this._projectionTextureViewLightDirty) {
  50050. this._computeProjectionTextureViewLightMatrix();
  50051. }
  50052. if (this._projectionTextureProjectionLightDirty) {
  50053. this._computeProjectionTextureProjectionLightMatrix();
  50054. }
  50055. if (this._projectionTextureDirty) {
  50056. this._computeProjectionTextureMatrix();
  50057. }
  50058. effect.setMatrix("textureProjectionMatrix" + lightIndex, this._projectionTextureMatrix);
  50059. effect.setTexture("projectionLightSampler" + lightIndex, this.projectionTexture);
  50060. }
  50061. return this;
  50062. };
  50063. /**
  50064. * Disposes the light and the associated resources.
  50065. */
  50066. SpotLight.prototype.dispose = function () {
  50067. _super.prototype.dispose.call(this);
  50068. if (this._projectionTexture) {
  50069. this._projectionTexture.dispose();
  50070. }
  50071. };
  50072. __decorate([
  50073. BABYLON.serialize()
  50074. ], SpotLight.prototype, "angle", null);
  50075. __decorate([
  50076. BABYLON.serialize()
  50077. ], SpotLight.prototype, "shadowAngleScale", null);
  50078. __decorate([
  50079. BABYLON.serialize()
  50080. ], SpotLight.prototype, "exponent", void 0);
  50081. __decorate([
  50082. BABYLON.serialize()
  50083. ], SpotLight.prototype, "projectionTextureLightNear", null);
  50084. __decorate([
  50085. BABYLON.serialize()
  50086. ], SpotLight.prototype, "projectionTextureLightFar", null);
  50087. __decorate([
  50088. BABYLON.serialize()
  50089. ], SpotLight.prototype, "projectionTextureUpDirection", null);
  50090. __decorate([
  50091. BABYLON.serializeAsTexture("projectedLightTexture")
  50092. ], SpotLight.prototype, "_projectionTexture", void 0);
  50093. return SpotLight;
  50094. }(BABYLON.ShadowLight));
  50095. BABYLON.SpotLight = SpotLight;
  50096. })(BABYLON || (BABYLON = {}));
  50097. //# sourceMappingURL=babylon.spotLight.js.map
  50098. var BABYLON;
  50099. (function (BABYLON) {
  50100. /**
  50101. * Class used to override all child animations of a given target
  50102. */
  50103. var AnimationPropertiesOverride = /** @class */ (function () {
  50104. function AnimationPropertiesOverride() {
  50105. /**
  50106. * Gets or sets a value indicating if animation blending must be used
  50107. */
  50108. this.enableBlending = false;
  50109. /**
  50110. * Gets or sets the blending speed to use when enableBlending is true
  50111. */
  50112. this.blendingSpeed = 0.01;
  50113. /**
  50114. * Gets or sets the default loop mode to use
  50115. */
  50116. this.loopMode = BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE;
  50117. }
  50118. return AnimationPropertiesOverride;
  50119. }());
  50120. BABYLON.AnimationPropertiesOverride = AnimationPropertiesOverride;
  50121. })(BABYLON || (BABYLON = {}));
  50122. //# sourceMappingURL=babylon.animationPropertiesOverride.js.map
  50123. var BABYLON;
  50124. (function (BABYLON) {
  50125. /**
  50126. * Represents the range of an animation
  50127. */
  50128. var AnimationRange = /** @class */ (function () {
  50129. /**
  50130. * Initializes the range of an animation
  50131. * @param name The name of the animation range
  50132. * @param from The starting frame of the animation
  50133. * @param to The ending frame of the animation
  50134. */
  50135. function AnimationRange(
  50136. /**The name of the animation range**/
  50137. name,
  50138. /**The starting frame of the animation */
  50139. from,
  50140. /**The ending frame of the animation*/
  50141. to) {
  50142. this.name = name;
  50143. this.from = from;
  50144. this.to = to;
  50145. }
  50146. /**
  50147. * Makes a copy of the animation range
  50148. * @returns A copy of the animation range
  50149. */
  50150. AnimationRange.prototype.clone = function () {
  50151. return new AnimationRange(this.name, this.from, this.to);
  50152. };
  50153. return AnimationRange;
  50154. }());
  50155. BABYLON.AnimationRange = AnimationRange;
  50156. /**
  50157. * Composed of a frame, and an action function
  50158. */
  50159. var AnimationEvent = /** @class */ (function () {
  50160. /**
  50161. * Initializes the animation event
  50162. * @param frame The frame for which the event is triggered
  50163. * @param action The event to perform when triggered
  50164. * @param onlyOnce Specifies if the event should be triggered only once
  50165. */
  50166. function AnimationEvent(
  50167. /** The frame for which the event is triggered **/
  50168. frame,
  50169. /** The event to perform when triggered **/
  50170. action,
  50171. /** Specifies if the event should be triggered only once**/
  50172. onlyOnce) {
  50173. this.frame = frame;
  50174. this.action = action;
  50175. this.onlyOnce = onlyOnce;
  50176. /**
  50177. * Specifies if the animation event is done
  50178. */
  50179. this.isDone = false;
  50180. }
  50181. return AnimationEvent;
  50182. }());
  50183. BABYLON.AnimationEvent = AnimationEvent;
  50184. /**
  50185. * A cursor which tracks a point on a path
  50186. */
  50187. var PathCursor = /** @class */ (function () {
  50188. /**
  50189. * Initializes the path cursor
  50190. * @param path The path to track
  50191. */
  50192. function PathCursor(path) {
  50193. this.path = path;
  50194. /**
  50195. * Stores path cursor callbacks for when an onchange event is triggered
  50196. */
  50197. this._onchange = new Array();
  50198. /**
  50199. * The value of the path cursor
  50200. */
  50201. this.value = 0;
  50202. /**
  50203. * The animation array of the path cursor
  50204. */
  50205. this.animations = new Array();
  50206. }
  50207. /**
  50208. * Gets the cursor point on the path
  50209. * @returns A point on the path cursor at the cursor location
  50210. */
  50211. PathCursor.prototype.getPoint = function () {
  50212. var point = this.path.getPointAtLengthPosition(this.value);
  50213. return new BABYLON.Vector3(point.x, 0, point.y);
  50214. };
  50215. /**
  50216. * Moves the cursor ahead by the step amount
  50217. * @param step The amount to move the cursor forward
  50218. * @returns This path cursor
  50219. */
  50220. PathCursor.prototype.moveAhead = function (step) {
  50221. if (step === void 0) { step = 0.002; }
  50222. this.move(step);
  50223. return this;
  50224. };
  50225. /**
  50226. * Moves the cursor behind by the step amount
  50227. * @param step The amount to move the cursor back
  50228. * @returns This path cursor
  50229. */
  50230. PathCursor.prototype.moveBack = function (step) {
  50231. if (step === void 0) { step = 0.002; }
  50232. this.move(-step);
  50233. return this;
  50234. };
  50235. /**
  50236. * Moves the cursor by the step amount
  50237. * If the step amount is greater than one, an exception is thrown
  50238. * @param step The amount to move the cursor
  50239. * @returns This path cursor
  50240. */
  50241. PathCursor.prototype.move = function (step) {
  50242. if (Math.abs(step) > 1) {
  50243. throw "step size should be less than 1.";
  50244. }
  50245. this.value += step;
  50246. this.ensureLimits();
  50247. this.raiseOnChange();
  50248. return this;
  50249. };
  50250. /**
  50251. * Ensures that the value is limited between zero and one
  50252. * @returns This path cursor
  50253. */
  50254. PathCursor.prototype.ensureLimits = function () {
  50255. while (this.value > 1) {
  50256. this.value -= 1;
  50257. }
  50258. while (this.value < 0) {
  50259. this.value += 1;
  50260. }
  50261. return this;
  50262. };
  50263. /**
  50264. * Runs onchange callbacks on change (used by the animation engine)
  50265. * @returns This path cursor
  50266. */
  50267. PathCursor.prototype.raiseOnChange = function () {
  50268. var _this = this;
  50269. this._onchange.forEach(function (f) { return f(_this); });
  50270. return this;
  50271. };
  50272. /**
  50273. * Executes a function on change
  50274. * @param f A path cursor onchange callback
  50275. * @returns This path cursor
  50276. */
  50277. PathCursor.prototype.onchange = function (f) {
  50278. this._onchange.push(f);
  50279. return this;
  50280. };
  50281. return PathCursor;
  50282. }());
  50283. BABYLON.PathCursor = PathCursor;
  50284. /**
  50285. * Enum for the animation key frame interpolation type
  50286. */
  50287. var AnimationKeyInterpolation;
  50288. (function (AnimationKeyInterpolation) {
  50289. /**
  50290. * Do not interpolate between keys and use the start key value only. Tangents are ignored
  50291. */
  50292. AnimationKeyInterpolation[AnimationKeyInterpolation["STEP"] = 1] = "STEP";
  50293. })(AnimationKeyInterpolation = BABYLON.AnimationKeyInterpolation || (BABYLON.AnimationKeyInterpolation = {}));
  50294. /**
  50295. * Class used to store any kind of animation
  50296. */
  50297. var Animation = /** @class */ (function () {
  50298. /**
  50299. * Initializes the animation
  50300. * @param name Name of the animation
  50301. * @param targetProperty Property to animate
  50302. * @param framePerSecond The frames per second of the animation
  50303. * @param dataType The data type of the animation
  50304. * @param loopMode The loop mode of the animation
  50305. * @param enableBlendings Specifies if blending should be enabled
  50306. */
  50307. function Animation(
  50308. /**Name of the animation */
  50309. name,
  50310. /**Property to animate */
  50311. targetProperty,
  50312. /**The frames per second of the animation */
  50313. framePerSecond,
  50314. /**The data type of the animation */
  50315. dataType,
  50316. /**The loop mode of the animation */
  50317. loopMode,
  50318. /**Specifies if blending should be enabled */
  50319. enableBlending) {
  50320. this.name = name;
  50321. this.targetProperty = targetProperty;
  50322. this.framePerSecond = framePerSecond;
  50323. this.dataType = dataType;
  50324. this.loopMode = loopMode;
  50325. this.enableBlending = enableBlending;
  50326. /**
  50327. * @hidden Internal use only
  50328. */
  50329. this._runtimeAnimations = new Array();
  50330. /**
  50331. * The set of event that will be linked to this animation
  50332. */
  50333. this._events = new Array();
  50334. /**
  50335. * Stores the blending speed of the animation
  50336. */
  50337. this.blendingSpeed = 0.01;
  50338. /**
  50339. * Stores the animation ranges for the animation
  50340. */
  50341. this._ranges = {};
  50342. this.targetPropertyPath = targetProperty.split(".");
  50343. this.dataType = dataType;
  50344. this.loopMode = loopMode === undefined ? Animation.ANIMATIONLOOPMODE_CYCLE : loopMode;
  50345. }
  50346. /**
  50347. * @hidden Internal use
  50348. */
  50349. Animation._PrepareAnimation = function (name, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction) {
  50350. var dataType = undefined;
  50351. if (!isNaN(parseFloat(from)) && isFinite(from)) {
  50352. dataType = Animation.ANIMATIONTYPE_FLOAT;
  50353. }
  50354. else if (from instanceof BABYLON.Quaternion) {
  50355. dataType = Animation.ANIMATIONTYPE_QUATERNION;
  50356. }
  50357. else if (from instanceof BABYLON.Vector3) {
  50358. dataType = Animation.ANIMATIONTYPE_VECTOR3;
  50359. }
  50360. else if (from instanceof BABYLON.Vector2) {
  50361. dataType = Animation.ANIMATIONTYPE_VECTOR2;
  50362. }
  50363. else if (from instanceof BABYLON.Color3) {
  50364. dataType = Animation.ANIMATIONTYPE_COLOR3;
  50365. }
  50366. else if (from instanceof BABYLON.Size) {
  50367. dataType = Animation.ANIMATIONTYPE_SIZE;
  50368. }
  50369. if (dataType == undefined) {
  50370. return null;
  50371. }
  50372. var animation = new Animation(name, targetProperty, framePerSecond, dataType, loopMode);
  50373. var keys = [{ frame: 0, value: from }, { frame: totalFrame, value: to }];
  50374. animation.setKeys(keys);
  50375. if (easingFunction !== undefined) {
  50376. animation.setEasingFunction(easingFunction);
  50377. }
  50378. return animation;
  50379. };
  50380. /**
  50381. * Sets up an animation
  50382. * @param property The property to animate
  50383. * @param animationType The animation type to apply
  50384. * @param framePerSecond The frames per second of the animation
  50385. * @param easingFunction The easing function used in the animation
  50386. * @returns The created animation
  50387. */
  50388. Animation.CreateAnimation = function (property, animationType, framePerSecond, easingFunction) {
  50389. var animation = new Animation(property + "Animation", property, framePerSecond, animationType, Animation.ANIMATIONLOOPMODE_CONSTANT);
  50390. animation.setEasingFunction(easingFunction);
  50391. return animation;
  50392. };
  50393. /**
  50394. * Create and start an animation on a node
  50395. * @param name defines the name of the global animation that will be run on all nodes
  50396. * @param node defines the root node where the animation will take place
  50397. * @param targetProperty defines property to animate
  50398. * @param framePerSecond defines the number of frame per second yo use
  50399. * @param totalFrame defines the number of frames in total
  50400. * @param from defines the initial value
  50401. * @param to defines the final value
  50402. * @param loopMode defines which loop mode you want to use (off by default)
  50403. * @param easingFunction defines the easing function to use (linear by default)
  50404. * @param onAnimationEnd defines the callback to call when animation end
  50405. * @returns the animatable created for this animation
  50406. */
  50407. Animation.CreateAndStartAnimation = function (name, node, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction, onAnimationEnd) {
  50408. var animation = Animation._PrepareAnimation(name, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction);
  50409. if (!animation) {
  50410. return null;
  50411. }
  50412. return node.getScene().beginDirectAnimation(node, [animation], 0, totalFrame, (animation.loopMode === 1), 1.0, onAnimationEnd);
  50413. };
  50414. /**
  50415. * Create and start an animation on a node and its descendants
  50416. * @param name defines the name of the global animation that will be run on all nodes
  50417. * @param node defines the root node where the animation will take place
  50418. * @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
  50419. * @param targetProperty defines property to animate
  50420. * @param framePerSecond defines the number of frame per second to use
  50421. * @param totalFrame defines the number of frames in total
  50422. * @param from defines the initial value
  50423. * @param to defines the final value
  50424. * @param loopMode defines which loop mode you want to use (off by default)
  50425. * @param easingFunction defines the easing function to use (linear by default)
  50426. * @param onAnimationEnd defines the callback to call when an animation ends (will be called once per node)
  50427. * @returns the list of animatables created for all nodes
  50428. * @example https://www.babylonjs-playground.com/#MH0VLI
  50429. */
  50430. Animation.CreateAndStartHierarchyAnimation = function (name, node, directDescendantsOnly, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction, onAnimationEnd) {
  50431. var animation = Animation._PrepareAnimation(name, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction);
  50432. if (!animation) {
  50433. return null;
  50434. }
  50435. var scene = node.getScene();
  50436. return scene.beginDirectHierarchyAnimation(node, directDescendantsOnly, [animation], 0, totalFrame, (animation.loopMode === 1), 1.0, onAnimationEnd);
  50437. };
  50438. /**
  50439. * Creates a new animation, merges it with the existing animations and starts it
  50440. * @param name Name of the animation
  50441. * @param node Node which contains the scene that begins the animations
  50442. * @param targetProperty Specifies which property to animate
  50443. * @param framePerSecond The frames per second of the animation
  50444. * @param totalFrame The total number of frames
  50445. * @param from The frame at the beginning of the animation
  50446. * @param to The frame at the end of the animation
  50447. * @param loopMode Specifies the loop mode of the animation
  50448. * @param easingFunction (Optional) The easing function of the animation, which allow custom mathematical formulas for animations
  50449. * @param onAnimationEnd Callback to run once the animation is complete
  50450. * @returns Nullable animation
  50451. */
  50452. Animation.CreateMergeAndStartAnimation = function (name, node, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction, onAnimationEnd) {
  50453. var animation = Animation._PrepareAnimation(name, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction);
  50454. if (!animation) {
  50455. return null;
  50456. }
  50457. node.animations.push(animation);
  50458. return node.getScene().beginAnimation(node, 0, totalFrame, (animation.loopMode === 1), 1.0, onAnimationEnd);
  50459. };
  50460. /**
  50461. * Transition property of the Camera to the target Value
  50462. * @param property The property to transition
  50463. * @param targetValue The target Value of the property
  50464. * @param host The object where the property to animate belongs
  50465. * @param scene Scene used to run the animation
  50466. * @param frameRate Framerate (in frame/s) to use
  50467. * @param transition The transition type we want to use
  50468. * @param duration The duration of the animation, in milliseconds
  50469. * @param onAnimationEnd Callback trigger at the end of the animation
  50470. * @returns Nullable animation
  50471. */
  50472. Animation.TransitionTo = function (property, targetValue, host, scene, frameRate, transition, duration, onAnimationEnd) {
  50473. if (onAnimationEnd === void 0) { onAnimationEnd = null; }
  50474. if (duration <= 0) {
  50475. host[property] = targetValue;
  50476. if (onAnimationEnd) {
  50477. onAnimationEnd();
  50478. }
  50479. return null;
  50480. }
  50481. var endFrame = frameRate * (duration / 1000);
  50482. transition.setKeys([{
  50483. frame: 0,
  50484. value: host[property].clone ? host[property].clone() : host[property]
  50485. },
  50486. {
  50487. frame: endFrame,
  50488. value: targetValue
  50489. }]);
  50490. if (!host.animations) {
  50491. host.animations = [];
  50492. }
  50493. host.animations.push(transition);
  50494. var animation = scene.beginAnimation(host, 0, endFrame, false);
  50495. animation.onAnimationEnd = onAnimationEnd;
  50496. return animation;
  50497. };
  50498. Object.defineProperty(Animation.prototype, "runtimeAnimations", {
  50499. /**
  50500. * Return the array of runtime animations currently using this animation
  50501. */
  50502. get: function () {
  50503. return this._runtimeAnimations;
  50504. },
  50505. enumerable: true,
  50506. configurable: true
  50507. });
  50508. Object.defineProperty(Animation.prototype, "hasRunningRuntimeAnimations", {
  50509. /**
  50510. * Specifies if any of the runtime animations are currently running
  50511. */
  50512. get: function () {
  50513. for (var _i = 0, _a = this._runtimeAnimations; _i < _a.length; _i++) {
  50514. var runtimeAnimation = _a[_i];
  50515. if (!runtimeAnimation.isStopped) {
  50516. return true;
  50517. }
  50518. }
  50519. return false;
  50520. },
  50521. enumerable: true,
  50522. configurable: true
  50523. });
  50524. // Methods
  50525. /**
  50526. * Converts the animation to a string
  50527. * @param fullDetails support for multiple levels of logging within scene loading
  50528. * @returns String form of the animation
  50529. */
  50530. Animation.prototype.toString = function (fullDetails) {
  50531. var ret = "Name: " + this.name + ", property: " + this.targetProperty;
  50532. ret += ", datatype: " + (["Float", "Vector3", "Quaternion", "Matrix", "Color3", "Vector2"])[this.dataType];
  50533. ret += ", nKeys: " + (this._keys ? this._keys.length : "none");
  50534. ret += ", nRanges: " + (this._ranges ? Object.keys(this._ranges).length : "none");
  50535. if (fullDetails) {
  50536. ret += ", Ranges: {";
  50537. var first = true;
  50538. for (var name in this._ranges) {
  50539. if (first) {
  50540. ret += ", ";
  50541. first = false;
  50542. }
  50543. ret += name;
  50544. }
  50545. ret += "}";
  50546. }
  50547. return ret;
  50548. };
  50549. /**
  50550. * Add an event to this animation
  50551. * @param event Event to add
  50552. */
  50553. Animation.prototype.addEvent = function (event) {
  50554. this._events.push(event);
  50555. };
  50556. /**
  50557. * Remove all events found at the given frame
  50558. * @param frame The frame to remove events from
  50559. */
  50560. Animation.prototype.removeEvents = function (frame) {
  50561. for (var index = 0; index < this._events.length; index++) {
  50562. if (this._events[index].frame === frame) {
  50563. this._events.splice(index, 1);
  50564. index--;
  50565. }
  50566. }
  50567. };
  50568. /**
  50569. * Retrieves all the events from the animation
  50570. * @returns Events from the animation
  50571. */
  50572. Animation.prototype.getEvents = function () {
  50573. return this._events;
  50574. };
  50575. /**
  50576. * Creates an animation range
  50577. * @param name Name of the animation range
  50578. * @param from Starting frame of the animation range
  50579. * @param to Ending frame of the animation
  50580. */
  50581. Animation.prototype.createRange = function (name, from, to) {
  50582. // check name not already in use; could happen for bones after serialized
  50583. if (!this._ranges[name]) {
  50584. this._ranges[name] = new AnimationRange(name, from, to);
  50585. }
  50586. };
  50587. /**
  50588. * Deletes an animation range by name
  50589. * @param name Name of the animation range to delete
  50590. * @param deleteFrames Specifies if the key frames for the range should also be deleted (true) or not (false)
  50591. */
  50592. Animation.prototype.deleteRange = function (name, deleteFrames) {
  50593. if (deleteFrames === void 0) { deleteFrames = true; }
  50594. var range = this._ranges[name];
  50595. if (!range) {
  50596. return;
  50597. }
  50598. if (deleteFrames) {
  50599. var from = range.from;
  50600. var to = range.to;
  50601. // this loop MUST go high to low for multiple splices to work
  50602. for (var key = this._keys.length - 1; key >= 0; key--) {
  50603. if (this._keys[key].frame >= from && this._keys[key].frame <= to) {
  50604. this._keys.splice(key, 1);
  50605. }
  50606. }
  50607. }
  50608. this._ranges[name] = null; // said much faster than 'delete this._range[name]'
  50609. };
  50610. /**
  50611. * Gets the animation range by name, or null if not defined
  50612. * @param name Name of the animation range
  50613. * @returns Nullable animation range
  50614. */
  50615. Animation.prototype.getRange = function (name) {
  50616. return this._ranges[name];
  50617. };
  50618. /**
  50619. * Gets the key frames from the animation
  50620. * @returns The key frames of the animation
  50621. */
  50622. Animation.prototype.getKeys = function () {
  50623. return this._keys;
  50624. };
  50625. /**
  50626. * Gets the highest frame rate of the animation
  50627. * @returns Highest frame rate of the animation
  50628. */
  50629. Animation.prototype.getHighestFrame = function () {
  50630. var ret = 0;
  50631. for (var key = 0, nKeys = this._keys.length; key < nKeys; key++) {
  50632. if (ret < this._keys[key].frame) {
  50633. ret = this._keys[key].frame;
  50634. }
  50635. }
  50636. return ret;
  50637. };
  50638. /**
  50639. * Gets the easing function of the animation
  50640. * @returns Easing function of the animation
  50641. */
  50642. Animation.prototype.getEasingFunction = function () {
  50643. return this._easingFunction;
  50644. };
  50645. /**
  50646. * Sets the easing function of the animation
  50647. * @param easingFunction A custom mathematical formula for animation
  50648. */
  50649. Animation.prototype.setEasingFunction = function (easingFunction) {
  50650. this._easingFunction = easingFunction;
  50651. };
  50652. /**
  50653. * Interpolates a scalar linearly
  50654. * @param startValue Start value of the animation curve
  50655. * @param endValue End value of the animation curve
  50656. * @param gradient Scalar amount to interpolate
  50657. * @returns Interpolated scalar value
  50658. */
  50659. Animation.prototype.floatInterpolateFunction = function (startValue, endValue, gradient) {
  50660. return BABYLON.Scalar.Lerp(startValue, endValue, gradient);
  50661. };
  50662. /**
  50663. * Interpolates a scalar cubically
  50664. * @param startValue Start value of the animation curve
  50665. * @param outTangent End tangent of the animation
  50666. * @param endValue End value of the animation curve
  50667. * @param inTangent Start tangent of the animation curve
  50668. * @param gradient Scalar amount to interpolate
  50669. * @returns Interpolated scalar value
  50670. */
  50671. Animation.prototype.floatInterpolateFunctionWithTangents = function (startValue, outTangent, endValue, inTangent, gradient) {
  50672. return BABYLON.Scalar.Hermite(startValue, outTangent, endValue, inTangent, gradient);
  50673. };
  50674. /**
  50675. * Interpolates a quaternion using a spherical linear interpolation
  50676. * @param startValue Start value of the animation curve
  50677. * @param endValue End value of the animation curve
  50678. * @param gradient Scalar amount to interpolate
  50679. * @returns Interpolated quaternion value
  50680. */
  50681. Animation.prototype.quaternionInterpolateFunction = function (startValue, endValue, gradient) {
  50682. return BABYLON.Quaternion.Slerp(startValue, endValue, gradient);
  50683. };
  50684. /**
  50685. * Interpolates a quaternion cubically
  50686. * @param startValue Start value of the animation curve
  50687. * @param outTangent End tangent of the animation curve
  50688. * @param endValue End value of the animation curve
  50689. * @param inTangent Start tangent of the animation curve
  50690. * @param gradient Scalar amount to interpolate
  50691. * @returns Interpolated quaternion value
  50692. */
  50693. Animation.prototype.quaternionInterpolateFunctionWithTangents = function (startValue, outTangent, endValue, inTangent, gradient) {
  50694. return BABYLON.Quaternion.Hermite(startValue, outTangent, endValue, inTangent, gradient).normalize();
  50695. };
  50696. /**
  50697. * Interpolates a Vector3 linearl
  50698. * @param startValue Start value of the animation curve
  50699. * @param endValue End value of the animation curve
  50700. * @param gradient Scalar amount to interpolate
  50701. * @returns Interpolated scalar value
  50702. */
  50703. Animation.prototype.vector3InterpolateFunction = function (startValue, endValue, gradient) {
  50704. return BABYLON.Vector3.Lerp(startValue, endValue, gradient);
  50705. };
  50706. /**
  50707. * Interpolates a Vector3 cubically
  50708. * @param startValue Start value of the animation curve
  50709. * @param outTangent End tangent of the animation
  50710. * @param endValue End value of the animation curve
  50711. * @param inTangent Start tangent of the animation curve
  50712. * @param gradient Scalar amount to interpolate
  50713. * @returns InterpolatedVector3 value
  50714. */
  50715. Animation.prototype.vector3InterpolateFunctionWithTangents = function (startValue, outTangent, endValue, inTangent, gradient) {
  50716. return BABYLON.Vector3.Hermite(startValue, outTangent, endValue, inTangent, gradient);
  50717. };
  50718. /**
  50719. * Interpolates a Vector2 linearly
  50720. * @param startValue Start value of the animation curve
  50721. * @param endValue End value of the animation curve
  50722. * @param gradient Scalar amount to interpolate
  50723. * @returns Interpolated Vector2 value
  50724. */
  50725. Animation.prototype.vector2InterpolateFunction = function (startValue, endValue, gradient) {
  50726. return BABYLON.Vector2.Lerp(startValue, endValue, gradient);
  50727. };
  50728. /**
  50729. * Interpolates a Vector2 cubically
  50730. * @param startValue Start value of the animation curve
  50731. * @param outTangent End tangent of the animation
  50732. * @param endValue End value of the animation curve
  50733. * @param inTangent Start tangent of the animation curve
  50734. * @param gradient Scalar amount to interpolate
  50735. * @returns Interpolated Vector2 value
  50736. */
  50737. Animation.prototype.vector2InterpolateFunctionWithTangents = function (startValue, outTangent, endValue, inTangent, gradient) {
  50738. return BABYLON.Vector2.Hermite(startValue, outTangent, endValue, inTangent, gradient);
  50739. };
  50740. /**
  50741. * Interpolates a size linearly
  50742. * @param startValue Start value of the animation curve
  50743. * @param endValue End value of the animation curve
  50744. * @param gradient Scalar amount to interpolate
  50745. * @returns Interpolated Size value
  50746. */
  50747. Animation.prototype.sizeInterpolateFunction = function (startValue, endValue, gradient) {
  50748. return BABYLON.Size.Lerp(startValue, endValue, gradient);
  50749. };
  50750. /**
  50751. * Interpolates a Color3 linearly
  50752. * @param startValue Start value of the animation curve
  50753. * @param endValue End value of the animation curve
  50754. * @param gradient Scalar amount to interpolate
  50755. * @returns Interpolated Color3 value
  50756. */
  50757. Animation.prototype.color3InterpolateFunction = function (startValue, endValue, gradient) {
  50758. return BABYLON.Color3.Lerp(startValue, endValue, gradient);
  50759. };
  50760. /**
  50761. * @hidden Internal use only
  50762. */
  50763. Animation.prototype._getKeyValue = function (value) {
  50764. if (typeof value === "function") {
  50765. return value();
  50766. }
  50767. return value;
  50768. };
  50769. /**
  50770. * @hidden Internal use only
  50771. */
  50772. Animation.prototype._interpolate = function (currentFrame, repeatCount, workValue, loopMode, offsetValue, highLimitValue) {
  50773. if (loopMode === Animation.ANIMATIONLOOPMODE_CONSTANT && repeatCount > 0) {
  50774. return highLimitValue.clone ? highLimitValue.clone() : highLimitValue;
  50775. }
  50776. var keys = this.getKeys();
  50777. // Try to get a hash to find the right key
  50778. 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));
  50779. if (keys[startKeyIndex].frame >= currentFrame) {
  50780. while (startKeyIndex - 1 >= 0 && keys[startKeyIndex].frame >= currentFrame) {
  50781. startKeyIndex--;
  50782. }
  50783. }
  50784. for (var key = startKeyIndex; key < keys.length; key++) {
  50785. var endKey = keys[key + 1];
  50786. if (endKey.frame >= currentFrame) {
  50787. var startKey = keys[key];
  50788. var startValue = this._getKeyValue(startKey.value);
  50789. if (startKey.interpolation === AnimationKeyInterpolation.STEP) {
  50790. return startValue;
  50791. }
  50792. var endValue = this._getKeyValue(endKey.value);
  50793. var useTangent = startKey.outTangent !== undefined && endKey.inTangent !== undefined;
  50794. var frameDelta = endKey.frame - startKey.frame;
  50795. // gradient : percent of currentFrame between the frame inf and the frame sup
  50796. var gradient = (currentFrame - startKey.frame) / frameDelta;
  50797. // check for easingFunction and correction of gradient
  50798. var easingFunction = this.getEasingFunction();
  50799. if (easingFunction != null) {
  50800. gradient = easingFunction.ease(gradient);
  50801. }
  50802. switch (this.dataType) {
  50803. // Float
  50804. case Animation.ANIMATIONTYPE_FLOAT:
  50805. var floatValue = useTangent ? this.floatInterpolateFunctionWithTangents(startValue, startKey.outTangent * frameDelta, endValue, endKey.inTangent * frameDelta, gradient) : this.floatInterpolateFunction(startValue, endValue, gradient);
  50806. switch (loopMode) {
  50807. case Animation.ANIMATIONLOOPMODE_CYCLE:
  50808. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  50809. return floatValue;
  50810. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  50811. return offsetValue * repeatCount + floatValue;
  50812. }
  50813. break;
  50814. // Quaternion
  50815. case Animation.ANIMATIONTYPE_QUATERNION:
  50816. var quatValue = useTangent ? this.quaternionInterpolateFunctionWithTangents(startValue, startKey.outTangent.scale(frameDelta), endValue, endKey.inTangent.scale(frameDelta), gradient) : this.quaternionInterpolateFunction(startValue, endValue, gradient);
  50817. switch (loopMode) {
  50818. case Animation.ANIMATIONLOOPMODE_CYCLE:
  50819. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  50820. return quatValue;
  50821. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  50822. return quatValue.addInPlace(offsetValue.scale(repeatCount));
  50823. }
  50824. return quatValue;
  50825. // Vector3
  50826. case Animation.ANIMATIONTYPE_VECTOR3:
  50827. var vec3Value = useTangent ? this.vector3InterpolateFunctionWithTangents(startValue, startKey.outTangent.scale(frameDelta), endValue, endKey.inTangent.scale(frameDelta), gradient) : this.vector3InterpolateFunction(startValue, endValue, gradient);
  50828. switch (loopMode) {
  50829. case Animation.ANIMATIONLOOPMODE_CYCLE:
  50830. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  50831. return vec3Value;
  50832. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  50833. return vec3Value.add(offsetValue.scale(repeatCount));
  50834. }
  50835. // Vector2
  50836. case Animation.ANIMATIONTYPE_VECTOR2:
  50837. var vec2Value = useTangent ? this.vector2InterpolateFunctionWithTangents(startValue, startKey.outTangent.scale(frameDelta), endValue, endKey.inTangent.scale(frameDelta), gradient) : this.vector2InterpolateFunction(startValue, endValue, gradient);
  50838. switch (loopMode) {
  50839. case Animation.ANIMATIONLOOPMODE_CYCLE:
  50840. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  50841. return vec2Value;
  50842. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  50843. return vec2Value.add(offsetValue.scale(repeatCount));
  50844. }
  50845. // Size
  50846. case Animation.ANIMATIONTYPE_SIZE:
  50847. switch (loopMode) {
  50848. case Animation.ANIMATIONLOOPMODE_CYCLE:
  50849. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  50850. return this.sizeInterpolateFunction(startValue, endValue, gradient);
  50851. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  50852. return this.sizeInterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  50853. }
  50854. // Color3
  50855. case Animation.ANIMATIONTYPE_COLOR3:
  50856. switch (loopMode) {
  50857. case Animation.ANIMATIONLOOPMODE_CYCLE:
  50858. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  50859. return this.color3InterpolateFunction(startValue, endValue, gradient);
  50860. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  50861. return this.color3InterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  50862. }
  50863. // Matrix
  50864. case Animation.ANIMATIONTYPE_MATRIX:
  50865. switch (loopMode) {
  50866. case Animation.ANIMATIONLOOPMODE_CYCLE:
  50867. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  50868. if (Animation.AllowMatricesInterpolation) {
  50869. return this.matrixInterpolateFunction(startValue, endValue, gradient, workValue);
  50870. }
  50871. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  50872. return startValue;
  50873. }
  50874. default:
  50875. break;
  50876. }
  50877. break;
  50878. }
  50879. }
  50880. return this._getKeyValue(keys[keys.length - 1].value);
  50881. };
  50882. /**
  50883. * Defines the function to use to interpolate matrices
  50884. * @param startValue defines the start matrix
  50885. * @param endValue defines the end matrix
  50886. * @param gradient defines the gradient between both matrices
  50887. * @param result defines an optional target matrix where to store the interpolation
  50888. * @returns the interpolated matrix
  50889. */
  50890. Animation.prototype.matrixInterpolateFunction = function (startValue, endValue, gradient, result) {
  50891. if (Animation.AllowMatrixDecomposeForInterpolation) {
  50892. if (result) {
  50893. BABYLON.Matrix.DecomposeLerpToRef(startValue, endValue, gradient, result);
  50894. return result;
  50895. }
  50896. return BABYLON.Matrix.DecomposeLerp(startValue, endValue, gradient);
  50897. }
  50898. if (result) {
  50899. BABYLON.Matrix.LerpToRef(startValue, endValue, gradient, result);
  50900. return result;
  50901. }
  50902. return BABYLON.Matrix.Lerp(startValue, endValue, gradient);
  50903. };
  50904. /**
  50905. * Makes a copy of the animation
  50906. * @returns Cloned animation
  50907. */
  50908. Animation.prototype.clone = function () {
  50909. var clone = new Animation(this.name, this.targetPropertyPath.join("."), this.framePerSecond, this.dataType, this.loopMode);
  50910. clone.enableBlending = this.enableBlending;
  50911. clone.blendingSpeed = this.blendingSpeed;
  50912. if (this._keys) {
  50913. clone.setKeys(this._keys);
  50914. }
  50915. if (this._ranges) {
  50916. clone._ranges = {};
  50917. for (var name in this._ranges) {
  50918. var range = this._ranges[name];
  50919. if (!range) {
  50920. continue;
  50921. }
  50922. clone._ranges[name] = range.clone();
  50923. }
  50924. }
  50925. return clone;
  50926. };
  50927. /**
  50928. * Sets the key frames of the animation
  50929. * @param values The animation key frames to set
  50930. */
  50931. Animation.prototype.setKeys = function (values) {
  50932. this._keys = values.slice(0);
  50933. };
  50934. /**
  50935. * Serializes the animation to an object
  50936. * @returns Serialized object
  50937. */
  50938. Animation.prototype.serialize = function () {
  50939. var serializationObject = {};
  50940. serializationObject.name = this.name;
  50941. serializationObject.property = this.targetProperty;
  50942. serializationObject.framePerSecond = this.framePerSecond;
  50943. serializationObject.dataType = this.dataType;
  50944. serializationObject.loopBehavior = this.loopMode;
  50945. serializationObject.enableBlending = this.enableBlending;
  50946. serializationObject.blendingSpeed = this.blendingSpeed;
  50947. var dataType = this.dataType;
  50948. serializationObject.keys = [];
  50949. var keys = this.getKeys();
  50950. for (var index = 0; index < keys.length; index++) {
  50951. var animationKey = keys[index];
  50952. var key = {};
  50953. key.frame = animationKey.frame;
  50954. switch (dataType) {
  50955. case Animation.ANIMATIONTYPE_FLOAT:
  50956. key.values = [animationKey.value];
  50957. break;
  50958. case Animation.ANIMATIONTYPE_QUATERNION:
  50959. case Animation.ANIMATIONTYPE_MATRIX:
  50960. case Animation.ANIMATIONTYPE_VECTOR3:
  50961. case Animation.ANIMATIONTYPE_COLOR3:
  50962. key.values = animationKey.value.asArray();
  50963. break;
  50964. }
  50965. serializationObject.keys.push(key);
  50966. }
  50967. serializationObject.ranges = [];
  50968. for (var name in this._ranges) {
  50969. var source = this._ranges[name];
  50970. if (!source) {
  50971. continue;
  50972. }
  50973. var range = {};
  50974. range.name = name;
  50975. range.from = source.from;
  50976. range.to = source.to;
  50977. serializationObject.ranges.push(range);
  50978. }
  50979. return serializationObject;
  50980. };
  50981. Object.defineProperty(Animation, "ANIMATIONTYPE_FLOAT", {
  50982. /**
  50983. * Get the float animation type
  50984. */
  50985. get: function () {
  50986. return Animation._ANIMATIONTYPE_FLOAT;
  50987. },
  50988. enumerable: true,
  50989. configurable: true
  50990. });
  50991. Object.defineProperty(Animation, "ANIMATIONTYPE_VECTOR3", {
  50992. /**
  50993. * Get the Vector3 animation type
  50994. */
  50995. get: function () {
  50996. return Animation._ANIMATIONTYPE_VECTOR3;
  50997. },
  50998. enumerable: true,
  50999. configurable: true
  51000. });
  51001. Object.defineProperty(Animation, "ANIMATIONTYPE_VECTOR2", {
  51002. /**
  51003. * Get the Vectpr2 animation type
  51004. */
  51005. get: function () {
  51006. return Animation._ANIMATIONTYPE_VECTOR2;
  51007. },
  51008. enumerable: true,
  51009. configurable: true
  51010. });
  51011. Object.defineProperty(Animation, "ANIMATIONTYPE_SIZE", {
  51012. /**
  51013. * Get the Size animation type
  51014. */
  51015. get: function () {
  51016. return Animation._ANIMATIONTYPE_SIZE;
  51017. },
  51018. enumerable: true,
  51019. configurable: true
  51020. });
  51021. Object.defineProperty(Animation, "ANIMATIONTYPE_QUATERNION", {
  51022. /**
  51023. * Get the Quaternion animation type
  51024. */
  51025. get: function () {
  51026. return Animation._ANIMATIONTYPE_QUATERNION;
  51027. },
  51028. enumerable: true,
  51029. configurable: true
  51030. });
  51031. Object.defineProperty(Animation, "ANIMATIONTYPE_MATRIX", {
  51032. /**
  51033. * Get the Matrix animation type
  51034. */
  51035. get: function () {
  51036. return Animation._ANIMATIONTYPE_MATRIX;
  51037. },
  51038. enumerable: true,
  51039. configurable: true
  51040. });
  51041. Object.defineProperty(Animation, "ANIMATIONTYPE_COLOR3", {
  51042. /**
  51043. * Get the Color3 animation type
  51044. */
  51045. get: function () {
  51046. return Animation._ANIMATIONTYPE_COLOR3;
  51047. },
  51048. enumerable: true,
  51049. configurable: true
  51050. });
  51051. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_RELATIVE", {
  51052. /**
  51053. * Get the Relative Loop Mode
  51054. */
  51055. get: function () {
  51056. return Animation._ANIMATIONLOOPMODE_RELATIVE;
  51057. },
  51058. enumerable: true,
  51059. configurable: true
  51060. });
  51061. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_CYCLE", {
  51062. /**
  51063. * Get the Cycle Loop Mode
  51064. */
  51065. get: function () {
  51066. return Animation._ANIMATIONLOOPMODE_CYCLE;
  51067. },
  51068. enumerable: true,
  51069. configurable: true
  51070. });
  51071. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_CONSTANT", {
  51072. /**
  51073. * Get the Constant Loop Mode
  51074. */
  51075. get: function () {
  51076. return Animation._ANIMATIONLOOPMODE_CONSTANT;
  51077. },
  51078. enumerable: true,
  51079. configurable: true
  51080. });
  51081. /**
  51082. * Parses an animation object and creates an animation
  51083. * @param parsedAnimation Parsed animation object
  51084. * @returns Animation object
  51085. */
  51086. Animation.Parse = function (parsedAnimation) {
  51087. var animation = new Animation(parsedAnimation.name, parsedAnimation.property, parsedAnimation.framePerSecond, parsedAnimation.dataType, parsedAnimation.loopBehavior);
  51088. var dataType = parsedAnimation.dataType;
  51089. var keys = [];
  51090. var data;
  51091. var index;
  51092. if (parsedAnimation.enableBlending) {
  51093. animation.enableBlending = parsedAnimation.enableBlending;
  51094. }
  51095. if (parsedAnimation.blendingSpeed) {
  51096. animation.blendingSpeed = parsedAnimation.blendingSpeed;
  51097. }
  51098. for (index = 0; index < parsedAnimation.keys.length; index++) {
  51099. var key = parsedAnimation.keys[index];
  51100. var inTangent;
  51101. var outTangent;
  51102. switch (dataType) {
  51103. case Animation.ANIMATIONTYPE_FLOAT:
  51104. data = key.values[0];
  51105. if (key.values.length >= 1) {
  51106. inTangent = key.values[1];
  51107. }
  51108. if (key.values.length >= 2) {
  51109. outTangent = key.values[2];
  51110. }
  51111. break;
  51112. case Animation.ANIMATIONTYPE_QUATERNION:
  51113. data = BABYLON.Quaternion.FromArray(key.values);
  51114. if (key.values.length >= 8) {
  51115. var _inTangent = BABYLON.Quaternion.FromArray(key.values.slice(4, 8));
  51116. if (!_inTangent.equals(BABYLON.Quaternion.Zero())) {
  51117. inTangent = _inTangent;
  51118. }
  51119. }
  51120. if (key.values.length >= 12) {
  51121. var _outTangent = BABYLON.Quaternion.FromArray(key.values.slice(8, 12));
  51122. if (!_outTangent.equals(BABYLON.Quaternion.Zero())) {
  51123. outTangent = _outTangent;
  51124. }
  51125. }
  51126. break;
  51127. case Animation.ANIMATIONTYPE_MATRIX:
  51128. data = BABYLON.Matrix.FromArray(key.values);
  51129. break;
  51130. case Animation.ANIMATIONTYPE_COLOR3:
  51131. data = BABYLON.Color3.FromArray(key.values);
  51132. break;
  51133. case Animation.ANIMATIONTYPE_VECTOR3:
  51134. default:
  51135. data = BABYLON.Vector3.FromArray(key.values);
  51136. break;
  51137. }
  51138. var keyData = {};
  51139. keyData.frame = key.frame;
  51140. keyData.value = data;
  51141. if (inTangent != undefined) {
  51142. keyData.inTangent = inTangent;
  51143. }
  51144. if (outTangent != undefined) {
  51145. keyData.outTangent = outTangent;
  51146. }
  51147. keys.push(keyData);
  51148. }
  51149. animation.setKeys(keys);
  51150. if (parsedAnimation.ranges) {
  51151. for (index = 0; index < parsedAnimation.ranges.length; index++) {
  51152. data = parsedAnimation.ranges[index];
  51153. animation.createRange(data.name, data.from, data.to);
  51154. }
  51155. }
  51156. return animation;
  51157. };
  51158. /**
  51159. * Appends the serialized animations from the source animations
  51160. * @param source Source containing the animations
  51161. * @param destination Target to store the animations
  51162. */
  51163. Animation.AppendSerializedAnimations = function (source, destination) {
  51164. if (source.animations) {
  51165. destination.animations = [];
  51166. for (var animationIndex = 0; animationIndex < source.animations.length; animationIndex++) {
  51167. var animation = source.animations[animationIndex];
  51168. destination.animations.push(animation.serialize());
  51169. }
  51170. }
  51171. };
  51172. /**
  51173. * Use matrix interpolation instead of using direct key value when animating matrices
  51174. */
  51175. Animation.AllowMatricesInterpolation = false;
  51176. /**
  51177. * When matrix interpolation is enabled, this boolean forces the system to use Matrix.DecomposeLerp instead of Matrix.Lerp. Interpolation is more precise but slower
  51178. */
  51179. Animation.AllowMatrixDecomposeForInterpolation = true;
  51180. // Statics
  51181. /**
  51182. * Float animation type
  51183. */
  51184. Animation._ANIMATIONTYPE_FLOAT = 0;
  51185. /**
  51186. * Vector3 animation type
  51187. */
  51188. Animation._ANIMATIONTYPE_VECTOR3 = 1;
  51189. /**
  51190. * Quaternion animation type
  51191. */
  51192. Animation._ANIMATIONTYPE_QUATERNION = 2;
  51193. /**
  51194. * Matrix animation type
  51195. */
  51196. Animation._ANIMATIONTYPE_MATRIX = 3;
  51197. /**
  51198. * Color3 animation type
  51199. */
  51200. Animation._ANIMATIONTYPE_COLOR3 = 4;
  51201. /**
  51202. * Vector2 animation type
  51203. */
  51204. Animation._ANIMATIONTYPE_VECTOR2 = 5;
  51205. /**
  51206. * Size animation type
  51207. */
  51208. Animation._ANIMATIONTYPE_SIZE = 6;
  51209. /**
  51210. * Relative Loop Mode
  51211. */
  51212. Animation._ANIMATIONLOOPMODE_RELATIVE = 0;
  51213. /**
  51214. * Cycle Loop Mode
  51215. */
  51216. Animation._ANIMATIONLOOPMODE_CYCLE = 1;
  51217. /**
  51218. * Constant Loop Mode
  51219. */
  51220. Animation._ANIMATIONLOOPMODE_CONSTANT = 2;
  51221. return Animation;
  51222. }());
  51223. BABYLON.Animation = Animation;
  51224. })(BABYLON || (BABYLON = {}));
  51225. //# sourceMappingURL=babylon.animation.js.map
  51226. var BABYLON;
  51227. (function (BABYLON) {
  51228. /**
  51229. * This class defines the direct association between an animation and a target
  51230. */
  51231. var TargetedAnimation = /** @class */ (function () {
  51232. function TargetedAnimation() {
  51233. }
  51234. return TargetedAnimation;
  51235. }());
  51236. BABYLON.TargetedAnimation = TargetedAnimation;
  51237. /**
  51238. * Use this class to create coordinated animations on multiple targets
  51239. */
  51240. var AnimationGroup = /** @class */ (function () {
  51241. function AnimationGroup(name, scene) {
  51242. if (scene === void 0) { scene = null; }
  51243. this.name = name;
  51244. this._targetedAnimations = new Array();
  51245. this._animatables = new Array();
  51246. this._from = Number.MAX_VALUE;
  51247. this._to = -Number.MAX_VALUE;
  51248. this._speedRatio = 1;
  51249. this.onAnimationEndObservable = new BABYLON.Observable();
  51250. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  51251. this._scene.animationGroups.push(this);
  51252. }
  51253. Object.defineProperty(AnimationGroup.prototype, "isStarted", {
  51254. /**
  51255. * Define if the animations are started
  51256. */
  51257. get: function () {
  51258. return this._isStarted;
  51259. },
  51260. enumerable: true,
  51261. configurable: true
  51262. });
  51263. Object.defineProperty(AnimationGroup.prototype, "speedRatio", {
  51264. /**
  51265. * Gets or sets the speed ratio to use for all animations
  51266. */
  51267. get: function () {
  51268. return this._speedRatio;
  51269. },
  51270. /**
  51271. * Gets or sets the speed ratio to use for all animations
  51272. */
  51273. set: function (value) {
  51274. if (this._speedRatio === value) {
  51275. return;
  51276. }
  51277. this._speedRatio = value;
  51278. for (var index = 0; index < this._animatables.length; index++) {
  51279. var animatable = this._animatables[index];
  51280. animatable.speedRatio = this._speedRatio;
  51281. }
  51282. },
  51283. enumerable: true,
  51284. configurable: true
  51285. });
  51286. Object.defineProperty(AnimationGroup.prototype, "targetedAnimations", {
  51287. /**
  51288. * Gets the targeted animations for this animation group
  51289. */
  51290. get: function () {
  51291. return this._targetedAnimations;
  51292. },
  51293. enumerable: true,
  51294. configurable: true
  51295. });
  51296. Object.defineProperty(AnimationGroup.prototype, "animatables", {
  51297. /**
  51298. * returning the list of animatables controlled by this animation group.
  51299. */
  51300. get: function () {
  51301. return this._animatables;
  51302. },
  51303. enumerable: true,
  51304. configurable: true
  51305. });
  51306. /**
  51307. * Add an animation (with its target) in the group
  51308. * @param animation defines the animation we want to add
  51309. * @param target defines the target of the animation
  51310. * @returns the {BABYLON.TargetedAnimation} object
  51311. */
  51312. AnimationGroup.prototype.addTargetedAnimation = function (animation, target) {
  51313. var targetedAnimation = {
  51314. animation: animation,
  51315. target: target
  51316. };
  51317. var keys = animation.getKeys();
  51318. if (this._from > keys[0].frame) {
  51319. this._from = keys[0].frame;
  51320. }
  51321. if (this._to < keys[keys.length - 1].frame) {
  51322. this._to = keys[keys.length - 1].frame;
  51323. }
  51324. this._targetedAnimations.push(targetedAnimation);
  51325. return targetedAnimation;
  51326. };
  51327. /**
  51328. * This function will normalize every animation in the group to make sure they all go from beginFrame to endFrame
  51329. * It can add constant keys at begin or end
  51330. * @param beginFrame defines the new begin frame for all animations. It can't be bigger than the smallest begin frame of all animations
  51331. * @param endFrame defines the new end frame for all animations. It can't be smaller than the largest end frame of all animations
  51332. */
  51333. AnimationGroup.prototype.normalize = function (beginFrame, endFrame) {
  51334. if (beginFrame === void 0) { beginFrame = -Number.MAX_VALUE; }
  51335. if (endFrame === void 0) { endFrame = Number.MAX_VALUE; }
  51336. beginFrame = Math.max(beginFrame, this._from);
  51337. endFrame = Math.min(endFrame, this._to);
  51338. for (var index = 0; index < this._targetedAnimations.length; index++) {
  51339. var targetedAnimation = this._targetedAnimations[index];
  51340. var keys = targetedAnimation.animation.getKeys();
  51341. var startKey = keys[0];
  51342. var endKey = keys[keys.length - 1];
  51343. if (startKey.frame > beginFrame) {
  51344. var newKey = {
  51345. frame: beginFrame,
  51346. value: startKey.value,
  51347. inTangent: startKey.inTangent,
  51348. outTangent: startKey.outTangent,
  51349. interpolation: startKey.interpolation
  51350. };
  51351. keys.splice(0, 0, newKey);
  51352. }
  51353. if (endKey.frame < endFrame) {
  51354. var newKey = {
  51355. frame: endFrame,
  51356. value: endKey.value,
  51357. inTangent: endKey.outTangent,
  51358. outTangent: endKey.outTangent,
  51359. interpolation: endKey.interpolation
  51360. };
  51361. keys.push(newKey);
  51362. }
  51363. }
  51364. return this;
  51365. };
  51366. /**
  51367. * Start all animations on given targets
  51368. * @param loop defines if animations must loop
  51369. * @param speedRatio defines the ratio to apply to animation speed (1 by default)
  51370. * @param from defines the from key (optional)
  51371. * @param to defines the to key (optional)
  51372. * @returns the current animation group
  51373. */
  51374. AnimationGroup.prototype.start = function (loop, speedRatio, from, to) {
  51375. var _this = this;
  51376. if (loop === void 0) { loop = false; }
  51377. if (speedRatio === void 0) { speedRatio = 1; }
  51378. if (this._isStarted || this._targetedAnimations.length === 0) {
  51379. return this;
  51380. }
  51381. var _loop_1 = function (targetedAnimation) {
  51382. 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 () {
  51383. _this.onAnimationEndObservable.notifyObservers(targetedAnimation);
  51384. }));
  51385. };
  51386. var this_1 = this;
  51387. for (var _i = 0, _a = this._targetedAnimations; _i < _a.length; _i++) {
  51388. var targetedAnimation = _a[_i];
  51389. _loop_1(targetedAnimation);
  51390. }
  51391. this._speedRatio = speedRatio;
  51392. this._isStarted = true;
  51393. return this;
  51394. };
  51395. /**
  51396. * Pause all animations
  51397. */
  51398. AnimationGroup.prototype.pause = function () {
  51399. if (!this._isStarted) {
  51400. return this;
  51401. }
  51402. for (var index = 0; index < this._animatables.length; index++) {
  51403. var animatable = this._animatables[index];
  51404. animatable.pause();
  51405. }
  51406. return this;
  51407. };
  51408. /**
  51409. * Play all animations to initial state
  51410. * This function will start() the animations if they were not started or will restart() them if they were paused
  51411. * @param loop defines if animations must loop
  51412. */
  51413. AnimationGroup.prototype.play = function (loop) {
  51414. if (this.isStarted) {
  51415. if (loop !== undefined) {
  51416. for (var index = 0; index < this._animatables.length; index++) {
  51417. var animatable = this._animatables[index];
  51418. animatable.loopAnimation = loop;
  51419. }
  51420. }
  51421. this.restart();
  51422. }
  51423. else {
  51424. this.start(loop, this._speedRatio);
  51425. }
  51426. return this;
  51427. };
  51428. /**
  51429. * Reset all animations to initial state
  51430. */
  51431. AnimationGroup.prototype.reset = function () {
  51432. if (!this._isStarted) {
  51433. return this;
  51434. }
  51435. for (var index = 0; index < this._animatables.length; index++) {
  51436. var animatable = this._animatables[index];
  51437. animatable.reset();
  51438. }
  51439. return this;
  51440. };
  51441. /**
  51442. * Restart animations from key 0
  51443. */
  51444. AnimationGroup.prototype.restart = function () {
  51445. if (!this._isStarted) {
  51446. return this;
  51447. }
  51448. for (var index = 0; index < this._animatables.length; index++) {
  51449. var animatable = this._animatables[index];
  51450. animatable.restart();
  51451. }
  51452. return this;
  51453. };
  51454. /**
  51455. * Stop all animations
  51456. */
  51457. AnimationGroup.prototype.stop = function () {
  51458. if (!this._isStarted) {
  51459. return this;
  51460. }
  51461. for (var index = 0; index < this._animatables.length; index++) {
  51462. var animatable = this._animatables[index];
  51463. animatable.stop();
  51464. }
  51465. this._isStarted = false;
  51466. return this;
  51467. };
  51468. /**
  51469. * Set animation weight for all animatables
  51470. * @param weight defines the weight to use
  51471. * @return the animationGroup
  51472. * @see http://doc.babylonjs.com/babylon101/animations#animation-weights
  51473. */
  51474. AnimationGroup.prototype.setWeightForAllAnimatables = function (weight) {
  51475. for (var index = 0; index < this._animatables.length; index++) {
  51476. var animatable = this._animatables[index];
  51477. animatable.weight = weight;
  51478. }
  51479. return this;
  51480. };
  51481. /**
  51482. * Synchronize and normalize all animatables with a source animatable
  51483. * @param root defines the root animatable to synchronize with
  51484. * @return the animationGroup
  51485. * @see http://doc.babylonjs.com/babylon101/animations#animation-weights
  51486. */
  51487. AnimationGroup.prototype.syncAllAnimationsWith = function (root) {
  51488. for (var index = 0; index < this._animatables.length; index++) {
  51489. var animatable = this._animatables[index];
  51490. animatable.syncWith(root);
  51491. }
  51492. return this;
  51493. };
  51494. /**
  51495. * Goes to a specific frame in this animation group
  51496. * @param frame the frame number to go to
  51497. * @return the animationGroup
  51498. */
  51499. AnimationGroup.prototype.goToFrame = function (frame) {
  51500. if (!this._isStarted) {
  51501. return this;
  51502. }
  51503. for (var index = 0; index < this._animatables.length; index++) {
  51504. var animatable = this._animatables[index];
  51505. animatable.goToFrame(frame);
  51506. }
  51507. return this;
  51508. };
  51509. /**
  51510. * Dispose all associated resources
  51511. */
  51512. AnimationGroup.prototype.dispose = function () {
  51513. this._targetedAnimations = [];
  51514. this._animatables = [];
  51515. var index = this._scene.animationGroups.indexOf(this);
  51516. if (index > -1) {
  51517. this._scene.animationGroups.splice(index, 1);
  51518. }
  51519. };
  51520. return AnimationGroup;
  51521. }());
  51522. BABYLON.AnimationGroup = AnimationGroup;
  51523. })(BABYLON || (BABYLON = {}));
  51524. //# sourceMappingURL=babylon.animationGroup.js.map
  51525. var BABYLON;
  51526. (function (BABYLON) {
  51527. /**
  51528. * Defines a runtime animation
  51529. */
  51530. var RuntimeAnimation = /** @class */ (function () {
  51531. /**
  51532. * Create a new RuntimeAnimation object
  51533. * @param target defines the target of the animation
  51534. * @param animation defines the source animation object
  51535. * @param scene defines the hosting scene
  51536. * @param host defines the initiating Animatable
  51537. */
  51538. function RuntimeAnimation(target, animation, scene, host) {
  51539. /**
  51540. * The current frame of the runtime animation
  51541. */
  51542. this._currentFrame = 0;
  51543. /**
  51544. * The offsets cache of the runtime animation
  51545. */
  51546. this._offsetsCache = {};
  51547. /**
  51548. * The high limits cache of the runtime animation
  51549. */
  51550. this._highLimitsCache = {};
  51551. /**
  51552. * Specifies if the runtime animation has been stopped
  51553. */
  51554. this._stopped = false;
  51555. /**
  51556. * The blending factor of the runtime animation
  51557. */
  51558. this._blendingFactor = 0;
  51559. /**
  51560. * The target path of the runtime animation
  51561. */
  51562. this._targetPath = "";
  51563. /**
  51564. * The weight of the runtime animation
  51565. */
  51566. this._weight = 1.0;
  51567. /**
  51568. * The ratio offset of the runtime animation
  51569. */
  51570. this._ratioOffset = 0;
  51571. /**
  51572. * The previous delay of the runtime animation
  51573. */
  51574. this._previousDelay = 0;
  51575. /**
  51576. * The previous ratio of the runtime animation
  51577. */
  51578. this._previousRatio = 0;
  51579. this._animation = animation;
  51580. this._target = target;
  51581. this._scene = scene;
  51582. this._host = host;
  51583. animation._runtimeAnimations.push(this);
  51584. }
  51585. Object.defineProperty(RuntimeAnimation.prototype, "currentFrame", {
  51586. /**
  51587. * Gets the current frame of the runtime animation
  51588. */
  51589. get: function () {
  51590. return this._currentFrame;
  51591. },
  51592. enumerable: true,
  51593. configurable: true
  51594. });
  51595. Object.defineProperty(RuntimeAnimation.prototype, "weight", {
  51596. /**
  51597. * Gets the weight of the runtime animation
  51598. */
  51599. get: function () {
  51600. return this._weight;
  51601. },
  51602. enumerable: true,
  51603. configurable: true
  51604. });
  51605. Object.defineProperty(RuntimeAnimation.prototype, "originalValue", {
  51606. /**
  51607. * Gets the original value of the runtime animation
  51608. */
  51609. get: function () {
  51610. return this._originalValue;
  51611. },
  51612. enumerable: true,
  51613. configurable: true
  51614. });
  51615. Object.defineProperty(RuntimeAnimation.prototype, "currentValue", {
  51616. /**
  51617. * Gets the current value of the runtime animation
  51618. */
  51619. get: function () {
  51620. return this._currentValue;
  51621. },
  51622. enumerable: true,
  51623. configurable: true
  51624. });
  51625. Object.defineProperty(RuntimeAnimation.prototype, "targetPath", {
  51626. /**
  51627. * Gets the target path of the runtime animation
  51628. */
  51629. get: function () {
  51630. return this._targetPath;
  51631. },
  51632. enumerable: true,
  51633. configurable: true
  51634. });
  51635. Object.defineProperty(RuntimeAnimation.prototype, "target", {
  51636. /**
  51637. * Gets the actual target of the runtime animation
  51638. */
  51639. get: function () {
  51640. return this._activeTarget;
  51641. },
  51642. enumerable: true,
  51643. configurable: true
  51644. });
  51645. Object.defineProperty(RuntimeAnimation.prototype, "animation", {
  51646. /**
  51647. * Gets the animation from the runtime animation
  51648. */
  51649. get: function () {
  51650. return this._animation;
  51651. },
  51652. enumerable: true,
  51653. configurable: true
  51654. });
  51655. /**
  51656. * Resets the runtime animation to the beginning
  51657. */
  51658. RuntimeAnimation.prototype.reset = function () {
  51659. this._offsetsCache = {};
  51660. this._highLimitsCache = {};
  51661. this._currentFrame = 0;
  51662. this._blendingFactor = 0;
  51663. this._originalValue = null;
  51664. };
  51665. /**
  51666. * Specifies if the runtime animation is stopped
  51667. * @returns Boolean specifying if the runtime animation is stopped
  51668. */
  51669. RuntimeAnimation.prototype.isStopped = function () {
  51670. return this._stopped;
  51671. };
  51672. /**
  51673. * Disposes of the runtime animation
  51674. */
  51675. RuntimeAnimation.prototype.dispose = function () {
  51676. var index = this._animation.runtimeAnimations.indexOf(this);
  51677. if (index > -1) {
  51678. this._animation.runtimeAnimations.splice(index, 1);
  51679. }
  51680. };
  51681. /**
  51682. * Interpolates the animation from the current frame
  51683. * @param currentFrame The frame to interpolate the animation to
  51684. * @param repeatCount The number of times that the animation should loop
  51685. * @param loopMode The type of looping mode to use
  51686. * @param offsetValue Animation offset value
  51687. * @param highLimitValue The high limit value
  51688. * @returns The interpolated value
  51689. */
  51690. RuntimeAnimation.prototype._interpolate = function (currentFrame, repeatCount, loopMode, offsetValue, highLimitValue) {
  51691. this._currentFrame = currentFrame;
  51692. if (this._animation.dataType === BABYLON.Animation.ANIMATIONTYPE_MATRIX && !this._workValue) {
  51693. this._workValue = BABYLON.Matrix.Zero();
  51694. }
  51695. return this._animation._interpolate(currentFrame, repeatCount, this._workValue, loopMode, offsetValue, highLimitValue);
  51696. };
  51697. /**
  51698. * Affect the interpolated value to the target
  51699. * @param currentValue defines the value computed by the animation
  51700. * @param weight defines the weight to apply to this value
  51701. */
  51702. RuntimeAnimation.prototype.setValue = function (currentValue, weight) {
  51703. if (weight === void 0) { weight = 1.0; }
  51704. if (this._target instanceof Array) {
  51705. for (var _i = 0, _a = this._target; _i < _a.length; _i++) {
  51706. var target = _a[_i];
  51707. this._setValue(target, currentValue, weight);
  51708. }
  51709. }
  51710. else {
  51711. this._setValue(this._target, currentValue, weight);
  51712. }
  51713. };
  51714. /**
  51715. * Sets the value of the runtime animation
  51716. * @param target The target property of the runtime animation
  51717. * @param currentValue The current value to use for the runtime animation
  51718. * @param weight The weight to use for the runtime animation (Defaults to 1.0)
  51719. */
  51720. RuntimeAnimation.prototype._setValue = function (target, currentValue, weight) {
  51721. if (weight === void 0) { weight = 1.0; }
  51722. // Set value
  51723. var path;
  51724. var destination;
  51725. var targetPropertyPath = this._animation.targetPropertyPath;
  51726. if (targetPropertyPath.length > 1) {
  51727. var property = target[targetPropertyPath[0]];
  51728. for (var index = 1; index < targetPropertyPath.length - 1; index++) {
  51729. property = property[targetPropertyPath[index]];
  51730. }
  51731. path = targetPropertyPath[targetPropertyPath.length - 1];
  51732. destination = property;
  51733. }
  51734. else {
  51735. path = targetPropertyPath[0];
  51736. destination = target;
  51737. }
  51738. this._targetPath = path;
  51739. this._activeTarget = destination;
  51740. this._weight = weight;
  51741. // Blending
  51742. var enableBlending = target && target.animationPropertiesOverride ? target.animationPropertiesOverride.enableBlending : this._animation.enableBlending;
  51743. var blendingSpeed = target && target.animationPropertiesOverride ? target.animationPropertiesOverride.blendingSpeed : this._animation.blendingSpeed;
  51744. if (enableBlending && this._blendingFactor <= 1.0) {
  51745. if (!this._originalBlendValue) {
  51746. var originalValue = destination[path];
  51747. if (originalValue.clone) {
  51748. this._originalBlendValue = originalValue.clone();
  51749. }
  51750. else {
  51751. this._originalBlendValue = originalValue;
  51752. }
  51753. }
  51754. }
  51755. if (weight !== -1.0) {
  51756. if (!this._originalValue) {
  51757. var originalValue = void 0;
  51758. if (destination.getRestPose && path === "_matrix") { // For bones
  51759. originalValue = destination.getRestPose();
  51760. }
  51761. else {
  51762. originalValue = destination[path];
  51763. }
  51764. if (originalValue.clone) {
  51765. this._originalValue = originalValue.clone();
  51766. }
  51767. else {
  51768. this._originalValue = originalValue;
  51769. }
  51770. }
  51771. }
  51772. if (enableBlending && this._blendingFactor <= 1.0) {
  51773. if (this._originalBlendValue.m) { // Matrix
  51774. if (BABYLON.Animation.AllowMatrixDecomposeForInterpolation) {
  51775. if (this._currentValue) {
  51776. BABYLON.Matrix.DecomposeLerpToRef(this._originalBlendValue, currentValue, this._blendingFactor, this._currentValue);
  51777. }
  51778. else {
  51779. this._currentValue = BABYLON.Matrix.DecomposeLerp(this._originalBlendValue, currentValue, this._blendingFactor);
  51780. }
  51781. }
  51782. else {
  51783. if (this._currentValue) {
  51784. BABYLON.Matrix.LerpToRef(this._originalBlendValue, currentValue, this._blendingFactor, this._currentValue);
  51785. }
  51786. else {
  51787. this._currentValue = BABYLON.Matrix.Lerp(this._originalBlendValue, currentValue, this._blendingFactor);
  51788. }
  51789. }
  51790. }
  51791. else {
  51792. var constructor = this._originalBlendValue.constructor;
  51793. if (constructor.Lerp) { // Lerp supported
  51794. this._currentValue = constructor.Lerp(this._originalBlendValue, currentValue, this._blendingFactor);
  51795. }
  51796. else if (constructor.Slerp) { // Slerp supported
  51797. this._currentValue = constructor.Slerp(this._originalBlendValue, currentValue, this._blendingFactor);
  51798. }
  51799. else if (this._originalBlendValue.toFixed) { // Number
  51800. this._currentValue = this._originalBlendValue * (1.0 - this._blendingFactor) + this._blendingFactor * currentValue;
  51801. }
  51802. else { // Blending not supported
  51803. this._currentValue = currentValue;
  51804. }
  51805. }
  51806. this._blendingFactor += blendingSpeed;
  51807. }
  51808. else {
  51809. this._currentValue = currentValue;
  51810. }
  51811. if (weight !== -1.0) {
  51812. this._scene._registerTargetForLateAnimationBinding(this);
  51813. }
  51814. else {
  51815. destination[path] = this._currentValue;
  51816. }
  51817. if (target.markAsDirty) {
  51818. target.markAsDirty(this._animation.targetProperty);
  51819. }
  51820. };
  51821. /**
  51822. * Gets the loop pmode of the runtime animation
  51823. * @returns Loop Mode
  51824. */
  51825. RuntimeAnimation.prototype._getCorrectLoopMode = function () {
  51826. if (this._target && this._target.animationPropertiesOverride) {
  51827. return this._target.animationPropertiesOverride.loopMode;
  51828. }
  51829. return this._animation.loopMode;
  51830. };
  51831. /**
  51832. * Move the current animation to a given frame
  51833. * @param frame defines the frame to move to
  51834. */
  51835. RuntimeAnimation.prototype.goToFrame = function (frame) {
  51836. var keys = this._animation.getKeys();
  51837. if (frame < keys[0].frame) {
  51838. frame = keys[0].frame;
  51839. }
  51840. else if (frame > keys[keys.length - 1].frame) {
  51841. frame = keys[keys.length - 1].frame;
  51842. }
  51843. var currentValue = this._interpolate(frame, 0, this._getCorrectLoopMode());
  51844. this.setValue(currentValue, -1);
  51845. };
  51846. /**
  51847. * @hidden Internal use only
  51848. */
  51849. RuntimeAnimation.prototype._prepareForSpeedRatioChange = function (newSpeedRatio) {
  51850. var newRatio = this._previousDelay * (this._animation.framePerSecond * newSpeedRatio) / 1000.0;
  51851. this._ratioOffset = this._previousRatio - newRatio;
  51852. };
  51853. /**
  51854. * Execute the current animation
  51855. * @param delay defines the delay to add to the current frame
  51856. * @param from defines the lower bound of the animation range
  51857. * @param to defines the upper bound of the animation range
  51858. * @param loop defines if the current animation must loop
  51859. * @param speedRatio defines the current speed ratio
  51860. * @param weight defines the weight of the animation (default is -1 so no weight)
  51861. * @returns a boolean indicating if the animation has ended
  51862. */
  51863. RuntimeAnimation.prototype.animate = function (delay, from, to, loop, speedRatio, weight) {
  51864. if (weight === void 0) { weight = -1.0; }
  51865. var targetPropertyPath = this._animation.targetPropertyPath;
  51866. if (!targetPropertyPath || targetPropertyPath.length < 1) {
  51867. this._stopped = true;
  51868. return false;
  51869. }
  51870. var returnValue = true;
  51871. var keys = this._animation.getKeys();
  51872. // Adding a start key at frame 0 if missing
  51873. if (keys[0].frame !== 0) {
  51874. var newKey = { frame: 0, value: keys[0].value };
  51875. keys.splice(0, 0, newKey);
  51876. }
  51877. // Check limits
  51878. if (from < keys[0].frame || from > keys[keys.length - 1].frame) {
  51879. from = keys[0].frame;
  51880. }
  51881. if (to < keys[0].frame || to > keys[keys.length - 1].frame) {
  51882. to = keys[keys.length - 1].frame;
  51883. }
  51884. //to and from cannot be the same key
  51885. if (from === to) {
  51886. if (from > keys[0].frame) {
  51887. from--;
  51888. }
  51889. else if (to < keys[keys.length - 1].frame) {
  51890. to++;
  51891. }
  51892. }
  51893. // Compute ratio
  51894. var range = to - from;
  51895. var offsetValue;
  51896. // ratio represents the frame delta between from and to
  51897. var ratio = (delay * (this._animation.framePerSecond * speedRatio) / 1000.0) + this._ratioOffset;
  51898. var highLimitValue = 0;
  51899. this._previousDelay = delay;
  51900. this._previousRatio = ratio;
  51901. if (((to > from && ratio > range) || (from > to && ratio < range)) && !loop) { // If we are out of range and not looping get back to caller
  51902. returnValue = false;
  51903. highLimitValue = this._animation._getKeyValue(keys[keys.length - 1].value);
  51904. }
  51905. else {
  51906. // Get max value if required
  51907. if (this._getCorrectLoopMode() !== BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE) {
  51908. var keyOffset = to.toString() + from.toString();
  51909. if (!this._offsetsCache[keyOffset]) {
  51910. var fromValue = this._interpolate(from, 0, BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE);
  51911. var toValue = this._interpolate(to, 0, BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE);
  51912. switch (this._animation.dataType) {
  51913. // Float
  51914. case BABYLON.Animation.ANIMATIONTYPE_FLOAT:
  51915. this._offsetsCache[keyOffset] = toValue - fromValue;
  51916. break;
  51917. // Quaternion
  51918. case BABYLON.Animation.ANIMATIONTYPE_QUATERNION:
  51919. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  51920. break;
  51921. // Vector3
  51922. case BABYLON.Animation.ANIMATIONTYPE_VECTOR3:
  51923. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  51924. // Vector2
  51925. case BABYLON.Animation.ANIMATIONTYPE_VECTOR2:
  51926. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  51927. // Size
  51928. case BABYLON.Animation.ANIMATIONTYPE_SIZE:
  51929. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  51930. // Color3
  51931. case BABYLON.Animation.ANIMATIONTYPE_COLOR3:
  51932. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  51933. default:
  51934. break;
  51935. }
  51936. this._highLimitsCache[keyOffset] = toValue;
  51937. }
  51938. highLimitValue = this._highLimitsCache[keyOffset];
  51939. offsetValue = this._offsetsCache[keyOffset];
  51940. }
  51941. }
  51942. if (offsetValue === undefined) {
  51943. switch (this._animation.dataType) {
  51944. // Float
  51945. case BABYLON.Animation.ANIMATIONTYPE_FLOAT:
  51946. offsetValue = 0;
  51947. break;
  51948. // Quaternion
  51949. case BABYLON.Animation.ANIMATIONTYPE_QUATERNION:
  51950. offsetValue = new BABYLON.Quaternion(0, 0, 0, 0);
  51951. break;
  51952. // Vector3
  51953. case BABYLON.Animation.ANIMATIONTYPE_VECTOR3:
  51954. offsetValue = BABYLON.Vector3.Zero();
  51955. break;
  51956. // Vector2
  51957. case BABYLON.Animation.ANIMATIONTYPE_VECTOR2:
  51958. offsetValue = BABYLON.Vector2.Zero();
  51959. break;
  51960. // Size
  51961. case BABYLON.Animation.ANIMATIONTYPE_SIZE:
  51962. offsetValue = BABYLON.Size.Zero();
  51963. break;
  51964. // Color3
  51965. case BABYLON.Animation.ANIMATIONTYPE_COLOR3:
  51966. offsetValue = BABYLON.Color3.Black();
  51967. }
  51968. }
  51969. // Compute value
  51970. var repeatCount = (ratio / range) >> 0;
  51971. var currentFrame = returnValue ? from + ratio % range : to;
  51972. // Need to normalize?
  51973. if (this._host && this._host.syncRoot) {
  51974. var syncRoot = this._host.syncRoot;
  51975. var hostNormalizedFrame = (syncRoot.masterFrame - syncRoot.fromFrame) / (syncRoot.toFrame - syncRoot.fromFrame);
  51976. currentFrame = from + (to - from) * hostNormalizedFrame;
  51977. }
  51978. var currentValue = this._interpolate(currentFrame, repeatCount, this._getCorrectLoopMode(), offsetValue, highLimitValue);
  51979. // Set value
  51980. this.setValue(currentValue, weight);
  51981. // Check events
  51982. var events = this._animation.getEvents();
  51983. for (var index = 0; index < events.length; index++) {
  51984. // Make sure current frame has passed event frame and that event frame is within the current range
  51985. // Also, handle both forward and reverse animations
  51986. if ((range > 0 && currentFrame >= events[index].frame && events[index].frame >= from) ||
  51987. (range < 0 && currentFrame <= events[index].frame && events[index].frame <= from)) {
  51988. var event = events[index];
  51989. if (!event.isDone) {
  51990. // If event should be done only once, remove it.
  51991. if (event.onlyOnce) {
  51992. events.splice(index, 1);
  51993. index--;
  51994. }
  51995. event.isDone = true;
  51996. event.action();
  51997. } // Don't do anything if the event has already be done.
  51998. }
  51999. else if (events[index].isDone && !events[index].onlyOnce) {
  52000. // reset event, the animation is looping
  52001. events[index].isDone = false;
  52002. }
  52003. }
  52004. if (!returnValue) {
  52005. this._stopped = true;
  52006. }
  52007. return returnValue;
  52008. };
  52009. return RuntimeAnimation;
  52010. }());
  52011. BABYLON.RuntimeAnimation = RuntimeAnimation;
  52012. })(BABYLON || (BABYLON = {}));
  52013. //# sourceMappingURL=babylon.runtimeAnimation.js.map
  52014. var BABYLON;
  52015. (function (BABYLON) {
  52016. var Animatable = /** @class */ (function () {
  52017. function Animatable(scene, target, fromFrame, toFrame, loopAnimation, speedRatio, onAnimationEnd, animations) {
  52018. if (fromFrame === void 0) { fromFrame = 0; }
  52019. if (toFrame === void 0) { toFrame = 100; }
  52020. if (loopAnimation === void 0) { loopAnimation = false; }
  52021. if (speedRatio === void 0) { speedRatio = 1.0; }
  52022. this.target = target;
  52023. this.fromFrame = fromFrame;
  52024. this.toFrame = toFrame;
  52025. this.loopAnimation = loopAnimation;
  52026. this.onAnimationEnd = onAnimationEnd;
  52027. this._localDelayOffset = null;
  52028. this._pausedDelay = null;
  52029. this._runtimeAnimations = new Array();
  52030. this._paused = false;
  52031. this._speedRatio = 1;
  52032. this._weight = -1.0;
  52033. this.animationStarted = false;
  52034. this._scene = scene;
  52035. if (animations) {
  52036. this.appendAnimations(target, animations);
  52037. }
  52038. this._speedRatio = speedRatio;
  52039. scene._activeAnimatables.push(this);
  52040. }
  52041. Object.defineProperty(Animatable.prototype, "syncRoot", {
  52042. /**
  52043. * Gets the root Animatable used to synchronize and normalize animations
  52044. */
  52045. get: function () {
  52046. return this._syncRoot;
  52047. },
  52048. enumerable: true,
  52049. configurable: true
  52050. });
  52051. Object.defineProperty(Animatable.prototype, "masterFrame", {
  52052. /**
  52053. * Gets the current frame of the first RuntimeAnimation
  52054. * Used to synchronize Animatables
  52055. */
  52056. get: function () {
  52057. if (this._runtimeAnimations.length === 0) {
  52058. return 0;
  52059. }
  52060. return this._runtimeAnimations[0].currentFrame;
  52061. },
  52062. enumerable: true,
  52063. configurable: true
  52064. });
  52065. Object.defineProperty(Animatable.prototype, "weight", {
  52066. /**
  52067. * Gets or sets the animatable weight (-1.0 by default meaning not weighted)
  52068. */
  52069. get: function () {
  52070. return this._weight;
  52071. },
  52072. set: function (value) {
  52073. if (value === -1) { // -1 is ok and means no weight
  52074. this._weight = -1;
  52075. return;
  52076. }
  52077. // Else weight must be in [0, 1] range
  52078. this._weight = Math.min(Math.max(value, 0), 1.0);
  52079. },
  52080. enumerable: true,
  52081. configurable: true
  52082. });
  52083. Object.defineProperty(Animatable.prototype, "speedRatio", {
  52084. /**
  52085. * Gets or sets the speed ratio to apply to the animatable (1.0 by default)
  52086. */
  52087. get: function () {
  52088. return this._speedRatio;
  52089. },
  52090. set: function (value) {
  52091. for (var index = 0; index < this._runtimeAnimations.length; index++) {
  52092. var animation = this._runtimeAnimations[index];
  52093. animation._prepareForSpeedRatioChange(value);
  52094. }
  52095. this._speedRatio = value;
  52096. },
  52097. enumerable: true,
  52098. configurable: true
  52099. });
  52100. // Methods
  52101. /**
  52102. * Synchronize and normalize current Animatable with a source Animatable
  52103. * This is useful when using animation weights and when animations are not of the same length
  52104. * @param root defines the root Animatable to synchronize with
  52105. * @returns the current Animatable
  52106. */
  52107. Animatable.prototype.syncWith = function (root) {
  52108. this._syncRoot = root;
  52109. if (root) {
  52110. // Make sure this animatable will animate after the root
  52111. var index = this._scene._activeAnimatables.indexOf(this);
  52112. if (index > -1) {
  52113. this._scene._activeAnimatables.splice(index, 1);
  52114. this._scene._activeAnimatables.push(this);
  52115. }
  52116. }
  52117. return this;
  52118. };
  52119. Animatable.prototype.getAnimations = function () {
  52120. return this._runtimeAnimations;
  52121. };
  52122. Animatable.prototype.appendAnimations = function (target, animations) {
  52123. for (var index = 0; index < animations.length; index++) {
  52124. var animation = animations[index];
  52125. this._runtimeAnimations.push(new BABYLON.RuntimeAnimation(target, animation, this._scene, this));
  52126. }
  52127. };
  52128. Animatable.prototype.getAnimationByTargetProperty = function (property) {
  52129. var runtimeAnimations = this._runtimeAnimations;
  52130. for (var index = 0; index < runtimeAnimations.length; index++) {
  52131. if (runtimeAnimations[index].animation.targetProperty === property) {
  52132. return runtimeAnimations[index].animation;
  52133. }
  52134. }
  52135. return null;
  52136. };
  52137. Animatable.prototype.getRuntimeAnimationByTargetProperty = function (property) {
  52138. var runtimeAnimations = this._runtimeAnimations;
  52139. for (var index = 0; index < runtimeAnimations.length; index++) {
  52140. if (runtimeAnimations[index].animation.targetProperty === property) {
  52141. return runtimeAnimations[index];
  52142. }
  52143. }
  52144. return null;
  52145. };
  52146. Animatable.prototype.reset = function () {
  52147. var runtimeAnimations = this._runtimeAnimations;
  52148. for (var index = 0; index < runtimeAnimations.length; index++) {
  52149. runtimeAnimations[index].reset();
  52150. }
  52151. // Reset to original value
  52152. for (index = 0; index < runtimeAnimations.length; index++) {
  52153. var animation = runtimeAnimations[index];
  52154. animation.animate(0, this.fromFrame, this.toFrame, false, this._speedRatio);
  52155. }
  52156. this._localDelayOffset = null;
  52157. this._pausedDelay = null;
  52158. };
  52159. Animatable.prototype.enableBlending = function (blendingSpeed) {
  52160. var runtimeAnimations = this._runtimeAnimations;
  52161. for (var index = 0; index < runtimeAnimations.length; index++) {
  52162. runtimeAnimations[index].animation.enableBlending = true;
  52163. runtimeAnimations[index].animation.blendingSpeed = blendingSpeed;
  52164. }
  52165. };
  52166. Animatable.prototype.disableBlending = function () {
  52167. var runtimeAnimations = this._runtimeAnimations;
  52168. for (var index = 0; index < runtimeAnimations.length; index++) {
  52169. runtimeAnimations[index].animation.enableBlending = false;
  52170. }
  52171. };
  52172. Animatable.prototype.goToFrame = function (frame) {
  52173. var runtimeAnimations = this._runtimeAnimations;
  52174. if (runtimeAnimations[0]) {
  52175. var fps = runtimeAnimations[0].animation.framePerSecond;
  52176. var currentFrame = runtimeAnimations[0].currentFrame;
  52177. var adjustTime = frame - currentFrame;
  52178. var delay = adjustTime * 1000 / (fps * this.speedRatio);
  52179. if (this._localDelayOffset === null) {
  52180. this._localDelayOffset = 0;
  52181. }
  52182. this._localDelayOffset -= delay;
  52183. }
  52184. for (var index = 0; index < runtimeAnimations.length; index++) {
  52185. runtimeAnimations[index].goToFrame(frame);
  52186. }
  52187. };
  52188. Animatable.prototype.pause = function () {
  52189. if (this._paused) {
  52190. return;
  52191. }
  52192. this._paused = true;
  52193. };
  52194. Animatable.prototype.restart = function () {
  52195. this._paused = false;
  52196. };
  52197. Animatable.prototype.stop = function (animationName) {
  52198. if (animationName) {
  52199. var idx = this._scene._activeAnimatables.indexOf(this);
  52200. if (idx > -1) {
  52201. var runtimeAnimations = this._runtimeAnimations;
  52202. for (var index = runtimeAnimations.length - 1; index >= 0; index--) {
  52203. if (typeof animationName === "string" && runtimeAnimations[index].animation.name != animationName) {
  52204. continue;
  52205. }
  52206. runtimeAnimations[index].dispose();
  52207. runtimeAnimations.splice(index, 1);
  52208. }
  52209. if (runtimeAnimations.length == 0) {
  52210. this._scene._activeAnimatables.splice(idx, 1);
  52211. if (this.onAnimationEnd) {
  52212. this.onAnimationEnd();
  52213. }
  52214. }
  52215. }
  52216. }
  52217. else {
  52218. var index = this._scene._activeAnimatables.indexOf(this);
  52219. if (index > -1) {
  52220. this._scene._activeAnimatables.splice(index, 1);
  52221. var runtimeAnimations = this._runtimeAnimations;
  52222. for (var index = 0; index < runtimeAnimations.length; index++) {
  52223. runtimeAnimations[index].dispose();
  52224. }
  52225. if (this.onAnimationEnd) {
  52226. this.onAnimationEnd();
  52227. }
  52228. }
  52229. }
  52230. };
  52231. Animatable.prototype._animate = function (delay) {
  52232. if (this._paused) {
  52233. this.animationStarted = false;
  52234. if (this._pausedDelay === null) {
  52235. this._pausedDelay = delay;
  52236. }
  52237. return true;
  52238. }
  52239. if (this._localDelayOffset === null) {
  52240. this._localDelayOffset = delay;
  52241. this._pausedDelay = null;
  52242. }
  52243. else if (this._pausedDelay !== null) {
  52244. this._localDelayOffset += delay - this._pausedDelay;
  52245. this._pausedDelay = null;
  52246. }
  52247. if (this._weight === 0) { // We consider that an animation with a weight === 0 is "actively" paused
  52248. return true;
  52249. }
  52250. // Animating
  52251. var running = false;
  52252. var runtimeAnimations = this._runtimeAnimations;
  52253. var index;
  52254. for (index = 0; index < runtimeAnimations.length; index++) {
  52255. var animation = runtimeAnimations[index];
  52256. var isRunning = animation.animate(delay - this._localDelayOffset, this.fromFrame, this.toFrame, this.loopAnimation, this._speedRatio, this._weight);
  52257. running = running || isRunning;
  52258. }
  52259. this.animationStarted = running;
  52260. if (!running) {
  52261. // Remove from active animatables
  52262. index = this._scene._activeAnimatables.indexOf(this);
  52263. this._scene._activeAnimatables.splice(index, 1);
  52264. // Dispose all runtime animations
  52265. for (index = 0; index < runtimeAnimations.length; index++) {
  52266. runtimeAnimations[index].dispose();
  52267. }
  52268. }
  52269. if (!running && this.onAnimationEnd) {
  52270. this.onAnimationEnd();
  52271. this.onAnimationEnd = null;
  52272. }
  52273. return running;
  52274. };
  52275. return Animatable;
  52276. }());
  52277. BABYLON.Animatable = Animatable;
  52278. })(BABYLON || (BABYLON = {}));
  52279. //# sourceMappingURL=babylon.animatable.js.map
  52280. var BABYLON;
  52281. (function (BABYLON) {
  52282. var EasingFunction = /** @class */ (function () {
  52283. function EasingFunction() {
  52284. // Properties
  52285. this._easingMode = EasingFunction.EASINGMODE_EASEIN;
  52286. }
  52287. Object.defineProperty(EasingFunction, "EASINGMODE_EASEIN", {
  52288. get: function () {
  52289. return EasingFunction._EASINGMODE_EASEIN;
  52290. },
  52291. enumerable: true,
  52292. configurable: true
  52293. });
  52294. Object.defineProperty(EasingFunction, "EASINGMODE_EASEOUT", {
  52295. get: function () {
  52296. return EasingFunction._EASINGMODE_EASEOUT;
  52297. },
  52298. enumerable: true,
  52299. configurable: true
  52300. });
  52301. Object.defineProperty(EasingFunction, "EASINGMODE_EASEINOUT", {
  52302. get: function () {
  52303. return EasingFunction._EASINGMODE_EASEINOUT;
  52304. },
  52305. enumerable: true,
  52306. configurable: true
  52307. });
  52308. EasingFunction.prototype.setEasingMode = function (easingMode) {
  52309. var n = Math.min(Math.max(easingMode, 0), 2);
  52310. this._easingMode = n;
  52311. };
  52312. EasingFunction.prototype.getEasingMode = function () {
  52313. return this._easingMode;
  52314. };
  52315. EasingFunction.prototype.easeInCore = function (gradient) {
  52316. throw new Error('You must implement this method');
  52317. };
  52318. EasingFunction.prototype.ease = function (gradient) {
  52319. switch (this._easingMode) {
  52320. case EasingFunction.EASINGMODE_EASEIN:
  52321. return this.easeInCore(gradient);
  52322. case EasingFunction.EASINGMODE_EASEOUT:
  52323. return (1 - this.easeInCore(1 - gradient));
  52324. }
  52325. if (gradient >= 0.5) {
  52326. return (((1 - this.easeInCore((1 - gradient) * 2)) * 0.5) + 0.5);
  52327. }
  52328. return (this.easeInCore(gradient * 2) * 0.5);
  52329. };
  52330. //Statics
  52331. EasingFunction._EASINGMODE_EASEIN = 0;
  52332. EasingFunction._EASINGMODE_EASEOUT = 1;
  52333. EasingFunction._EASINGMODE_EASEINOUT = 2;
  52334. return EasingFunction;
  52335. }());
  52336. BABYLON.EasingFunction = EasingFunction;
  52337. var CircleEase = /** @class */ (function (_super) {
  52338. __extends(CircleEase, _super);
  52339. function CircleEase() {
  52340. return _super !== null && _super.apply(this, arguments) || this;
  52341. }
  52342. CircleEase.prototype.easeInCore = function (gradient) {
  52343. gradient = Math.max(0, Math.min(1, gradient));
  52344. return (1.0 - Math.sqrt(1.0 - (gradient * gradient)));
  52345. };
  52346. return CircleEase;
  52347. }(EasingFunction));
  52348. BABYLON.CircleEase = CircleEase;
  52349. var BackEase = /** @class */ (function (_super) {
  52350. __extends(BackEase, _super);
  52351. function BackEase(amplitude) {
  52352. if (amplitude === void 0) { amplitude = 1; }
  52353. var _this = _super.call(this) || this;
  52354. _this.amplitude = amplitude;
  52355. return _this;
  52356. }
  52357. BackEase.prototype.easeInCore = function (gradient) {
  52358. var num = Math.max(0, this.amplitude);
  52359. return (Math.pow(gradient, 3.0) - ((gradient * num) * Math.sin(3.1415926535897931 * gradient)));
  52360. };
  52361. return BackEase;
  52362. }(EasingFunction));
  52363. BABYLON.BackEase = BackEase;
  52364. var BounceEase = /** @class */ (function (_super) {
  52365. __extends(BounceEase, _super);
  52366. function BounceEase(bounces, bounciness) {
  52367. if (bounces === void 0) { bounces = 3; }
  52368. if (bounciness === void 0) { bounciness = 2; }
  52369. var _this = _super.call(this) || this;
  52370. _this.bounces = bounces;
  52371. _this.bounciness = bounciness;
  52372. return _this;
  52373. }
  52374. BounceEase.prototype.easeInCore = function (gradient) {
  52375. var y = Math.max(0.0, this.bounces);
  52376. var bounciness = this.bounciness;
  52377. if (bounciness <= 1.0) {
  52378. bounciness = 1.001;
  52379. }
  52380. var num9 = Math.pow(bounciness, y);
  52381. var num5 = 1.0 - bounciness;
  52382. var num4 = ((1.0 - num9) / num5) + (num9 * 0.5);
  52383. var num15 = gradient * num4;
  52384. var num65 = Math.log((-num15 * (1.0 - bounciness)) + 1.0) / Math.log(bounciness);
  52385. var num3 = Math.floor(num65);
  52386. var num13 = num3 + 1.0;
  52387. var num8 = (1.0 - Math.pow(bounciness, num3)) / (num5 * num4);
  52388. var num12 = (1.0 - Math.pow(bounciness, num13)) / (num5 * num4);
  52389. var num7 = (num8 + num12) * 0.5;
  52390. var num6 = gradient - num7;
  52391. var num2 = num7 - num8;
  52392. return (((-Math.pow(1.0 / bounciness, y - num3) / (num2 * num2)) * (num6 - num2)) * (num6 + num2));
  52393. };
  52394. return BounceEase;
  52395. }(EasingFunction));
  52396. BABYLON.BounceEase = BounceEase;
  52397. var CubicEase = /** @class */ (function (_super) {
  52398. __extends(CubicEase, _super);
  52399. function CubicEase() {
  52400. return _super !== null && _super.apply(this, arguments) || this;
  52401. }
  52402. CubicEase.prototype.easeInCore = function (gradient) {
  52403. return (gradient * gradient * gradient);
  52404. };
  52405. return CubicEase;
  52406. }(EasingFunction));
  52407. BABYLON.CubicEase = CubicEase;
  52408. var ElasticEase = /** @class */ (function (_super) {
  52409. __extends(ElasticEase, _super);
  52410. function ElasticEase(oscillations, springiness) {
  52411. if (oscillations === void 0) { oscillations = 3; }
  52412. if (springiness === void 0) { springiness = 3; }
  52413. var _this = _super.call(this) || this;
  52414. _this.oscillations = oscillations;
  52415. _this.springiness = springiness;
  52416. return _this;
  52417. }
  52418. ElasticEase.prototype.easeInCore = function (gradient) {
  52419. var num2;
  52420. var num3 = Math.max(0.0, this.oscillations);
  52421. var num = Math.max(0.0, this.springiness);
  52422. if (num == 0) {
  52423. num2 = gradient;
  52424. }
  52425. else {
  52426. num2 = (Math.exp(num * gradient) - 1.0) / (Math.exp(num) - 1.0);
  52427. }
  52428. return (num2 * Math.sin(((6.2831853071795862 * num3) + 1.5707963267948966) * gradient));
  52429. };
  52430. return ElasticEase;
  52431. }(EasingFunction));
  52432. BABYLON.ElasticEase = ElasticEase;
  52433. var ExponentialEase = /** @class */ (function (_super) {
  52434. __extends(ExponentialEase, _super);
  52435. function ExponentialEase(exponent) {
  52436. if (exponent === void 0) { exponent = 2; }
  52437. var _this = _super.call(this) || this;
  52438. _this.exponent = exponent;
  52439. return _this;
  52440. }
  52441. ExponentialEase.prototype.easeInCore = function (gradient) {
  52442. if (this.exponent <= 0) {
  52443. return gradient;
  52444. }
  52445. return ((Math.exp(this.exponent * gradient) - 1.0) / (Math.exp(this.exponent) - 1.0));
  52446. };
  52447. return ExponentialEase;
  52448. }(EasingFunction));
  52449. BABYLON.ExponentialEase = ExponentialEase;
  52450. var PowerEase = /** @class */ (function (_super) {
  52451. __extends(PowerEase, _super);
  52452. function PowerEase(power) {
  52453. if (power === void 0) { power = 2; }
  52454. var _this = _super.call(this) || this;
  52455. _this.power = power;
  52456. return _this;
  52457. }
  52458. PowerEase.prototype.easeInCore = function (gradient) {
  52459. var y = Math.max(0.0, this.power);
  52460. return Math.pow(gradient, y);
  52461. };
  52462. return PowerEase;
  52463. }(EasingFunction));
  52464. BABYLON.PowerEase = PowerEase;
  52465. var QuadraticEase = /** @class */ (function (_super) {
  52466. __extends(QuadraticEase, _super);
  52467. function QuadraticEase() {
  52468. return _super !== null && _super.apply(this, arguments) || this;
  52469. }
  52470. QuadraticEase.prototype.easeInCore = function (gradient) {
  52471. return (gradient * gradient);
  52472. };
  52473. return QuadraticEase;
  52474. }(EasingFunction));
  52475. BABYLON.QuadraticEase = QuadraticEase;
  52476. var QuarticEase = /** @class */ (function (_super) {
  52477. __extends(QuarticEase, _super);
  52478. function QuarticEase() {
  52479. return _super !== null && _super.apply(this, arguments) || this;
  52480. }
  52481. QuarticEase.prototype.easeInCore = function (gradient) {
  52482. return (gradient * gradient * gradient * gradient);
  52483. };
  52484. return QuarticEase;
  52485. }(EasingFunction));
  52486. BABYLON.QuarticEase = QuarticEase;
  52487. var QuinticEase = /** @class */ (function (_super) {
  52488. __extends(QuinticEase, _super);
  52489. function QuinticEase() {
  52490. return _super !== null && _super.apply(this, arguments) || this;
  52491. }
  52492. QuinticEase.prototype.easeInCore = function (gradient) {
  52493. return (gradient * gradient * gradient * gradient * gradient);
  52494. };
  52495. return QuinticEase;
  52496. }(EasingFunction));
  52497. BABYLON.QuinticEase = QuinticEase;
  52498. var SineEase = /** @class */ (function (_super) {
  52499. __extends(SineEase, _super);
  52500. function SineEase() {
  52501. return _super !== null && _super.apply(this, arguments) || this;
  52502. }
  52503. SineEase.prototype.easeInCore = function (gradient) {
  52504. return (1.0 - Math.sin(1.5707963267948966 * (1.0 - gradient)));
  52505. };
  52506. return SineEase;
  52507. }(EasingFunction));
  52508. BABYLON.SineEase = SineEase;
  52509. var BezierCurveEase = /** @class */ (function (_super) {
  52510. __extends(BezierCurveEase, _super);
  52511. function BezierCurveEase(x1, y1, x2, y2) {
  52512. if (x1 === void 0) { x1 = 0; }
  52513. if (y1 === void 0) { y1 = 0; }
  52514. if (x2 === void 0) { x2 = 1; }
  52515. if (y2 === void 0) { y2 = 1; }
  52516. var _this = _super.call(this) || this;
  52517. _this.x1 = x1;
  52518. _this.y1 = y1;
  52519. _this.x2 = x2;
  52520. _this.y2 = y2;
  52521. return _this;
  52522. }
  52523. BezierCurveEase.prototype.easeInCore = function (gradient) {
  52524. return BABYLON.BezierCurve.interpolate(gradient, this.x1, this.y1, this.x2, this.y2);
  52525. };
  52526. return BezierCurveEase;
  52527. }(EasingFunction));
  52528. BABYLON.BezierCurveEase = BezierCurveEase;
  52529. })(BABYLON || (BABYLON = {}));
  52530. //# sourceMappingURL=babylon.easing.js.map
  52531. var BABYLON;
  52532. (function (BABYLON) {
  52533. /**
  52534. * A Condition applied to an Action
  52535. */
  52536. var Condition = /** @class */ (function () {
  52537. /**
  52538. * Creates a new Condition
  52539. * @param actionManager the manager of the action the condition is applied to
  52540. */
  52541. function Condition(actionManager) {
  52542. this._actionManager = actionManager;
  52543. }
  52544. /**
  52545. * Check if the current condition is valid
  52546. * @returns a boolean
  52547. */
  52548. Condition.prototype.isValid = function () {
  52549. return true;
  52550. };
  52551. /**
  52552. * Internal only
  52553. * @hidden
  52554. */
  52555. Condition.prototype._getProperty = function (propertyPath) {
  52556. return this._actionManager._getProperty(propertyPath);
  52557. };
  52558. /**
  52559. * Internal only
  52560. * @hidden
  52561. */
  52562. Condition.prototype._getEffectiveTarget = function (target, propertyPath) {
  52563. return this._actionManager._getEffectiveTarget(target, propertyPath);
  52564. };
  52565. /**
  52566. * Serialize placeholder for child classes
  52567. * @returns the serialized object
  52568. */
  52569. Condition.prototype.serialize = function () {
  52570. };
  52571. /**
  52572. * Internal only
  52573. * @hidden
  52574. */
  52575. Condition.prototype._serialize = function (serializedCondition) {
  52576. return {
  52577. type: 2,
  52578. children: [],
  52579. name: serializedCondition.name,
  52580. properties: serializedCondition.properties
  52581. };
  52582. };
  52583. return Condition;
  52584. }());
  52585. BABYLON.Condition = Condition;
  52586. /**
  52587. * Defines specific conditional operators as extensions of Condition
  52588. */
  52589. var ValueCondition = /** @class */ (function (_super) {
  52590. __extends(ValueCondition, _super);
  52591. /**
  52592. * Creates a new ValueCondition
  52593. * @param actionManager manager for the action the condition applies to
  52594. * @param target for the action
  52595. * @param propertyPath path to specify the property of the target the conditional operator uses
  52596. * @param value the value compared by the conditional operator against the current value of the property
  52597. * @param operator the conditional operator, default ValueCondition.IsEqual
  52598. */
  52599. function ValueCondition(actionManager, target,
  52600. /** path to specify the property of the target the conditional operator uses */
  52601. propertyPath,
  52602. /** the value compared by the conditional operator against the current value of the property */
  52603. value,
  52604. /** the conditional operator, default ValueCondition.IsEqual */
  52605. operator) {
  52606. if (operator === void 0) { operator = ValueCondition.IsEqual; }
  52607. var _this = _super.call(this, actionManager) || this;
  52608. _this.propertyPath = propertyPath;
  52609. _this.value = value;
  52610. _this.operator = operator;
  52611. _this._target = target;
  52612. _this._effectiveTarget = _this._getEffectiveTarget(target, _this.propertyPath);
  52613. _this._property = _this._getProperty(_this.propertyPath);
  52614. return _this;
  52615. }
  52616. Object.defineProperty(ValueCondition, "IsEqual", {
  52617. /**
  52618. * returns the number for IsEqual
  52619. */
  52620. get: function () {
  52621. return ValueCondition._IsEqual;
  52622. },
  52623. enumerable: true,
  52624. configurable: true
  52625. });
  52626. Object.defineProperty(ValueCondition, "IsDifferent", {
  52627. /**
  52628. * Returns the number for IsDifferent
  52629. */
  52630. get: function () {
  52631. return ValueCondition._IsDifferent;
  52632. },
  52633. enumerable: true,
  52634. configurable: true
  52635. });
  52636. Object.defineProperty(ValueCondition, "IsGreater", {
  52637. /**
  52638. * Returns the number for IsGreater
  52639. */
  52640. get: function () {
  52641. return ValueCondition._IsGreater;
  52642. },
  52643. enumerable: true,
  52644. configurable: true
  52645. });
  52646. Object.defineProperty(ValueCondition, "IsLesser", {
  52647. /**
  52648. * Returns the number for IsLesser
  52649. */
  52650. get: function () {
  52651. return ValueCondition._IsLesser;
  52652. },
  52653. enumerable: true,
  52654. configurable: true
  52655. });
  52656. /**
  52657. * Compares the given value with the property value for the specified conditional operator
  52658. * @returns the result of the comparison
  52659. */
  52660. ValueCondition.prototype.isValid = function () {
  52661. switch (this.operator) {
  52662. case ValueCondition.IsGreater:
  52663. return this._effectiveTarget[this._property] > this.value;
  52664. case ValueCondition.IsLesser:
  52665. return this._effectiveTarget[this._property] < this.value;
  52666. case ValueCondition.IsEqual:
  52667. case ValueCondition.IsDifferent:
  52668. var check;
  52669. if (this.value.equals) {
  52670. check = this.value.equals(this._effectiveTarget[this._property]);
  52671. }
  52672. else {
  52673. check = this.value === this._effectiveTarget[this._property];
  52674. }
  52675. return this.operator === ValueCondition.IsEqual ? check : !check;
  52676. }
  52677. return false;
  52678. };
  52679. /**
  52680. * Serialize the ValueCondition into a JSON compatible object
  52681. * @returns serialization object
  52682. */
  52683. ValueCondition.prototype.serialize = function () {
  52684. return this._serialize({
  52685. name: "ValueCondition",
  52686. properties: [
  52687. BABYLON.Action._GetTargetProperty(this._target),
  52688. { name: "propertyPath", value: this.propertyPath },
  52689. { name: "value", value: BABYLON.Action._SerializeValueAsString(this.value) },
  52690. { name: "operator", value: ValueCondition.GetOperatorName(this.operator) }
  52691. ]
  52692. });
  52693. };
  52694. /**
  52695. * Gets the name of the conditional operator for the ValueCondition
  52696. * @param operator the conditional operator
  52697. * @returns the name
  52698. */
  52699. ValueCondition.GetOperatorName = function (operator) {
  52700. switch (operator) {
  52701. case ValueCondition._IsEqual: return "IsEqual";
  52702. case ValueCondition._IsDifferent: return "IsDifferent";
  52703. case ValueCondition._IsGreater: return "IsGreater";
  52704. case ValueCondition._IsLesser: return "IsLesser";
  52705. default: return "";
  52706. }
  52707. };
  52708. /**
  52709. * Internal only
  52710. * @hidden
  52711. */
  52712. ValueCondition._IsEqual = 0;
  52713. /**
  52714. * Internal only
  52715. * @hidden
  52716. */
  52717. ValueCondition._IsDifferent = 1;
  52718. /**
  52719. * Internal only
  52720. * @hidden
  52721. */
  52722. ValueCondition._IsGreater = 2;
  52723. /**
  52724. * Internal only
  52725. * @hidden
  52726. */
  52727. ValueCondition._IsLesser = 3;
  52728. return ValueCondition;
  52729. }(Condition));
  52730. BABYLON.ValueCondition = ValueCondition;
  52731. /**
  52732. * Defines a predicate condition as an extension of Condition
  52733. */
  52734. var PredicateCondition = /** @class */ (function (_super) {
  52735. __extends(PredicateCondition, _super);
  52736. /**
  52737. * Creates a new PredicateCondition
  52738. * @param actionManager manager for the action the condition applies to
  52739. * @param predicate defines the predicate function used to validate the condition
  52740. */
  52741. function PredicateCondition(actionManager,
  52742. /** defines the predicate function used to validate the condition */
  52743. predicate) {
  52744. var _this = _super.call(this, actionManager) || this;
  52745. _this.predicate = predicate;
  52746. return _this;
  52747. }
  52748. /**
  52749. * @returns the validity of the predicate condition
  52750. */
  52751. PredicateCondition.prototype.isValid = function () {
  52752. return this.predicate();
  52753. };
  52754. return PredicateCondition;
  52755. }(Condition));
  52756. BABYLON.PredicateCondition = PredicateCondition;
  52757. /**
  52758. * Defines a state condition as an extension of Condition
  52759. */
  52760. var StateCondition = /** @class */ (function (_super) {
  52761. __extends(StateCondition, _super);
  52762. /**
  52763. * Creates a new StateCondition
  52764. * @param actionManager manager for the action the condition applies to
  52765. * @param target of the condition
  52766. * @param value to compare with target state
  52767. */
  52768. function StateCondition(actionManager, target, value) {
  52769. var _this = _super.call(this, actionManager) || this;
  52770. _this.value = value;
  52771. _this._target = target;
  52772. return _this;
  52773. }
  52774. /**
  52775. * @returns the validity of the state
  52776. */
  52777. StateCondition.prototype.isValid = function () {
  52778. return this._target.state === this.value;
  52779. };
  52780. /**
  52781. * Serialize the StateCondition into a JSON compatible object
  52782. * @returns serialization object
  52783. */
  52784. StateCondition.prototype.serialize = function () {
  52785. return this._serialize({
  52786. name: "StateCondition",
  52787. properties: [
  52788. BABYLON.Action._GetTargetProperty(this._target),
  52789. { name: "value", value: this.value }
  52790. ]
  52791. });
  52792. };
  52793. return StateCondition;
  52794. }(Condition));
  52795. BABYLON.StateCondition = StateCondition;
  52796. })(BABYLON || (BABYLON = {}));
  52797. //# sourceMappingURL=babylon.condition.js.map
  52798. var BABYLON;
  52799. (function (BABYLON) {
  52800. /**
  52801. * The action to be carried out following a trigger
  52802. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#available-actions
  52803. */
  52804. var Action = /** @class */ (function () {
  52805. /**
  52806. * Creates a new Action
  52807. * @param triggerOptions the trigger, with or without parameters, for the action
  52808. * @param condition an optional determinant of action
  52809. */
  52810. function Action(
  52811. /** the trigger, with or without parameters, for the action */
  52812. triggerOptions, condition) {
  52813. this.triggerOptions = triggerOptions;
  52814. /**
  52815. * An event triggered prior to action being executed.
  52816. */
  52817. this.onBeforeExecuteObservable = new BABYLON.Observable();
  52818. if (triggerOptions.parameter) {
  52819. this.trigger = triggerOptions.trigger;
  52820. this._triggerParameter = triggerOptions.parameter;
  52821. }
  52822. else {
  52823. this.trigger = triggerOptions;
  52824. }
  52825. this._nextActiveAction = this;
  52826. this._condition = condition;
  52827. }
  52828. /**
  52829. * Internal only
  52830. * @hidden
  52831. */
  52832. Action.prototype._prepare = function () {
  52833. };
  52834. /**
  52835. * Gets the trigger parameters
  52836. * @returns the trigger parameters
  52837. */
  52838. Action.prototype.getTriggerParameter = function () {
  52839. return this._triggerParameter;
  52840. };
  52841. /**
  52842. * Internal only - executes current action event
  52843. * @hidden
  52844. */
  52845. Action.prototype._executeCurrent = function (evt) {
  52846. if (this._nextActiveAction._condition) {
  52847. var condition = this._nextActiveAction._condition;
  52848. var currentRenderId = this._actionManager.getScene().getRenderId();
  52849. // We cache the current evaluation for the current frame
  52850. if (condition._evaluationId === currentRenderId) {
  52851. if (!condition._currentResult) {
  52852. return;
  52853. }
  52854. }
  52855. else {
  52856. condition._evaluationId = currentRenderId;
  52857. if (!condition.isValid()) {
  52858. condition._currentResult = false;
  52859. return;
  52860. }
  52861. condition._currentResult = true;
  52862. }
  52863. }
  52864. this.onBeforeExecuteObservable.notifyObservers(this);
  52865. this._nextActiveAction.execute(evt);
  52866. this.skipToNextActiveAction();
  52867. };
  52868. /**
  52869. * Execute placeholder for child classes
  52870. * @param evt optional action event
  52871. */
  52872. Action.prototype.execute = function (evt) {
  52873. };
  52874. /**
  52875. * Skips to next active action
  52876. */
  52877. Action.prototype.skipToNextActiveAction = function () {
  52878. if (this._nextActiveAction._child) {
  52879. if (!this._nextActiveAction._child._actionManager) {
  52880. this._nextActiveAction._child._actionManager = this._actionManager;
  52881. }
  52882. this._nextActiveAction = this._nextActiveAction._child;
  52883. }
  52884. else {
  52885. this._nextActiveAction = this;
  52886. }
  52887. };
  52888. /**
  52889. * Adds action to chain of actions, may be a DoNothingAction
  52890. * @param action defines the next action to execute
  52891. * @returns The action passed in
  52892. * @see https://www.babylonjs-playground.com/#1T30HR#0
  52893. */
  52894. Action.prototype.then = function (action) {
  52895. this._child = action;
  52896. action._actionManager = this._actionManager;
  52897. action._prepare();
  52898. return action;
  52899. };
  52900. /**
  52901. * Internal only
  52902. * @hidden
  52903. */
  52904. Action.prototype._getProperty = function (propertyPath) {
  52905. return this._actionManager._getProperty(propertyPath);
  52906. };
  52907. /**
  52908. * Internal only
  52909. * @hidden
  52910. */
  52911. Action.prototype._getEffectiveTarget = function (target, propertyPath) {
  52912. return this._actionManager._getEffectiveTarget(target, propertyPath);
  52913. };
  52914. /**
  52915. * Serialize placeholder for child classes
  52916. * @param parent of child
  52917. * @returns the serialized object
  52918. */
  52919. Action.prototype.serialize = function (parent) {
  52920. };
  52921. /**
  52922. * Internal only called by serialize
  52923. * @hidden
  52924. */
  52925. Action.prototype._serialize = function (serializedAction, parent) {
  52926. var serializationObject = {
  52927. type: 1,
  52928. children: [],
  52929. name: serializedAction.name,
  52930. properties: serializedAction.properties || []
  52931. };
  52932. // Serialize child
  52933. if (this._child) {
  52934. this._child.serialize(serializationObject);
  52935. }
  52936. // Check if "this" has a condition
  52937. if (this._condition) {
  52938. var serializedCondition = this._condition.serialize();
  52939. serializedCondition.children.push(serializationObject);
  52940. if (parent) {
  52941. parent.children.push(serializedCondition);
  52942. }
  52943. return serializedCondition;
  52944. }
  52945. if (parent) {
  52946. parent.children.push(serializationObject);
  52947. }
  52948. return serializationObject;
  52949. };
  52950. /**
  52951. * Internal only
  52952. * @hidden
  52953. */
  52954. Action._SerializeValueAsString = function (value) {
  52955. if (typeof value === "number") {
  52956. return value.toString();
  52957. }
  52958. if (typeof value === "boolean") {
  52959. return value ? "true" : "false";
  52960. }
  52961. if (value instanceof BABYLON.Vector2) {
  52962. return value.x + ", " + value.y;
  52963. }
  52964. if (value instanceof BABYLON.Vector3) {
  52965. return value.x + ", " + value.y + ", " + value.z;
  52966. }
  52967. if (value instanceof BABYLON.Color3) {
  52968. return value.r + ", " + value.g + ", " + value.b;
  52969. }
  52970. if (value instanceof BABYLON.Color4) {
  52971. return value.r + ", " + value.g + ", " + value.b + ", " + value.a;
  52972. }
  52973. return value; // string
  52974. };
  52975. /**
  52976. * Internal only
  52977. * @hidden
  52978. */
  52979. Action._GetTargetProperty = function (target) {
  52980. return {
  52981. name: "target",
  52982. targetType: target instanceof BABYLON.Mesh ? "MeshProperties"
  52983. : target instanceof BABYLON.Light ? "LightProperties"
  52984. : target instanceof BABYLON.Camera ? "CameraProperties"
  52985. : "SceneProperties",
  52986. value: target instanceof BABYLON.Scene ? "Scene" : target.name
  52987. };
  52988. };
  52989. return Action;
  52990. }());
  52991. BABYLON.Action = Action;
  52992. })(BABYLON || (BABYLON = {}));
  52993. //# sourceMappingURL=babylon.action.js.map
  52994. var BABYLON;
  52995. (function (BABYLON) {
  52996. /**
  52997. * ActionEvent is the event being sent when an action is triggered.
  52998. */
  52999. var ActionEvent = /** @class */ (function () {
  53000. /**
  53001. * Creates a new ActionEvent
  53002. * @param source The mesh or sprite that triggered the action
  53003. * @param pointerX The X mouse cursor position at the time of the event
  53004. * @param pointerY The Y mouse cursor position at the time of the event
  53005. * @param meshUnderPointer The mesh that is currently pointed at (can be null)
  53006. * @param sourceEvent the original (browser) event that triggered the ActionEvent
  53007. * @param additionalData additional data for the event
  53008. */
  53009. function ActionEvent(
  53010. /** The mesh or sprite that triggered the action */
  53011. source,
  53012. /** The X mouse cursor position at the time of the event */
  53013. pointerX,
  53014. /** The Y mouse cursor position at the time of the event */
  53015. pointerY,
  53016. /** The mesh that is currently pointed at (can be null) */
  53017. meshUnderPointer,
  53018. /** the original (browser) event that triggered the ActionEvent */
  53019. sourceEvent,
  53020. /** additional data for the event */
  53021. additionalData) {
  53022. this.source = source;
  53023. this.pointerX = pointerX;
  53024. this.pointerY = pointerY;
  53025. this.meshUnderPointer = meshUnderPointer;
  53026. this.sourceEvent = sourceEvent;
  53027. this.additionalData = additionalData;
  53028. }
  53029. /**
  53030. * Helper function to auto-create an ActionEvent from a source mesh.
  53031. * @param source The source mesh that triggered the event
  53032. * @param evt The original (browser) event
  53033. * @param additionalData additional data for the event
  53034. * @returns the new ActionEvent
  53035. */
  53036. ActionEvent.CreateNew = function (source, evt, additionalData) {
  53037. var scene = source.getScene();
  53038. return new ActionEvent(source, scene.pointerX, scene.pointerY, scene.meshUnderPointer, evt, additionalData);
  53039. };
  53040. /**
  53041. * Helper function to auto-create an ActionEvent from a source sprite
  53042. * @param source The source sprite that triggered the event
  53043. * @param scene Scene associated with the sprite
  53044. * @param evt The original (browser) event
  53045. * @param additionalData additional data for the event
  53046. * @returns the new ActionEvent
  53047. */
  53048. ActionEvent.CreateNewFromSprite = function (source, scene, evt, additionalData) {
  53049. return new ActionEvent(source, scene.pointerX, scene.pointerY, scene.meshUnderPointer, evt, additionalData);
  53050. };
  53051. /**
  53052. * Helper function to auto-create an ActionEvent from a scene. If triggered by a mesh use ActionEvent.CreateNew
  53053. * @param scene the scene where the event occurred
  53054. * @param evt The original (browser) event
  53055. * @returns the new ActionEvent
  53056. */
  53057. ActionEvent.CreateNewFromScene = function (scene, evt) {
  53058. return new ActionEvent(null, scene.pointerX, scene.pointerY, scene.meshUnderPointer, evt);
  53059. };
  53060. /**
  53061. * Helper function to auto-create an ActionEvent from a primitive
  53062. * @param prim defines the target primitive
  53063. * @param pointerPos defines the pointer position
  53064. * @param evt The original (browser) event
  53065. * @param additionalData additional data for the event
  53066. * @returns the new ActionEvent
  53067. */
  53068. ActionEvent.CreateNewFromPrimitive = function (prim, pointerPos, evt, additionalData) {
  53069. return new ActionEvent(prim, pointerPos.x, pointerPos.y, null, evt, additionalData);
  53070. };
  53071. return ActionEvent;
  53072. }());
  53073. BABYLON.ActionEvent = ActionEvent;
  53074. /**
  53075. * Action Manager manages all events to be triggered on a given mesh or the global scene.
  53076. * A single scene can have many Action Managers to handle predefined actions on specific meshes.
  53077. * @see http://doc.babylonjs.com/how_to/how_to_use_actions
  53078. */
  53079. var ActionManager = /** @class */ (function () {
  53080. /**
  53081. * Creates a new action manager
  53082. * @param scene defines the hosting scene
  53083. */
  53084. function ActionManager(scene) {
  53085. // Members
  53086. /** Gets the list of actions */
  53087. this.actions = new Array();
  53088. /** Gets the cursor to use when hovering items */
  53089. this.hoverCursor = '';
  53090. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  53091. scene._actionManagers.push(this);
  53092. }
  53093. Object.defineProperty(ActionManager, "NothingTrigger", {
  53094. /**
  53095. * Nothing
  53096. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  53097. */
  53098. get: function () {
  53099. return ActionManager._NothingTrigger;
  53100. },
  53101. enumerable: true,
  53102. configurable: true
  53103. });
  53104. Object.defineProperty(ActionManager, "OnPickTrigger", {
  53105. /**
  53106. * On pick
  53107. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  53108. */
  53109. get: function () {
  53110. return ActionManager._OnPickTrigger;
  53111. },
  53112. enumerable: true,
  53113. configurable: true
  53114. });
  53115. Object.defineProperty(ActionManager, "OnLeftPickTrigger", {
  53116. /**
  53117. * On left pick
  53118. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  53119. */
  53120. get: function () {
  53121. return ActionManager._OnLeftPickTrigger;
  53122. },
  53123. enumerable: true,
  53124. configurable: true
  53125. });
  53126. Object.defineProperty(ActionManager, "OnRightPickTrigger", {
  53127. /**
  53128. * On right pick
  53129. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  53130. */
  53131. get: function () {
  53132. return ActionManager._OnRightPickTrigger;
  53133. },
  53134. enumerable: true,
  53135. configurable: true
  53136. });
  53137. Object.defineProperty(ActionManager, "OnCenterPickTrigger", {
  53138. /**
  53139. * On center pick
  53140. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  53141. */
  53142. get: function () {
  53143. return ActionManager._OnCenterPickTrigger;
  53144. },
  53145. enumerable: true,
  53146. configurable: true
  53147. });
  53148. Object.defineProperty(ActionManager, "OnPickDownTrigger", {
  53149. /**
  53150. * On pick down
  53151. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  53152. */
  53153. get: function () {
  53154. return ActionManager._OnPickDownTrigger;
  53155. },
  53156. enumerable: true,
  53157. configurable: true
  53158. });
  53159. Object.defineProperty(ActionManager, "OnDoublePickTrigger", {
  53160. /**
  53161. * On double pick
  53162. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  53163. */
  53164. get: function () {
  53165. return ActionManager._OnDoublePickTrigger;
  53166. },
  53167. enumerable: true,
  53168. configurable: true
  53169. });
  53170. Object.defineProperty(ActionManager, "OnPickUpTrigger", {
  53171. /**
  53172. * On pick up
  53173. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  53174. */
  53175. get: function () {
  53176. return ActionManager._OnPickUpTrigger;
  53177. },
  53178. enumerable: true,
  53179. configurable: true
  53180. });
  53181. Object.defineProperty(ActionManager, "OnPickOutTrigger", {
  53182. /**
  53183. * On pick out.
  53184. * This trigger will only be raised if you also declared a OnPickDown
  53185. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  53186. */
  53187. get: function () {
  53188. return ActionManager._OnPickOutTrigger;
  53189. },
  53190. enumerable: true,
  53191. configurable: true
  53192. });
  53193. Object.defineProperty(ActionManager, "OnLongPressTrigger", {
  53194. /**
  53195. * On long press
  53196. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  53197. */
  53198. get: function () {
  53199. return ActionManager._OnLongPressTrigger;
  53200. },
  53201. enumerable: true,
  53202. configurable: true
  53203. });
  53204. Object.defineProperty(ActionManager, "OnPointerOverTrigger", {
  53205. /**
  53206. * On pointer over
  53207. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  53208. */
  53209. get: function () {
  53210. return ActionManager._OnPointerOverTrigger;
  53211. },
  53212. enumerable: true,
  53213. configurable: true
  53214. });
  53215. Object.defineProperty(ActionManager, "OnPointerOutTrigger", {
  53216. /**
  53217. * On pointer out
  53218. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  53219. */
  53220. get: function () {
  53221. return ActionManager._OnPointerOutTrigger;
  53222. },
  53223. enumerable: true,
  53224. configurable: true
  53225. });
  53226. Object.defineProperty(ActionManager, "OnEveryFrameTrigger", {
  53227. /**
  53228. * On every frame
  53229. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  53230. */
  53231. get: function () {
  53232. return ActionManager._OnEveryFrameTrigger;
  53233. },
  53234. enumerable: true,
  53235. configurable: true
  53236. });
  53237. Object.defineProperty(ActionManager, "OnIntersectionEnterTrigger", {
  53238. /**
  53239. * On intersection enter
  53240. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  53241. */
  53242. get: function () {
  53243. return ActionManager._OnIntersectionEnterTrigger;
  53244. },
  53245. enumerable: true,
  53246. configurable: true
  53247. });
  53248. Object.defineProperty(ActionManager, "OnIntersectionExitTrigger", {
  53249. /**
  53250. * On intersection exit
  53251. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  53252. */
  53253. get: function () {
  53254. return ActionManager._OnIntersectionExitTrigger;
  53255. },
  53256. enumerable: true,
  53257. configurable: true
  53258. });
  53259. Object.defineProperty(ActionManager, "OnKeyDownTrigger", {
  53260. /**
  53261. * On key down
  53262. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  53263. */
  53264. get: function () {
  53265. return ActionManager._OnKeyDownTrigger;
  53266. },
  53267. enumerable: true,
  53268. configurable: true
  53269. });
  53270. Object.defineProperty(ActionManager, "OnKeyUpTrigger", {
  53271. /**
  53272. * On key up
  53273. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  53274. */
  53275. get: function () {
  53276. return ActionManager._OnKeyUpTrigger;
  53277. },
  53278. enumerable: true,
  53279. configurable: true
  53280. });
  53281. // Methods
  53282. /**
  53283. * Releases all associated resources
  53284. */
  53285. ActionManager.prototype.dispose = function () {
  53286. var index = this._scene._actionManagers.indexOf(this);
  53287. for (var i = 0; i < this.actions.length; i++) {
  53288. var action = this.actions[i];
  53289. ActionManager.Triggers[action.trigger]--;
  53290. if (ActionManager.Triggers[action.trigger] === 0) {
  53291. delete ActionManager.Triggers[action.trigger];
  53292. }
  53293. }
  53294. if (index > -1) {
  53295. this._scene._actionManagers.splice(index, 1);
  53296. }
  53297. };
  53298. /**
  53299. * Gets hosting scene
  53300. * @returns the hosting scene
  53301. */
  53302. ActionManager.prototype.getScene = function () {
  53303. return this._scene;
  53304. };
  53305. /**
  53306. * Does this action manager handles actions of any of the given triggers
  53307. * @param triggers defines the triggers to be tested
  53308. * @return a boolean indicating whether one (or more) of the triggers is handled
  53309. */
  53310. ActionManager.prototype.hasSpecificTriggers = function (triggers) {
  53311. for (var index = 0; index < this.actions.length; index++) {
  53312. var action = this.actions[index];
  53313. if (triggers.indexOf(action.trigger) > -1) {
  53314. return true;
  53315. }
  53316. }
  53317. return false;
  53318. };
  53319. /**
  53320. * Does this action manager handles actions of a given trigger
  53321. * @param trigger defines the trigger to be tested
  53322. * @param parameterPredicate defines an optional predicate to filter triggers by parameter
  53323. * @return whether the trigger is handled
  53324. */
  53325. ActionManager.prototype.hasSpecificTrigger = function (trigger, parameterPredicate) {
  53326. for (var index = 0; index < this.actions.length; index++) {
  53327. var action = this.actions[index];
  53328. if (action.trigger === trigger) {
  53329. if (parameterPredicate) {
  53330. if (parameterPredicate(action.getTriggerParameter())) {
  53331. return true;
  53332. }
  53333. }
  53334. else {
  53335. return true;
  53336. }
  53337. }
  53338. }
  53339. return false;
  53340. };
  53341. Object.defineProperty(ActionManager.prototype, "hasPointerTriggers", {
  53342. /**
  53343. * Does this action manager has pointer triggers
  53344. */
  53345. get: function () {
  53346. for (var index = 0; index < this.actions.length; index++) {
  53347. var action = this.actions[index];
  53348. if (action.trigger >= ActionManager._OnPickTrigger && action.trigger <= ActionManager._OnPointerOutTrigger) {
  53349. return true;
  53350. }
  53351. }
  53352. return false;
  53353. },
  53354. enumerable: true,
  53355. configurable: true
  53356. });
  53357. Object.defineProperty(ActionManager.prototype, "hasPickTriggers", {
  53358. /**
  53359. * Does this action manager has pick triggers
  53360. */
  53361. get: function () {
  53362. for (var index = 0; index < this.actions.length; index++) {
  53363. var action = this.actions[index];
  53364. if (action.trigger >= ActionManager._OnPickTrigger && action.trigger <= ActionManager._OnPickUpTrigger) {
  53365. return true;
  53366. }
  53367. }
  53368. return false;
  53369. },
  53370. enumerable: true,
  53371. configurable: true
  53372. });
  53373. Object.defineProperty(ActionManager, "HasTriggers", {
  53374. /**
  53375. * Does exist one action manager with at least one trigger
  53376. **/
  53377. get: function () {
  53378. for (var t in ActionManager.Triggers) {
  53379. if (ActionManager.Triggers.hasOwnProperty(t)) {
  53380. return true;
  53381. }
  53382. }
  53383. return false;
  53384. },
  53385. enumerable: true,
  53386. configurable: true
  53387. });
  53388. Object.defineProperty(ActionManager, "HasPickTriggers", {
  53389. /**
  53390. * Does exist one action manager with at least one pick trigger
  53391. **/
  53392. get: function () {
  53393. for (var t in ActionManager.Triggers) {
  53394. if (ActionManager.Triggers.hasOwnProperty(t)) {
  53395. var t_int = parseInt(t);
  53396. if (t_int >= ActionManager._OnPickTrigger && t_int <= ActionManager._OnPickUpTrigger) {
  53397. return true;
  53398. }
  53399. }
  53400. }
  53401. return false;
  53402. },
  53403. enumerable: true,
  53404. configurable: true
  53405. });
  53406. /**
  53407. * Does exist one action manager that handles actions of a given trigger
  53408. * @param trigger defines the trigger to be tested
  53409. * @return a boolean indicating whether the trigger is handeled by at least one action manager
  53410. **/
  53411. ActionManager.HasSpecificTrigger = function (trigger) {
  53412. for (var t in ActionManager.Triggers) {
  53413. if (ActionManager.Triggers.hasOwnProperty(t)) {
  53414. var t_int = parseInt(t);
  53415. if (t_int === trigger) {
  53416. return true;
  53417. }
  53418. }
  53419. }
  53420. return false;
  53421. };
  53422. /**
  53423. * Registers an action to this action manager
  53424. * @param action defines the action to be registered
  53425. * @return the action amended (prepared) after registration
  53426. */
  53427. ActionManager.prototype.registerAction = function (action) {
  53428. if (action.trigger === ActionManager.OnEveryFrameTrigger) {
  53429. if (this.getScene().actionManager !== this) {
  53430. BABYLON.Tools.Warn("OnEveryFrameTrigger can only be used with scene.actionManager");
  53431. return null;
  53432. }
  53433. }
  53434. this.actions.push(action);
  53435. if (ActionManager.Triggers[action.trigger]) {
  53436. ActionManager.Triggers[action.trigger]++;
  53437. }
  53438. else {
  53439. ActionManager.Triggers[action.trigger] = 1;
  53440. }
  53441. action._actionManager = this;
  53442. action._prepare();
  53443. return action;
  53444. };
  53445. /**
  53446. * Unregisters an action to this action manager
  53447. * @param action defines the action to be unregistered
  53448. * @return a boolean indicating whether the action has been unregistered
  53449. */
  53450. ActionManager.prototype.unregisterAction = function (action) {
  53451. var index = this.actions.indexOf(action);
  53452. if (index !== -1) {
  53453. this.actions.splice(index, 1);
  53454. ActionManager.Triggers[action.trigger] -= 1;
  53455. if (ActionManager.Triggers[action.trigger] === 0) {
  53456. delete ActionManager.Triggers[action.trigger];
  53457. }
  53458. delete action._actionManager;
  53459. return true;
  53460. }
  53461. return false;
  53462. };
  53463. /**
  53464. * Process a specific trigger
  53465. * @param trigger defines the trigger to process
  53466. * @param evt defines the event details to be processed
  53467. */
  53468. ActionManager.prototype.processTrigger = function (trigger, evt) {
  53469. for (var index = 0; index < this.actions.length; index++) {
  53470. var action = this.actions[index];
  53471. if (action.trigger === trigger) {
  53472. if (evt) {
  53473. if (trigger === ActionManager.OnKeyUpTrigger
  53474. || trigger === ActionManager.OnKeyDownTrigger) {
  53475. var parameter = action.getTriggerParameter();
  53476. if (parameter && parameter !== evt.sourceEvent.keyCode) {
  53477. if (!parameter.toLowerCase) {
  53478. continue;
  53479. }
  53480. var lowerCase = parameter.toLowerCase();
  53481. if (lowerCase !== evt.sourceEvent.key) {
  53482. var unicode = evt.sourceEvent.charCode ? evt.sourceEvent.charCode : evt.sourceEvent.keyCode;
  53483. var actualkey = String.fromCharCode(unicode).toLowerCase();
  53484. if (actualkey !== lowerCase) {
  53485. continue;
  53486. }
  53487. }
  53488. }
  53489. }
  53490. }
  53491. action._executeCurrent(evt);
  53492. }
  53493. }
  53494. };
  53495. /** @hidden */
  53496. ActionManager.prototype._getEffectiveTarget = function (target, propertyPath) {
  53497. var properties = propertyPath.split(".");
  53498. for (var index = 0; index < properties.length - 1; index++) {
  53499. target = target[properties[index]];
  53500. }
  53501. return target;
  53502. };
  53503. /** @hidden */
  53504. ActionManager.prototype._getProperty = function (propertyPath) {
  53505. var properties = propertyPath.split(".");
  53506. return properties[properties.length - 1];
  53507. };
  53508. /**
  53509. * Serialize this manager to a JSON object
  53510. * @param name defines the property name to store this manager
  53511. * @returns a JSON representation of this manager
  53512. */
  53513. ActionManager.prototype.serialize = function (name) {
  53514. var root = {
  53515. children: new Array(),
  53516. name: name,
  53517. type: 3,
  53518. properties: new Array() // Empty for root but required
  53519. };
  53520. for (var i = 0; i < this.actions.length; i++) {
  53521. var triggerObject = {
  53522. type: 0,
  53523. children: new Array(),
  53524. name: ActionManager.GetTriggerName(this.actions[i].trigger),
  53525. properties: new Array()
  53526. };
  53527. var triggerOptions = this.actions[i].triggerOptions;
  53528. if (triggerOptions && typeof triggerOptions !== "number") {
  53529. if (triggerOptions.parameter instanceof BABYLON.Node) {
  53530. triggerObject.properties.push(BABYLON.Action._GetTargetProperty(triggerOptions.parameter));
  53531. }
  53532. else {
  53533. var parameter = {};
  53534. BABYLON.Tools.DeepCopy(triggerOptions.parameter, parameter, ["mesh"]);
  53535. if (triggerOptions.parameter.mesh) {
  53536. parameter._meshId = triggerOptions.parameter.mesh.id;
  53537. }
  53538. triggerObject.properties.push({ name: "parameter", targetType: null, value: parameter });
  53539. }
  53540. }
  53541. // Serialize child action, recursively
  53542. this.actions[i].serialize(triggerObject);
  53543. // Add serialized trigger
  53544. root.children.push(triggerObject);
  53545. }
  53546. return root;
  53547. };
  53548. /**
  53549. * Creates a new ActionManager from a JSON data
  53550. * @param parsedActions defines the JSON data to read from
  53551. * @param object defines the hosting mesh
  53552. * @param scene defines the hosting scene
  53553. */
  53554. ActionManager.Parse = function (parsedActions, object, scene) {
  53555. var actionManager = new ActionManager(scene);
  53556. if (object === null)
  53557. scene.actionManager = actionManager;
  53558. else
  53559. object.actionManager = actionManager;
  53560. // instanciate a new object
  53561. var instanciate = function (name, params) {
  53562. // TODO: We will need to find a solution for the next line when using commonjs / es6 .
  53563. var newInstance = Object.create(BABYLON.Tools.Instantiate("BABYLON." + name).prototype);
  53564. newInstance.constructor.apply(newInstance, params);
  53565. return newInstance;
  53566. };
  53567. var parseParameter = function (name, value, target, propertyPath) {
  53568. if (propertyPath === null) {
  53569. // String, boolean or float
  53570. var floatValue = parseFloat(value);
  53571. if (value === "true" || value === "false")
  53572. return value === "true";
  53573. else
  53574. return isNaN(floatValue) ? value : floatValue;
  53575. }
  53576. var effectiveTarget = propertyPath.split(".");
  53577. var values = value.split(",");
  53578. // Get effective Target
  53579. for (var i = 0; i < effectiveTarget.length; i++) {
  53580. target = target[effectiveTarget[i]];
  53581. }
  53582. // Return appropriate value with its type
  53583. if (typeof (target) === "boolean")
  53584. return values[0] === "true";
  53585. if (typeof (target) === "string")
  53586. return values[0];
  53587. // Parameters with multiple values such as Vector3 etc.
  53588. var split = new Array();
  53589. for (var i = 0; i < values.length; i++)
  53590. split.push(parseFloat(values[i]));
  53591. if (target instanceof BABYLON.Vector3)
  53592. return BABYLON.Vector3.FromArray(split);
  53593. if (target instanceof BABYLON.Vector4)
  53594. return BABYLON.Vector4.FromArray(split);
  53595. if (target instanceof BABYLON.Color3)
  53596. return BABYLON.Color3.FromArray(split);
  53597. if (target instanceof BABYLON.Color4)
  53598. return BABYLON.Color4.FromArray(split);
  53599. return parseFloat(values[0]);
  53600. };
  53601. // traverse graph per trigger
  53602. var traverse = function (parsedAction, trigger, condition, action, combineArray) {
  53603. if (combineArray === void 0) { combineArray = null; }
  53604. if (parsedAction.detached)
  53605. return;
  53606. var parameters = new Array();
  53607. var target = null;
  53608. var propertyPath = null;
  53609. var combine = parsedAction.combine && parsedAction.combine.length > 0;
  53610. // Parameters
  53611. if (parsedAction.type === 2)
  53612. parameters.push(actionManager);
  53613. else
  53614. parameters.push(trigger);
  53615. if (combine) {
  53616. var actions = new Array();
  53617. for (var j = 0; j < parsedAction.combine.length; j++) {
  53618. traverse(parsedAction.combine[j], ActionManager.NothingTrigger, condition, action, actions);
  53619. }
  53620. parameters.push(actions);
  53621. }
  53622. else {
  53623. for (var i = 0; i < parsedAction.properties.length; i++) {
  53624. var value = parsedAction.properties[i].value;
  53625. var name = parsedAction.properties[i].name;
  53626. var targetType = parsedAction.properties[i].targetType;
  53627. if (name === "target")
  53628. if (targetType !== null && targetType === "SceneProperties")
  53629. value = target = scene;
  53630. else
  53631. value = target = scene.getNodeByName(value);
  53632. else if (name === "parent")
  53633. value = scene.getNodeByName(value);
  53634. else if (name === "sound")
  53635. value = scene.getSoundByName(value);
  53636. else if (name !== "propertyPath") {
  53637. if (parsedAction.type === 2 && name === "operator")
  53638. value = BABYLON.ValueCondition[value];
  53639. else
  53640. value = parseParameter(name, value, target, name === "value" ? propertyPath : null);
  53641. }
  53642. else {
  53643. propertyPath = value;
  53644. }
  53645. parameters.push(value);
  53646. }
  53647. }
  53648. if (combineArray === null) {
  53649. parameters.push(condition);
  53650. }
  53651. else {
  53652. parameters.push(null);
  53653. }
  53654. // If interpolate value action
  53655. if (parsedAction.name === "InterpolateValueAction") {
  53656. var param = parameters[parameters.length - 2];
  53657. parameters[parameters.length - 1] = param;
  53658. parameters[parameters.length - 2] = condition;
  53659. }
  53660. // Action or condition(s) and not CombineAction
  53661. var newAction = instanciate(parsedAction.name, parameters);
  53662. if (newAction instanceof BABYLON.Condition && condition !== null) {
  53663. var nothing = new BABYLON.DoNothingAction(trigger, condition);
  53664. if (action)
  53665. action.then(nothing);
  53666. else
  53667. actionManager.registerAction(nothing);
  53668. action = nothing;
  53669. }
  53670. if (combineArray === null) {
  53671. if (newAction instanceof BABYLON.Condition) {
  53672. condition = newAction;
  53673. newAction = action;
  53674. }
  53675. else {
  53676. condition = null;
  53677. if (action)
  53678. action.then(newAction);
  53679. else
  53680. actionManager.registerAction(newAction);
  53681. }
  53682. }
  53683. else {
  53684. combineArray.push(newAction);
  53685. }
  53686. for (var i = 0; i < parsedAction.children.length; i++)
  53687. traverse(parsedAction.children[i], trigger, condition, newAction, null);
  53688. };
  53689. // triggers
  53690. for (var i = 0; i < parsedActions.children.length; i++) {
  53691. var triggerParams;
  53692. var trigger = parsedActions.children[i];
  53693. if (trigger.properties.length > 0) {
  53694. var param = trigger.properties[0].value;
  53695. var value = trigger.properties[0].targetType === null ? param : scene.getMeshByName(param);
  53696. if (value._meshId) {
  53697. value.mesh = scene.getMeshByID(value._meshId);
  53698. }
  53699. triggerParams = { trigger: ActionManager[trigger.name], parameter: value };
  53700. }
  53701. else
  53702. triggerParams = ActionManager[trigger.name];
  53703. for (var j = 0; j < trigger.children.length; j++) {
  53704. if (!trigger.detached)
  53705. traverse(trigger.children[j], triggerParams, null, null);
  53706. }
  53707. }
  53708. };
  53709. /**
  53710. * Get a trigger name by index
  53711. * @param trigger defines the trigger index
  53712. * @returns a trigger name
  53713. */
  53714. ActionManager.GetTriggerName = function (trigger) {
  53715. switch (trigger) {
  53716. case 0: return "NothingTrigger";
  53717. case 1: return "OnPickTrigger";
  53718. case 2: return "OnLeftPickTrigger";
  53719. case 3: return "OnRightPickTrigger";
  53720. case 4: return "OnCenterPickTrigger";
  53721. case 5: return "OnPickDownTrigger";
  53722. case 6: return "OnPickUpTrigger";
  53723. case 7: return "OnLongPressTrigger";
  53724. case 8: return "OnPointerOverTrigger";
  53725. case 9: return "OnPointerOutTrigger";
  53726. case 10: return "OnEveryFrameTrigger";
  53727. case 11: return "OnIntersectionEnterTrigger";
  53728. case 12: return "OnIntersectionExitTrigger";
  53729. case 13: return "OnKeyDownTrigger";
  53730. case 14: return "OnKeyUpTrigger";
  53731. case 15: return "OnPickOutTrigger";
  53732. default: return "";
  53733. }
  53734. };
  53735. // Statics
  53736. ActionManager._NothingTrigger = 0;
  53737. ActionManager._OnPickTrigger = 1;
  53738. ActionManager._OnLeftPickTrigger = 2;
  53739. ActionManager._OnRightPickTrigger = 3;
  53740. ActionManager._OnCenterPickTrigger = 4;
  53741. ActionManager._OnPickDownTrigger = 5;
  53742. ActionManager._OnDoublePickTrigger = 6;
  53743. ActionManager._OnPickUpTrigger = 7;
  53744. ActionManager._OnLongPressTrigger = 8;
  53745. ActionManager._OnPointerOverTrigger = 9;
  53746. ActionManager._OnPointerOutTrigger = 10;
  53747. ActionManager._OnEveryFrameTrigger = 11;
  53748. ActionManager._OnIntersectionEnterTrigger = 12;
  53749. ActionManager._OnIntersectionExitTrigger = 13;
  53750. ActionManager._OnKeyDownTrigger = 14;
  53751. ActionManager._OnKeyUpTrigger = 15;
  53752. ActionManager._OnPickOutTrigger = 16;
  53753. /** Gets the list of active triggers */
  53754. ActionManager.Triggers = {};
  53755. return ActionManager;
  53756. }());
  53757. BABYLON.ActionManager = ActionManager;
  53758. })(BABYLON || (BABYLON = {}));
  53759. //# sourceMappingURL=babylon.actionManager.js.map
  53760. var BABYLON;
  53761. (function (BABYLON) {
  53762. var InterpolateValueAction = /** @class */ (function (_super) {
  53763. __extends(InterpolateValueAction, _super);
  53764. function InterpolateValueAction(triggerOptions, target, propertyPath, value, duration, condition, stopOtherAnimations, onInterpolationDone) {
  53765. if (duration === void 0) { duration = 1000; }
  53766. var _this = _super.call(this, triggerOptions, condition) || this;
  53767. _this.propertyPath = propertyPath;
  53768. _this.value = value;
  53769. _this.duration = duration;
  53770. _this.stopOtherAnimations = stopOtherAnimations;
  53771. _this.onInterpolationDone = onInterpolationDone;
  53772. _this.onInterpolationDoneObservable = new BABYLON.Observable();
  53773. _this._target = _this._effectiveTarget = target;
  53774. return _this;
  53775. }
  53776. InterpolateValueAction.prototype._prepare = function () {
  53777. this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);
  53778. this._property = this._getProperty(this.propertyPath);
  53779. };
  53780. InterpolateValueAction.prototype.execute = function () {
  53781. var _this = this;
  53782. var scene = this._actionManager.getScene();
  53783. var keys = [
  53784. {
  53785. frame: 0,
  53786. value: this._effectiveTarget[this._property]
  53787. }, {
  53788. frame: 100,
  53789. value: this.value
  53790. }
  53791. ];
  53792. var dataType;
  53793. if (typeof this.value === "number") {
  53794. dataType = BABYLON.Animation.ANIMATIONTYPE_FLOAT;
  53795. }
  53796. else if (this.value instanceof BABYLON.Color3) {
  53797. dataType = BABYLON.Animation.ANIMATIONTYPE_COLOR3;
  53798. }
  53799. else if (this.value instanceof BABYLON.Vector3) {
  53800. dataType = BABYLON.Animation.ANIMATIONTYPE_VECTOR3;
  53801. }
  53802. else if (this.value instanceof BABYLON.Matrix) {
  53803. dataType = BABYLON.Animation.ANIMATIONTYPE_MATRIX;
  53804. }
  53805. else if (this.value instanceof BABYLON.Quaternion) {
  53806. dataType = BABYLON.Animation.ANIMATIONTYPE_QUATERNION;
  53807. }
  53808. else {
  53809. BABYLON.Tools.Warn("InterpolateValueAction: Unsupported type (" + typeof this.value + ")");
  53810. return;
  53811. }
  53812. var animation = new BABYLON.Animation("InterpolateValueAction", this._property, 100 * (1000.0 / this.duration), dataType, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  53813. animation.setKeys(keys);
  53814. if (this.stopOtherAnimations) {
  53815. scene.stopAnimation(this._effectiveTarget);
  53816. }
  53817. var wrapper = function () {
  53818. _this.onInterpolationDoneObservable.notifyObservers(_this);
  53819. if (_this.onInterpolationDone) {
  53820. _this.onInterpolationDone();
  53821. }
  53822. };
  53823. scene.beginDirectAnimation(this._effectiveTarget, [animation], 0, 100, false, 1, wrapper);
  53824. };
  53825. InterpolateValueAction.prototype.serialize = function (parent) {
  53826. return _super.prototype._serialize.call(this, {
  53827. name: "InterpolateValueAction",
  53828. properties: [
  53829. BABYLON.Action._GetTargetProperty(this._target),
  53830. { name: "propertyPath", value: this.propertyPath },
  53831. { name: "value", value: BABYLON.Action._SerializeValueAsString(this.value) },
  53832. { name: "duration", value: BABYLON.Action._SerializeValueAsString(this.duration) },
  53833. { name: "stopOtherAnimations", value: BABYLON.Action._SerializeValueAsString(this.stopOtherAnimations) || false }
  53834. ]
  53835. }, parent);
  53836. };
  53837. return InterpolateValueAction;
  53838. }(BABYLON.Action));
  53839. BABYLON.InterpolateValueAction = InterpolateValueAction;
  53840. })(BABYLON || (BABYLON = {}));
  53841. //# sourceMappingURL=babylon.interpolateValueAction.js.map
  53842. var BABYLON;
  53843. (function (BABYLON) {
  53844. var SwitchBooleanAction = /** @class */ (function (_super) {
  53845. __extends(SwitchBooleanAction, _super);
  53846. function SwitchBooleanAction(triggerOptions, target, propertyPath, condition) {
  53847. var _this = _super.call(this, triggerOptions, condition) || this;
  53848. _this.propertyPath = propertyPath;
  53849. _this._target = _this._effectiveTarget = target;
  53850. return _this;
  53851. }
  53852. SwitchBooleanAction.prototype._prepare = function () {
  53853. this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);
  53854. this._property = this._getProperty(this.propertyPath);
  53855. };
  53856. SwitchBooleanAction.prototype.execute = function () {
  53857. this._effectiveTarget[this._property] = !this._effectiveTarget[this._property];
  53858. };
  53859. SwitchBooleanAction.prototype.serialize = function (parent) {
  53860. return _super.prototype._serialize.call(this, {
  53861. name: "SwitchBooleanAction",
  53862. properties: [
  53863. BABYLON.Action._GetTargetProperty(this._target),
  53864. { name: "propertyPath", value: this.propertyPath }
  53865. ]
  53866. }, parent);
  53867. };
  53868. return SwitchBooleanAction;
  53869. }(BABYLON.Action));
  53870. BABYLON.SwitchBooleanAction = SwitchBooleanAction;
  53871. var SetStateAction = /** @class */ (function (_super) {
  53872. __extends(SetStateAction, _super);
  53873. function SetStateAction(triggerOptions, target, value, condition) {
  53874. var _this = _super.call(this, triggerOptions, condition) || this;
  53875. _this.value = value;
  53876. _this._target = target;
  53877. return _this;
  53878. }
  53879. SetStateAction.prototype.execute = function () {
  53880. this._target.state = this.value;
  53881. };
  53882. SetStateAction.prototype.serialize = function (parent) {
  53883. return _super.prototype._serialize.call(this, {
  53884. name: "SetStateAction",
  53885. properties: [
  53886. BABYLON.Action._GetTargetProperty(this._target),
  53887. { name: "value", value: this.value }
  53888. ]
  53889. }, parent);
  53890. };
  53891. return SetStateAction;
  53892. }(BABYLON.Action));
  53893. BABYLON.SetStateAction = SetStateAction;
  53894. var SetValueAction = /** @class */ (function (_super) {
  53895. __extends(SetValueAction, _super);
  53896. function SetValueAction(triggerOptions, target, propertyPath, value, condition) {
  53897. var _this = _super.call(this, triggerOptions, condition) || this;
  53898. _this.propertyPath = propertyPath;
  53899. _this.value = value;
  53900. _this._target = _this._effectiveTarget = target;
  53901. return _this;
  53902. }
  53903. SetValueAction.prototype._prepare = function () {
  53904. this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);
  53905. this._property = this._getProperty(this.propertyPath);
  53906. };
  53907. SetValueAction.prototype.execute = function () {
  53908. this._effectiveTarget[this._property] = this.value;
  53909. if (this._target.markAsDirty) {
  53910. this._target.markAsDirty(this._property);
  53911. }
  53912. };
  53913. SetValueAction.prototype.serialize = function (parent) {
  53914. return _super.prototype._serialize.call(this, {
  53915. name: "SetValueAction",
  53916. properties: [
  53917. BABYLON.Action._GetTargetProperty(this._target),
  53918. { name: "propertyPath", value: this.propertyPath },
  53919. { name: "value", value: BABYLON.Action._SerializeValueAsString(this.value) }
  53920. ]
  53921. }, parent);
  53922. };
  53923. return SetValueAction;
  53924. }(BABYLON.Action));
  53925. BABYLON.SetValueAction = SetValueAction;
  53926. var IncrementValueAction = /** @class */ (function (_super) {
  53927. __extends(IncrementValueAction, _super);
  53928. function IncrementValueAction(triggerOptions, target, propertyPath, value, condition) {
  53929. var _this = _super.call(this, triggerOptions, condition) || this;
  53930. _this.propertyPath = propertyPath;
  53931. _this.value = value;
  53932. _this._target = _this._effectiveTarget = target;
  53933. return _this;
  53934. }
  53935. IncrementValueAction.prototype._prepare = function () {
  53936. this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);
  53937. this._property = this._getProperty(this.propertyPath);
  53938. if (typeof this._effectiveTarget[this._property] !== "number") {
  53939. BABYLON.Tools.Warn("Warning: IncrementValueAction can only be used with number values");
  53940. }
  53941. };
  53942. IncrementValueAction.prototype.execute = function () {
  53943. this._effectiveTarget[this._property] += this.value;
  53944. if (this._target.markAsDirty) {
  53945. this._target.markAsDirty(this._property);
  53946. }
  53947. };
  53948. IncrementValueAction.prototype.serialize = function (parent) {
  53949. return _super.prototype._serialize.call(this, {
  53950. name: "IncrementValueAction",
  53951. properties: [
  53952. BABYLON.Action._GetTargetProperty(this._target),
  53953. { name: "propertyPath", value: this.propertyPath },
  53954. { name: "value", value: BABYLON.Action._SerializeValueAsString(this.value) }
  53955. ]
  53956. }, parent);
  53957. };
  53958. return IncrementValueAction;
  53959. }(BABYLON.Action));
  53960. BABYLON.IncrementValueAction = IncrementValueAction;
  53961. var PlayAnimationAction = /** @class */ (function (_super) {
  53962. __extends(PlayAnimationAction, _super);
  53963. function PlayAnimationAction(triggerOptions, target, from, to, loop, condition) {
  53964. var _this = _super.call(this, triggerOptions, condition) || this;
  53965. _this.from = from;
  53966. _this.to = to;
  53967. _this.loop = loop;
  53968. _this._target = target;
  53969. return _this;
  53970. }
  53971. PlayAnimationAction.prototype._prepare = function () {
  53972. };
  53973. PlayAnimationAction.prototype.execute = function () {
  53974. var scene = this._actionManager.getScene();
  53975. scene.beginAnimation(this._target, this.from, this.to, this.loop);
  53976. };
  53977. PlayAnimationAction.prototype.serialize = function (parent) {
  53978. return _super.prototype._serialize.call(this, {
  53979. name: "PlayAnimationAction",
  53980. properties: [
  53981. BABYLON.Action._GetTargetProperty(this._target),
  53982. { name: "from", value: String(this.from) },
  53983. { name: "to", value: String(this.to) },
  53984. { name: "loop", value: BABYLON.Action._SerializeValueAsString(this.loop) || false }
  53985. ]
  53986. }, parent);
  53987. };
  53988. return PlayAnimationAction;
  53989. }(BABYLON.Action));
  53990. BABYLON.PlayAnimationAction = PlayAnimationAction;
  53991. var StopAnimationAction = /** @class */ (function (_super) {
  53992. __extends(StopAnimationAction, _super);
  53993. function StopAnimationAction(triggerOptions, target, condition) {
  53994. var _this = _super.call(this, triggerOptions, condition) || this;
  53995. _this._target = target;
  53996. return _this;
  53997. }
  53998. StopAnimationAction.prototype._prepare = function () {
  53999. };
  54000. StopAnimationAction.prototype.execute = function () {
  54001. var scene = this._actionManager.getScene();
  54002. scene.stopAnimation(this._target);
  54003. };
  54004. StopAnimationAction.prototype.serialize = function (parent) {
  54005. return _super.prototype._serialize.call(this, {
  54006. name: "StopAnimationAction",
  54007. properties: [BABYLON.Action._GetTargetProperty(this._target)]
  54008. }, parent);
  54009. };
  54010. return StopAnimationAction;
  54011. }(BABYLON.Action));
  54012. BABYLON.StopAnimationAction = StopAnimationAction;
  54013. var DoNothingAction = /** @class */ (function (_super) {
  54014. __extends(DoNothingAction, _super);
  54015. function DoNothingAction(triggerOptions, condition) {
  54016. if (triggerOptions === void 0) { triggerOptions = BABYLON.ActionManager.NothingTrigger; }
  54017. return _super.call(this, triggerOptions, condition) || this;
  54018. }
  54019. DoNothingAction.prototype.execute = function () {
  54020. };
  54021. DoNothingAction.prototype.serialize = function (parent) {
  54022. return _super.prototype._serialize.call(this, {
  54023. name: "DoNothingAction",
  54024. properties: []
  54025. }, parent);
  54026. };
  54027. return DoNothingAction;
  54028. }(BABYLON.Action));
  54029. BABYLON.DoNothingAction = DoNothingAction;
  54030. var CombineAction = /** @class */ (function (_super) {
  54031. __extends(CombineAction, _super);
  54032. function CombineAction(triggerOptions, children, condition) {
  54033. var _this = _super.call(this, triggerOptions, condition) || this;
  54034. _this.children = children;
  54035. return _this;
  54036. }
  54037. CombineAction.prototype._prepare = function () {
  54038. for (var index = 0; index < this.children.length; index++) {
  54039. this.children[index]._actionManager = this._actionManager;
  54040. this.children[index]._prepare();
  54041. }
  54042. };
  54043. CombineAction.prototype.execute = function (evt) {
  54044. for (var index = 0; index < this.children.length; index++) {
  54045. this.children[index].execute(evt);
  54046. }
  54047. };
  54048. CombineAction.prototype.serialize = function (parent) {
  54049. var serializationObject = _super.prototype._serialize.call(this, {
  54050. name: "CombineAction",
  54051. properties: [],
  54052. combine: []
  54053. }, parent);
  54054. for (var i = 0; i < this.children.length; i++) {
  54055. serializationObject.combine.push(this.children[i].serialize(null));
  54056. }
  54057. return serializationObject;
  54058. };
  54059. return CombineAction;
  54060. }(BABYLON.Action));
  54061. BABYLON.CombineAction = CombineAction;
  54062. var ExecuteCodeAction = /** @class */ (function (_super) {
  54063. __extends(ExecuteCodeAction, _super);
  54064. function ExecuteCodeAction(triggerOptions, func, condition) {
  54065. var _this = _super.call(this, triggerOptions, condition) || this;
  54066. _this.func = func;
  54067. return _this;
  54068. }
  54069. ExecuteCodeAction.prototype.execute = function (evt) {
  54070. this.func(evt);
  54071. };
  54072. return ExecuteCodeAction;
  54073. }(BABYLON.Action));
  54074. BABYLON.ExecuteCodeAction = ExecuteCodeAction;
  54075. var SetParentAction = /** @class */ (function (_super) {
  54076. __extends(SetParentAction, _super);
  54077. function SetParentAction(triggerOptions, target, parent, condition) {
  54078. var _this = _super.call(this, triggerOptions, condition) || this;
  54079. _this._target = target;
  54080. _this._parent = parent;
  54081. return _this;
  54082. }
  54083. SetParentAction.prototype._prepare = function () {
  54084. };
  54085. SetParentAction.prototype.execute = function () {
  54086. if (this._target.parent === this._parent) {
  54087. return;
  54088. }
  54089. var invertParentWorldMatrix = this._parent.getWorldMatrix().clone();
  54090. invertParentWorldMatrix.invert();
  54091. this._target.position = BABYLON.Vector3.TransformCoordinates(this._target.position, invertParentWorldMatrix);
  54092. this._target.parent = this._parent;
  54093. };
  54094. SetParentAction.prototype.serialize = function (parent) {
  54095. return _super.prototype._serialize.call(this, {
  54096. name: "SetParentAction",
  54097. properties: [
  54098. BABYLON.Action._GetTargetProperty(this._target),
  54099. BABYLON.Action._GetTargetProperty(this._parent),
  54100. ]
  54101. }, parent);
  54102. };
  54103. return SetParentAction;
  54104. }(BABYLON.Action));
  54105. BABYLON.SetParentAction = SetParentAction;
  54106. var PlaySoundAction = /** @class */ (function (_super) {
  54107. __extends(PlaySoundAction, _super);
  54108. function PlaySoundAction(triggerOptions, sound, condition) {
  54109. var _this = _super.call(this, triggerOptions, condition) || this;
  54110. _this._sound = sound;
  54111. return _this;
  54112. }
  54113. PlaySoundAction.prototype._prepare = function () {
  54114. };
  54115. PlaySoundAction.prototype.execute = function () {
  54116. if (this._sound !== undefined)
  54117. this._sound.play();
  54118. };
  54119. PlaySoundAction.prototype.serialize = function (parent) {
  54120. return _super.prototype._serialize.call(this, {
  54121. name: "PlaySoundAction",
  54122. properties: [{ name: "sound", value: this._sound.name }]
  54123. }, parent);
  54124. };
  54125. return PlaySoundAction;
  54126. }(BABYLON.Action));
  54127. BABYLON.PlaySoundAction = PlaySoundAction;
  54128. var StopSoundAction = /** @class */ (function (_super) {
  54129. __extends(StopSoundAction, _super);
  54130. function StopSoundAction(triggerOptions, sound, condition) {
  54131. var _this = _super.call(this, triggerOptions, condition) || this;
  54132. _this._sound = sound;
  54133. return _this;
  54134. }
  54135. StopSoundAction.prototype._prepare = function () {
  54136. };
  54137. StopSoundAction.prototype.execute = function () {
  54138. if (this._sound !== undefined)
  54139. this._sound.stop();
  54140. };
  54141. StopSoundAction.prototype.serialize = function (parent) {
  54142. return _super.prototype._serialize.call(this, {
  54143. name: "StopSoundAction",
  54144. properties: [{ name: "sound", value: this._sound.name }]
  54145. }, parent);
  54146. };
  54147. return StopSoundAction;
  54148. }(BABYLON.Action));
  54149. BABYLON.StopSoundAction = StopSoundAction;
  54150. })(BABYLON || (BABYLON = {}));
  54151. //# sourceMappingURL=babylon.directActions.js.map
  54152. var BABYLON;
  54153. (function (BABYLON) {
  54154. var SpriteManager = /** @class */ (function () {
  54155. function SpriteManager(name, imgUrl, capacity, cellSize, scene, epsilon, samplingMode) {
  54156. if (epsilon === void 0) { epsilon = 0.01; }
  54157. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  54158. this.name = name;
  54159. this.sprites = new Array();
  54160. this.renderingGroupId = 0;
  54161. this.layerMask = 0x0FFFFFFF;
  54162. this.fogEnabled = true;
  54163. this.isPickable = false;
  54164. /**
  54165. * An event triggered when the manager is disposed.
  54166. */
  54167. this.onDisposeObservable = new BABYLON.Observable();
  54168. this._vertexBuffers = {};
  54169. this._capacity = capacity;
  54170. this._spriteTexture = new BABYLON.Texture(imgUrl, scene, true, false, samplingMode);
  54171. this._spriteTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  54172. this._spriteTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  54173. if (cellSize.width && cellSize.height) {
  54174. this.cellWidth = cellSize.width;
  54175. this.cellHeight = cellSize.height;
  54176. }
  54177. else if (cellSize !== undefined) {
  54178. this.cellWidth = cellSize;
  54179. this.cellHeight = cellSize;
  54180. }
  54181. else {
  54182. return;
  54183. }
  54184. this._epsilon = epsilon;
  54185. this._scene = scene;
  54186. this._scene.spriteManagers.push(this);
  54187. var indices = [];
  54188. var index = 0;
  54189. for (var count = 0; count < capacity; count++) {
  54190. indices.push(index);
  54191. indices.push(index + 1);
  54192. indices.push(index + 2);
  54193. indices.push(index);
  54194. indices.push(index + 2);
  54195. indices.push(index + 3);
  54196. index += 4;
  54197. }
  54198. this._indexBuffer = scene.getEngine().createIndexBuffer(indices);
  54199. // VBO
  54200. // 16 floats per sprite (x, y, z, angle, sizeX, sizeY, offsetX, offsetY, invertU, invertV, cellIndexX, cellIndexY, color r, color g, color b, color a)
  54201. this._vertexData = new Float32Array(capacity * 16 * 4);
  54202. this._buffer = new BABYLON.Buffer(scene.getEngine(), this._vertexData, true, 16);
  54203. var positions = this._buffer.createVertexBuffer(BABYLON.VertexBuffer.PositionKind, 0, 4);
  54204. var options = this._buffer.createVertexBuffer("options", 4, 4);
  54205. var cellInfo = this._buffer.createVertexBuffer("cellInfo", 8, 4);
  54206. var colors = this._buffer.createVertexBuffer(BABYLON.VertexBuffer.ColorKind, 12, 4);
  54207. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = positions;
  54208. this._vertexBuffers["options"] = options;
  54209. this._vertexBuffers["cellInfo"] = cellInfo;
  54210. this._vertexBuffers[BABYLON.VertexBuffer.ColorKind] = colors;
  54211. // Effects
  54212. this._effectBase = this._scene.getEngine().createEffect("sprites", [BABYLON.VertexBuffer.PositionKind, "options", "cellInfo", BABYLON.VertexBuffer.ColorKind], ["view", "projection", "textureInfos", "alphaTest"], ["diffuseSampler"], "");
  54213. this._effectFog = this._scene.getEngine().createEffect("sprites", [BABYLON.VertexBuffer.PositionKind, "options", "cellInfo", BABYLON.VertexBuffer.ColorKind], ["view", "projection", "textureInfos", "alphaTest", "vFogInfos", "vFogColor"], ["diffuseSampler"], "#define FOG");
  54214. }
  54215. Object.defineProperty(SpriteManager.prototype, "onDispose", {
  54216. set: function (callback) {
  54217. if (this._onDisposeObserver) {
  54218. this.onDisposeObservable.remove(this._onDisposeObserver);
  54219. }
  54220. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  54221. },
  54222. enumerable: true,
  54223. configurable: true
  54224. });
  54225. Object.defineProperty(SpriteManager.prototype, "texture", {
  54226. get: function () {
  54227. return this._spriteTexture;
  54228. },
  54229. set: function (value) {
  54230. this._spriteTexture = value;
  54231. },
  54232. enumerable: true,
  54233. configurable: true
  54234. });
  54235. SpriteManager.prototype._appendSpriteVertex = function (index, sprite, offsetX, offsetY, rowSize) {
  54236. var arrayOffset = index * 16;
  54237. if (offsetX === 0)
  54238. offsetX = this._epsilon;
  54239. else if (offsetX === 1)
  54240. offsetX = 1 - this._epsilon;
  54241. if (offsetY === 0)
  54242. offsetY = this._epsilon;
  54243. else if (offsetY === 1)
  54244. offsetY = 1 - this._epsilon;
  54245. this._vertexData[arrayOffset] = sprite.position.x;
  54246. this._vertexData[arrayOffset + 1] = sprite.position.y;
  54247. this._vertexData[arrayOffset + 2] = sprite.position.z;
  54248. this._vertexData[arrayOffset + 3] = sprite.angle;
  54249. this._vertexData[arrayOffset + 4] = sprite.width;
  54250. this._vertexData[arrayOffset + 5] = sprite.height;
  54251. this._vertexData[arrayOffset + 6] = offsetX;
  54252. this._vertexData[arrayOffset + 7] = offsetY;
  54253. this._vertexData[arrayOffset + 8] = sprite.invertU ? 1 : 0;
  54254. this._vertexData[arrayOffset + 9] = sprite.invertV ? 1 : 0;
  54255. var offset = (sprite.cellIndex / rowSize) >> 0;
  54256. this._vertexData[arrayOffset + 10] = sprite.cellIndex - offset * rowSize;
  54257. this._vertexData[arrayOffset + 11] = offset;
  54258. // Color
  54259. this._vertexData[arrayOffset + 12] = sprite.color.r;
  54260. this._vertexData[arrayOffset + 13] = sprite.color.g;
  54261. this._vertexData[arrayOffset + 14] = sprite.color.b;
  54262. this._vertexData[arrayOffset + 15] = sprite.color.a;
  54263. };
  54264. SpriteManager.prototype.intersects = function (ray, camera, predicate, fastCheck) {
  54265. var count = Math.min(this._capacity, this.sprites.length);
  54266. var min = BABYLON.Vector3.Zero();
  54267. var max = BABYLON.Vector3.Zero();
  54268. var distance = Number.MAX_VALUE;
  54269. var currentSprite = null;
  54270. var cameraSpacePosition = BABYLON.Vector3.Zero();
  54271. var cameraView = camera.getViewMatrix();
  54272. for (var index = 0; index < count; index++) {
  54273. var sprite = this.sprites[index];
  54274. if (!sprite) {
  54275. continue;
  54276. }
  54277. if (predicate) {
  54278. if (!predicate(sprite)) {
  54279. continue;
  54280. }
  54281. }
  54282. else if (!sprite.isPickable) {
  54283. continue;
  54284. }
  54285. BABYLON.Vector3.TransformCoordinatesToRef(sprite.position, cameraView, cameraSpacePosition);
  54286. min.copyFromFloats(cameraSpacePosition.x - sprite.width / 2, cameraSpacePosition.y - sprite.height / 2, cameraSpacePosition.z);
  54287. max.copyFromFloats(cameraSpacePosition.x + sprite.width / 2, cameraSpacePosition.y + sprite.height / 2, cameraSpacePosition.z);
  54288. if (ray.intersectsBoxMinMax(min, max)) {
  54289. var currentDistance = BABYLON.Vector3.Distance(cameraSpacePosition, ray.origin);
  54290. if (distance > currentDistance) {
  54291. distance = currentDistance;
  54292. currentSprite = sprite;
  54293. if (fastCheck) {
  54294. break;
  54295. }
  54296. }
  54297. }
  54298. }
  54299. if (currentSprite) {
  54300. var result = new BABYLON.PickingInfo();
  54301. result.hit = true;
  54302. result.pickedSprite = currentSprite;
  54303. result.distance = distance;
  54304. return result;
  54305. }
  54306. return null;
  54307. };
  54308. SpriteManager.prototype.render = function () {
  54309. // Check
  54310. if (!this._effectBase.isReady() || !this._effectFog.isReady() || !this._spriteTexture || !this._spriteTexture.isReady())
  54311. return;
  54312. var engine = this._scene.getEngine();
  54313. var baseSize = this._spriteTexture.getBaseSize();
  54314. // Sprites
  54315. var deltaTime = engine.getDeltaTime();
  54316. var max = Math.min(this._capacity, this.sprites.length);
  54317. var rowSize = baseSize.width / this.cellWidth;
  54318. var offset = 0;
  54319. for (var index = 0; index < max; index++) {
  54320. var sprite = this.sprites[index];
  54321. if (!sprite) {
  54322. continue;
  54323. }
  54324. sprite._animate(deltaTime);
  54325. this._appendSpriteVertex(offset++, sprite, 0, 0, rowSize);
  54326. this._appendSpriteVertex(offset++, sprite, 1, 0, rowSize);
  54327. this._appendSpriteVertex(offset++, sprite, 1, 1, rowSize);
  54328. this._appendSpriteVertex(offset++, sprite, 0, 1, rowSize);
  54329. }
  54330. this._buffer.update(this._vertexData);
  54331. // Render
  54332. var effect = this._effectBase;
  54333. if (this._scene.fogEnabled && this._scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && this.fogEnabled) {
  54334. effect = this._effectFog;
  54335. }
  54336. engine.enableEffect(effect);
  54337. var viewMatrix = this._scene.getViewMatrix();
  54338. effect.setTexture("diffuseSampler", this._spriteTexture);
  54339. effect.setMatrix("view", viewMatrix);
  54340. effect.setMatrix("projection", this._scene.getProjectionMatrix());
  54341. effect.setFloat2("textureInfos", this.cellWidth / baseSize.width, this.cellHeight / baseSize.height);
  54342. // Fog
  54343. if (this._scene.fogEnabled && this._scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && this.fogEnabled) {
  54344. effect.setFloat4("vFogInfos", this._scene.fogMode, this._scene.fogStart, this._scene.fogEnd, this._scene.fogDensity);
  54345. effect.setColor3("vFogColor", this._scene.fogColor);
  54346. }
  54347. // VBOs
  54348. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, effect);
  54349. // Draw order
  54350. engine.setDepthFunctionToLessOrEqual();
  54351. effect.setBool("alphaTest", true);
  54352. engine.setColorWrite(false);
  54353. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, max * 6);
  54354. engine.setColorWrite(true);
  54355. effect.setBool("alphaTest", false);
  54356. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  54357. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, max * 6);
  54358. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  54359. };
  54360. SpriteManager.prototype.dispose = function () {
  54361. if (this._buffer) {
  54362. this._buffer.dispose();
  54363. this._buffer = null;
  54364. }
  54365. if (this._indexBuffer) {
  54366. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  54367. this._indexBuffer = null;
  54368. }
  54369. if (this._spriteTexture) {
  54370. this._spriteTexture.dispose();
  54371. this._spriteTexture = null;
  54372. }
  54373. // Remove from scene
  54374. var index = this._scene.spriteManagers.indexOf(this);
  54375. this._scene.spriteManagers.splice(index, 1);
  54376. // Callback
  54377. this.onDisposeObservable.notifyObservers(this);
  54378. this.onDisposeObservable.clear();
  54379. };
  54380. return SpriteManager;
  54381. }());
  54382. BABYLON.SpriteManager = SpriteManager;
  54383. })(BABYLON || (BABYLON = {}));
  54384. //# sourceMappingURL=babylon.spriteManager.js.map
  54385. var BABYLON;
  54386. (function (BABYLON) {
  54387. var Sprite = /** @class */ (function () {
  54388. function Sprite(name, manager) {
  54389. this.name = name;
  54390. this.color = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  54391. this.width = 1.0;
  54392. this.height = 1.0;
  54393. this.angle = 0;
  54394. this.cellIndex = 0;
  54395. this.invertU = 0;
  54396. this.invertV = 0;
  54397. this.animations = new Array();
  54398. this.isPickable = false;
  54399. this._animationStarted = false;
  54400. this._loopAnimation = false;
  54401. this._fromIndex = 0;
  54402. this._toIndex = 0;
  54403. this._delay = 0;
  54404. this._direction = 1;
  54405. this._time = 0;
  54406. this._manager = manager;
  54407. this._manager.sprites.push(this);
  54408. this.position = BABYLON.Vector3.Zero();
  54409. }
  54410. Object.defineProperty(Sprite.prototype, "size", {
  54411. get: function () {
  54412. return this.width;
  54413. },
  54414. set: function (value) {
  54415. this.width = value;
  54416. this.height = value;
  54417. },
  54418. enumerable: true,
  54419. configurable: true
  54420. });
  54421. Sprite.prototype.playAnimation = function (from, to, loop, delay, onAnimationEnd) {
  54422. this._fromIndex = from;
  54423. this._toIndex = to;
  54424. this._loopAnimation = loop;
  54425. this._delay = delay;
  54426. this._animationStarted = true;
  54427. this._direction = from < to ? 1 : -1;
  54428. this.cellIndex = from;
  54429. this._time = 0;
  54430. this._onAnimationEnd = onAnimationEnd;
  54431. };
  54432. Sprite.prototype.stopAnimation = function () {
  54433. this._animationStarted = false;
  54434. };
  54435. Sprite.prototype._animate = function (deltaTime) {
  54436. if (!this._animationStarted)
  54437. return;
  54438. this._time += deltaTime;
  54439. if (this._time > this._delay) {
  54440. this._time = this._time % this._delay;
  54441. this.cellIndex += this._direction;
  54442. if (this.cellIndex > this._toIndex) {
  54443. if (this._loopAnimation) {
  54444. this.cellIndex = this._fromIndex;
  54445. }
  54446. else {
  54447. this.cellIndex = this._toIndex;
  54448. this._animationStarted = false;
  54449. if (this._onAnimationEnd) {
  54450. this._onAnimationEnd();
  54451. }
  54452. if (this.disposeWhenFinishedAnimating) {
  54453. this.dispose();
  54454. }
  54455. }
  54456. }
  54457. }
  54458. };
  54459. Sprite.prototype.dispose = function () {
  54460. for (var i = 0; i < this._manager.sprites.length; i++) {
  54461. if (this._manager.sprites[i] == this) {
  54462. this._manager.sprites.splice(i, 1);
  54463. }
  54464. }
  54465. };
  54466. return Sprite;
  54467. }());
  54468. BABYLON.Sprite = Sprite;
  54469. })(BABYLON || (BABYLON = {}));
  54470. //# sourceMappingURL=babylon.sprite.js.map
  54471. var BABYLON;
  54472. (function (BABYLON) {
  54473. var IntersectionInfo = /** @class */ (function () {
  54474. function IntersectionInfo(bu, bv, distance) {
  54475. this.bu = bu;
  54476. this.bv = bv;
  54477. this.distance = distance;
  54478. this.faceId = 0;
  54479. this.subMeshId = 0;
  54480. }
  54481. return IntersectionInfo;
  54482. }());
  54483. BABYLON.IntersectionInfo = IntersectionInfo;
  54484. var PickingInfo = /** @class */ (function () {
  54485. function PickingInfo() {
  54486. this.hit = false;
  54487. this.distance = 0;
  54488. this.pickedPoint = null;
  54489. this.pickedMesh = null;
  54490. this.bu = 0;
  54491. this.bv = 0;
  54492. this.faceId = -1;
  54493. this.subMeshId = 0;
  54494. this.pickedSprite = null;
  54495. }
  54496. // Methods
  54497. PickingInfo.prototype.getNormal = function (useWorldCoordinates, useVerticesNormals) {
  54498. if (useWorldCoordinates === void 0) { useWorldCoordinates = false; }
  54499. if (useVerticesNormals === void 0) { useVerticesNormals = true; }
  54500. if (!this.pickedMesh || !this.pickedMesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  54501. return null;
  54502. }
  54503. var indices = this.pickedMesh.getIndices();
  54504. if (!indices) {
  54505. return null;
  54506. }
  54507. var result;
  54508. if (useVerticesNormals) {
  54509. var normals = this.pickedMesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  54510. var normal0 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3] * 3);
  54511. var normal1 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3 + 1] * 3);
  54512. var normal2 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3 + 2] * 3);
  54513. normal0 = normal0.scale(this.bu);
  54514. normal1 = normal1.scale(this.bv);
  54515. normal2 = normal2.scale(1.0 - this.bu - this.bv);
  54516. result = new BABYLON.Vector3(normal0.x + normal1.x + normal2.x, normal0.y + normal1.y + normal2.y, normal0.z + normal1.z + normal2.z);
  54517. }
  54518. else {
  54519. var positions = this.pickedMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  54520. var vertex1 = BABYLON.Vector3.FromArray(positions, indices[this.faceId * 3] * 3);
  54521. var vertex2 = BABYLON.Vector3.FromArray(positions, indices[this.faceId * 3 + 1] * 3);
  54522. var vertex3 = BABYLON.Vector3.FromArray(positions, indices[this.faceId * 3 + 2] * 3);
  54523. var p1p2 = vertex1.subtract(vertex2);
  54524. var p3p2 = vertex3.subtract(vertex2);
  54525. result = BABYLON.Vector3.Cross(p1p2, p3p2);
  54526. }
  54527. if (useWorldCoordinates) {
  54528. result = BABYLON.Vector3.TransformNormal(result, this.pickedMesh.getWorldMatrix());
  54529. }
  54530. return BABYLON.Vector3.Normalize(result);
  54531. };
  54532. PickingInfo.prototype.getTextureCoordinates = function () {
  54533. if (!this.pickedMesh || !this.pickedMesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  54534. return null;
  54535. }
  54536. var indices = this.pickedMesh.getIndices();
  54537. if (!indices) {
  54538. return null;
  54539. }
  54540. var uvs = this.pickedMesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  54541. if (!uvs) {
  54542. return null;
  54543. }
  54544. var uv0 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3] * 2);
  54545. var uv1 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3 + 1] * 2);
  54546. var uv2 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3 + 2] * 2);
  54547. uv0 = uv0.scale(1.0 - this.bu - this.bv);
  54548. uv1 = uv1.scale(this.bu);
  54549. uv2 = uv2.scale(this.bv);
  54550. return new BABYLON.Vector2(uv0.x + uv1.x + uv2.x, uv0.y + uv1.y + uv2.y);
  54551. };
  54552. return PickingInfo;
  54553. }());
  54554. BABYLON.PickingInfo = PickingInfo;
  54555. })(BABYLON || (BABYLON = {}));
  54556. //# sourceMappingURL=babylon.pickingInfo.js.map
  54557. var BABYLON;
  54558. (function (BABYLON) {
  54559. var Ray = /** @class */ (function () {
  54560. function Ray(origin, direction, length) {
  54561. if (length === void 0) { length = Number.MAX_VALUE; }
  54562. this.origin = origin;
  54563. this.direction = direction;
  54564. this.length = length;
  54565. }
  54566. // Methods
  54567. Ray.prototype.intersectsBoxMinMax = function (minimum, maximum) {
  54568. var d = 0.0;
  54569. var maxValue = Number.MAX_VALUE;
  54570. var inv;
  54571. var min;
  54572. var max;
  54573. var temp;
  54574. if (Math.abs(this.direction.x) < 0.0000001) {
  54575. if (this.origin.x < minimum.x || this.origin.x > maximum.x) {
  54576. return false;
  54577. }
  54578. }
  54579. else {
  54580. inv = 1.0 / this.direction.x;
  54581. min = (minimum.x - this.origin.x) * inv;
  54582. max = (maximum.x - this.origin.x) * inv;
  54583. if (max === -Infinity) {
  54584. max = Infinity;
  54585. }
  54586. if (min > max) {
  54587. temp = min;
  54588. min = max;
  54589. max = temp;
  54590. }
  54591. d = Math.max(min, d);
  54592. maxValue = Math.min(max, maxValue);
  54593. if (d > maxValue) {
  54594. return false;
  54595. }
  54596. }
  54597. if (Math.abs(this.direction.y) < 0.0000001) {
  54598. if (this.origin.y < minimum.y || this.origin.y > maximum.y) {
  54599. return false;
  54600. }
  54601. }
  54602. else {
  54603. inv = 1.0 / this.direction.y;
  54604. min = (minimum.y - this.origin.y) * inv;
  54605. max = (maximum.y - this.origin.y) * inv;
  54606. if (max === -Infinity) {
  54607. max = Infinity;
  54608. }
  54609. if (min > max) {
  54610. temp = min;
  54611. min = max;
  54612. max = temp;
  54613. }
  54614. d = Math.max(min, d);
  54615. maxValue = Math.min(max, maxValue);
  54616. if (d > maxValue) {
  54617. return false;
  54618. }
  54619. }
  54620. if (Math.abs(this.direction.z) < 0.0000001) {
  54621. if (this.origin.z < minimum.z || this.origin.z > maximum.z) {
  54622. return false;
  54623. }
  54624. }
  54625. else {
  54626. inv = 1.0 / this.direction.z;
  54627. min = (minimum.z - this.origin.z) * inv;
  54628. max = (maximum.z - this.origin.z) * inv;
  54629. if (max === -Infinity) {
  54630. max = Infinity;
  54631. }
  54632. if (min > max) {
  54633. temp = min;
  54634. min = max;
  54635. max = temp;
  54636. }
  54637. d = Math.max(min, d);
  54638. maxValue = Math.min(max, maxValue);
  54639. if (d > maxValue) {
  54640. return false;
  54641. }
  54642. }
  54643. return true;
  54644. };
  54645. Ray.prototype.intersectsBox = function (box) {
  54646. return this.intersectsBoxMinMax(box.minimum, box.maximum);
  54647. };
  54648. Ray.prototype.intersectsSphere = function (sphere) {
  54649. var x = sphere.center.x - this.origin.x;
  54650. var y = sphere.center.y - this.origin.y;
  54651. var z = sphere.center.z - this.origin.z;
  54652. var pyth = (x * x) + (y * y) + (z * z);
  54653. var rr = sphere.radius * sphere.radius;
  54654. if (pyth <= rr) {
  54655. return true;
  54656. }
  54657. var dot = (x * this.direction.x) + (y * this.direction.y) + (z * this.direction.z);
  54658. if (dot < 0.0) {
  54659. return false;
  54660. }
  54661. var temp = pyth - (dot * dot);
  54662. return temp <= rr;
  54663. };
  54664. Ray.prototype.intersectsTriangle = function (vertex0, vertex1, vertex2) {
  54665. if (!this._edge1) {
  54666. this._edge1 = BABYLON.Vector3.Zero();
  54667. this._edge2 = BABYLON.Vector3.Zero();
  54668. this._pvec = BABYLON.Vector3.Zero();
  54669. this._tvec = BABYLON.Vector3.Zero();
  54670. this._qvec = BABYLON.Vector3.Zero();
  54671. }
  54672. vertex1.subtractToRef(vertex0, this._edge1);
  54673. vertex2.subtractToRef(vertex0, this._edge2);
  54674. BABYLON.Vector3.CrossToRef(this.direction, this._edge2, this._pvec);
  54675. var det = BABYLON.Vector3.Dot(this._edge1, this._pvec);
  54676. if (det === 0) {
  54677. return null;
  54678. }
  54679. var invdet = 1 / det;
  54680. this.origin.subtractToRef(vertex0, this._tvec);
  54681. var bu = BABYLON.Vector3.Dot(this._tvec, this._pvec) * invdet;
  54682. if (bu < 0 || bu > 1.0) {
  54683. return null;
  54684. }
  54685. BABYLON.Vector3.CrossToRef(this._tvec, this._edge1, this._qvec);
  54686. var bv = BABYLON.Vector3.Dot(this.direction, this._qvec) * invdet;
  54687. if (bv < 0 || bu + bv > 1.0) {
  54688. return null;
  54689. }
  54690. //check if the distance is longer than the predefined length.
  54691. var distance = BABYLON.Vector3.Dot(this._edge2, this._qvec) * invdet;
  54692. if (distance > this.length) {
  54693. return null;
  54694. }
  54695. return new BABYLON.IntersectionInfo(bu, bv, distance);
  54696. };
  54697. Ray.prototype.intersectsPlane = function (plane) {
  54698. var distance;
  54699. var result1 = BABYLON.Vector3.Dot(plane.normal, this.direction);
  54700. if (Math.abs(result1) < 9.99999997475243E-07) {
  54701. return null;
  54702. }
  54703. else {
  54704. var result2 = BABYLON.Vector3.Dot(plane.normal, this.origin);
  54705. distance = (-plane.d - result2) / result1;
  54706. if (distance < 0.0) {
  54707. if (distance < -9.99999997475243E-07) {
  54708. return null;
  54709. }
  54710. else {
  54711. return 0;
  54712. }
  54713. }
  54714. return distance;
  54715. }
  54716. };
  54717. Ray.prototype.intersectsMesh = function (mesh, fastCheck) {
  54718. var tm = BABYLON.Tmp.Matrix[0];
  54719. mesh.getWorldMatrix().invertToRef(tm);
  54720. if (this._tmpRay) {
  54721. Ray.TransformToRef(this, tm, this._tmpRay);
  54722. }
  54723. else {
  54724. this._tmpRay = Ray.Transform(this, tm);
  54725. }
  54726. return mesh.intersects(this._tmpRay, fastCheck);
  54727. };
  54728. Ray.prototype.intersectsMeshes = function (meshes, fastCheck, results) {
  54729. if (results) {
  54730. results.length = 0;
  54731. }
  54732. else {
  54733. results = [];
  54734. }
  54735. for (var i = 0; i < meshes.length; i++) {
  54736. var pickInfo = this.intersectsMesh(meshes[i], fastCheck);
  54737. if (pickInfo.hit) {
  54738. results.push(pickInfo);
  54739. }
  54740. }
  54741. results.sort(this._comparePickingInfo);
  54742. return results;
  54743. };
  54744. Ray.prototype._comparePickingInfo = function (pickingInfoA, pickingInfoB) {
  54745. if (pickingInfoA.distance < pickingInfoB.distance) {
  54746. return -1;
  54747. }
  54748. else if (pickingInfoA.distance > pickingInfoB.distance) {
  54749. return 1;
  54750. }
  54751. else {
  54752. return 0;
  54753. }
  54754. };
  54755. /**
  54756. * Intersection test between the ray and a given segment whithin a given tolerance (threshold)
  54757. * @param sega the first point of the segment to test the intersection against
  54758. * @param segb the second point of the segment to test the intersection against
  54759. * @param threshold the tolerance margin, if the ray doesn't intersect the segment but is close to the given threshold, the intersection is successful
  54760. * @return the distance from the ray origin to the intersection point if there's intersection, or -1 if there's no intersection
  54761. */
  54762. Ray.prototype.intersectionSegment = function (sega, segb, threshold) {
  54763. var rsegb = this.origin.add(this.direction.multiplyByFloats(Ray.rayl, Ray.rayl, Ray.rayl));
  54764. var u = segb.subtract(sega);
  54765. var v = rsegb.subtract(this.origin);
  54766. var w = sega.subtract(this.origin);
  54767. var a = BABYLON.Vector3.Dot(u, u); // always >= 0
  54768. var b = BABYLON.Vector3.Dot(u, v);
  54769. var c = BABYLON.Vector3.Dot(v, v); // always >= 0
  54770. var d = BABYLON.Vector3.Dot(u, w);
  54771. var e = BABYLON.Vector3.Dot(v, w);
  54772. var D = a * c - b * b; // always >= 0
  54773. var sc, sN, sD = D; // sc = sN / sD, default sD = D >= 0
  54774. var tc, tN, tD = D; // tc = tN / tD, default tD = D >= 0
  54775. // compute the line parameters of the two closest points
  54776. if (D < Ray.smallnum) { // the lines are almost parallel
  54777. sN = 0.0; // force using point P0 on segment S1
  54778. sD = 1.0; // to prevent possible division by 0.0 later
  54779. tN = e;
  54780. tD = c;
  54781. }
  54782. else { // get the closest points on the infinite lines
  54783. sN = (b * e - c * d);
  54784. tN = (a * e - b * d);
  54785. if (sN < 0.0) { // sc < 0 => the s=0 edge is visible
  54786. sN = 0.0;
  54787. tN = e;
  54788. tD = c;
  54789. }
  54790. else if (sN > sD) { // sc > 1 => the s=1 edge is visible
  54791. sN = sD;
  54792. tN = e + b;
  54793. tD = c;
  54794. }
  54795. }
  54796. if (tN < 0.0) { // tc < 0 => the t=0 edge is visible
  54797. tN = 0.0;
  54798. // recompute sc for this edge
  54799. if (-d < 0.0) {
  54800. sN = 0.0;
  54801. }
  54802. else if (-d > a)
  54803. sN = sD;
  54804. else {
  54805. sN = -d;
  54806. sD = a;
  54807. }
  54808. }
  54809. else if (tN > tD) { // tc > 1 => the t=1 edge is visible
  54810. tN = tD;
  54811. // recompute sc for this edge
  54812. if ((-d + b) < 0.0) {
  54813. sN = 0;
  54814. }
  54815. else if ((-d + b) > a) {
  54816. sN = sD;
  54817. }
  54818. else {
  54819. sN = (-d + b);
  54820. sD = a;
  54821. }
  54822. }
  54823. // finally do the division to get sc and tc
  54824. sc = (Math.abs(sN) < Ray.smallnum ? 0.0 : sN / sD);
  54825. tc = (Math.abs(tN) < Ray.smallnum ? 0.0 : tN / tD);
  54826. // get the difference of the two closest points
  54827. var qtc = v.multiplyByFloats(tc, tc, tc);
  54828. var dP = w.add(u.multiplyByFloats(sc, sc, sc)).subtract(qtc); // = S1(sc) - S2(tc)
  54829. var isIntersected = (tc > 0) && (tc <= this.length) && (dP.lengthSquared() < (threshold * threshold)); // return intersection result
  54830. if (isIntersected) {
  54831. return qtc.length();
  54832. }
  54833. return -1;
  54834. };
  54835. Ray.prototype.update = function (x, y, viewportWidth, viewportHeight, world, view, projection) {
  54836. BABYLON.Vector3.UnprojectFloatsToRef(x, y, 0, viewportWidth, viewportHeight, world, view, projection, this.origin);
  54837. BABYLON.Vector3.UnprojectFloatsToRef(x, y, 1, viewportWidth, viewportHeight, world, view, projection, BABYLON.Tmp.Vector3[0]);
  54838. BABYLON.Tmp.Vector3[0].subtractToRef(this.origin, this.direction);
  54839. this.direction.normalize();
  54840. return this;
  54841. };
  54842. // Statics
  54843. Ray.Zero = function () {
  54844. return new Ray(BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero());
  54845. };
  54846. Ray.CreateNew = function (x, y, viewportWidth, viewportHeight, world, view, projection) {
  54847. var result = Ray.Zero();
  54848. return result.update(x, y, viewportWidth, viewportHeight, world, view, projection);
  54849. };
  54850. /**
  54851. * 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
  54852. * transformed to the given world matrix.
  54853. * @param origin The origin point
  54854. * @param end The end point
  54855. * @param world a matrix to transform the ray to. Default is the identity matrix.
  54856. */
  54857. Ray.CreateNewFromTo = function (origin, end, world) {
  54858. if (world === void 0) { world = BABYLON.Matrix.Identity(); }
  54859. var direction = end.subtract(origin);
  54860. var length = Math.sqrt((direction.x * direction.x) + (direction.y * direction.y) + (direction.z * direction.z));
  54861. direction.normalize();
  54862. return Ray.Transform(new Ray(origin, direction, length), world);
  54863. };
  54864. Ray.Transform = function (ray, matrix) {
  54865. var result = new Ray(new BABYLON.Vector3(0, 0, 0), new BABYLON.Vector3(0, 0, 0));
  54866. Ray.TransformToRef(ray, matrix, result);
  54867. return result;
  54868. };
  54869. Ray.TransformToRef = function (ray, matrix, result) {
  54870. BABYLON.Vector3.TransformCoordinatesToRef(ray.origin, matrix, result.origin);
  54871. BABYLON.Vector3.TransformNormalToRef(ray.direction, matrix, result.direction);
  54872. result.length = ray.length;
  54873. var dir = result.direction;
  54874. var len = dir.length();
  54875. if (!(len === 0 || len === 1)) {
  54876. var num = 1.0 / len;
  54877. dir.x *= num;
  54878. dir.y *= num;
  54879. dir.z *= num;
  54880. result.length *= len;
  54881. }
  54882. };
  54883. Ray.smallnum = 0.00000001;
  54884. Ray.rayl = 10e8;
  54885. return Ray;
  54886. }());
  54887. BABYLON.Ray = Ray;
  54888. })(BABYLON || (BABYLON = {}));
  54889. //# sourceMappingURL=babylon.ray.js.map
  54890. var BABYLON;
  54891. (function (BABYLON) {
  54892. var intersectBoxAASphere = function (boxMin, boxMax, sphereCenter, sphereRadius) {
  54893. if (boxMin.x > sphereCenter.x + sphereRadius)
  54894. return false;
  54895. if (sphereCenter.x - sphereRadius > boxMax.x)
  54896. return false;
  54897. if (boxMin.y > sphereCenter.y + sphereRadius)
  54898. return false;
  54899. if (sphereCenter.y - sphereRadius > boxMax.y)
  54900. return false;
  54901. if (boxMin.z > sphereCenter.z + sphereRadius)
  54902. return false;
  54903. if (sphereCenter.z - sphereRadius > boxMax.z)
  54904. return false;
  54905. return true;
  54906. };
  54907. var getLowestRoot = (function () {
  54908. var result = { root: 0, found: false };
  54909. return function (a, b, c, maxR) {
  54910. result.root = 0;
  54911. result.found = false;
  54912. var determinant = b * b - 4.0 * a * c;
  54913. if (determinant < 0)
  54914. return result;
  54915. var sqrtD = Math.sqrt(determinant);
  54916. var r1 = (-b - sqrtD) / (2.0 * a);
  54917. var r2 = (-b + sqrtD) / (2.0 * a);
  54918. if (r1 > r2) {
  54919. var temp = r2;
  54920. r2 = r1;
  54921. r1 = temp;
  54922. }
  54923. if (r1 > 0 && r1 < maxR) {
  54924. result.root = r1;
  54925. result.found = true;
  54926. return result;
  54927. }
  54928. if (r2 > 0 && r2 < maxR) {
  54929. result.root = r2;
  54930. result.found = true;
  54931. return result;
  54932. }
  54933. return result;
  54934. };
  54935. })();
  54936. var Collider = /** @class */ (function () {
  54937. function Collider() {
  54938. this._collisionPoint = BABYLON.Vector3.Zero();
  54939. this._planeIntersectionPoint = BABYLON.Vector3.Zero();
  54940. this._tempVector = BABYLON.Vector3.Zero();
  54941. this._tempVector2 = BABYLON.Vector3.Zero();
  54942. this._tempVector3 = BABYLON.Vector3.Zero();
  54943. this._tempVector4 = BABYLON.Vector3.Zero();
  54944. this._edge = BABYLON.Vector3.Zero();
  54945. this._baseToVertex = BABYLON.Vector3.Zero();
  54946. this._destinationPoint = BABYLON.Vector3.Zero();
  54947. this._slidePlaneNormal = BABYLON.Vector3.Zero();
  54948. this._displacementVector = BABYLON.Vector3.Zero();
  54949. this._radius = BABYLON.Vector3.One();
  54950. this._retry = 0;
  54951. this._basePointWorld = BABYLON.Vector3.Zero();
  54952. this._velocityWorld = BABYLON.Vector3.Zero();
  54953. this._normalizedVelocity = BABYLON.Vector3.Zero();
  54954. this._collisionMask = -1;
  54955. }
  54956. Object.defineProperty(Collider.prototype, "collisionMask", {
  54957. get: function () {
  54958. return this._collisionMask;
  54959. },
  54960. set: function (mask) {
  54961. this._collisionMask = !isNaN(mask) ? mask : -1;
  54962. },
  54963. enumerable: true,
  54964. configurable: true
  54965. });
  54966. Object.defineProperty(Collider.prototype, "slidePlaneNormal", {
  54967. /**
  54968. * Gets the plane normal used to compute the sliding response (in local space)
  54969. */
  54970. get: function () {
  54971. return this._slidePlaneNormal;
  54972. },
  54973. enumerable: true,
  54974. configurable: true
  54975. });
  54976. // Methods
  54977. Collider.prototype._initialize = function (source, dir, e) {
  54978. this._velocity = dir;
  54979. BABYLON.Vector3.NormalizeToRef(dir, this._normalizedVelocity);
  54980. this._basePoint = source;
  54981. source.multiplyToRef(this._radius, this._basePointWorld);
  54982. dir.multiplyToRef(this._radius, this._velocityWorld);
  54983. this._velocityWorldLength = this._velocityWorld.length();
  54984. this._epsilon = e;
  54985. this.collisionFound = false;
  54986. };
  54987. Collider.prototype._checkPointInTriangle = function (point, pa, pb, pc, n) {
  54988. pa.subtractToRef(point, this._tempVector);
  54989. pb.subtractToRef(point, this._tempVector2);
  54990. BABYLON.Vector3.CrossToRef(this._tempVector, this._tempVector2, this._tempVector4);
  54991. var d = BABYLON.Vector3.Dot(this._tempVector4, n);
  54992. if (d < 0)
  54993. return false;
  54994. pc.subtractToRef(point, this._tempVector3);
  54995. BABYLON.Vector3.CrossToRef(this._tempVector2, this._tempVector3, this._tempVector4);
  54996. d = BABYLON.Vector3.Dot(this._tempVector4, n);
  54997. if (d < 0)
  54998. return false;
  54999. BABYLON.Vector3.CrossToRef(this._tempVector3, this._tempVector, this._tempVector4);
  55000. d = BABYLON.Vector3.Dot(this._tempVector4, n);
  55001. return d >= 0;
  55002. };
  55003. Collider.prototype._canDoCollision = function (sphereCenter, sphereRadius, vecMin, vecMax) {
  55004. var distance = BABYLON.Vector3.Distance(this._basePointWorld, sphereCenter);
  55005. var max = Math.max(this._radius.x, this._radius.y, this._radius.z);
  55006. if (distance > this._velocityWorldLength + max + sphereRadius) {
  55007. return false;
  55008. }
  55009. if (!intersectBoxAASphere(vecMin, vecMax, this._basePointWorld, this._velocityWorldLength + max))
  55010. return false;
  55011. return true;
  55012. };
  55013. Collider.prototype._testTriangle = function (faceIndex, trianglePlaneArray, p1, p2, p3, hasMaterial) {
  55014. var t0;
  55015. var embeddedInPlane = false;
  55016. //defensive programming, actually not needed.
  55017. if (!trianglePlaneArray) {
  55018. trianglePlaneArray = [];
  55019. }
  55020. if (!trianglePlaneArray[faceIndex]) {
  55021. trianglePlaneArray[faceIndex] = new BABYLON.Plane(0, 0, 0, 0);
  55022. trianglePlaneArray[faceIndex].copyFromPoints(p1, p2, p3);
  55023. }
  55024. var trianglePlane = trianglePlaneArray[faceIndex];
  55025. if ((!hasMaterial) && !trianglePlane.isFrontFacingTo(this._normalizedVelocity, 0))
  55026. return;
  55027. var signedDistToTrianglePlane = trianglePlane.signedDistanceTo(this._basePoint);
  55028. var normalDotVelocity = BABYLON.Vector3.Dot(trianglePlane.normal, this._velocity);
  55029. if (normalDotVelocity == 0) {
  55030. if (Math.abs(signedDistToTrianglePlane) >= 1.0)
  55031. return;
  55032. embeddedInPlane = true;
  55033. t0 = 0;
  55034. }
  55035. else {
  55036. t0 = (-1.0 - signedDistToTrianglePlane) / normalDotVelocity;
  55037. var t1 = (1.0 - signedDistToTrianglePlane) / normalDotVelocity;
  55038. if (t0 > t1) {
  55039. var temp = t1;
  55040. t1 = t0;
  55041. t0 = temp;
  55042. }
  55043. if (t0 > 1.0 || t1 < 0.0)
  55044. return;
  55045. if (t0 < 0)
  55046. t0 = 0;
  55047. if (t0 > 1.0)
  55048. t0 = 1.0;
  55049. }
  55050. this._collisionPoint.copyFromFloats(0, 0, 0);
  55051. var found = false;
  55052. var t = 1.0;
  55053. if (!embeddedInPlane) {
  55054. this._basePoint.subtractToRef(trianglePlane.normal, this._planeIntersectionPoint);
  55055. this._velocity.scaleToRef(t0, this._tempVector);
  55056. this._planeIntersectionPoint.addInPlace(this._tempVector);
  55057. if (this._checkPointInTriangle(this._planeIntersectionPoint, p1, p2, p3, trianglePlane.normal)) {
  55058. found = true;
  55059. t = t0;
  55060. this._collisionPoint.copyFrom(this._planeIntersectionPoint);
  55061. }
  55062. }
  55063. if (!found) {
  55064. var velocitySquaredLength = this._velocity.lengthSquared();
  55065. var a = velocitySquaredLength;
  55066. this._basePoint.subtractToRef(p1, this._tempVector);
  55067. var b = 2.0 * (BABYLON.Vector3.Dot(this._velocity, this._tempVector));
  55068. var c = this._tempVector.lengthSquared() - 1.0;
  55069. var lowestRoot = getLowestRoot(a, b, c, t);
  55070. if (lowestRoot.found) {
  55071. t = lowestRoot.root;
  55072. found = true;
  55073. this._collisionPoint.copyFrom(p1);
  55074. }
  55075. this._basePoint.subtractToRef(p2, this._tempVector);
  55076. b = 2.0 * (BABYLON.Vector3.Dot(this._velocity, this._tempVector));
  55077. c = this._tempVector.lengthSquared() - 1.0;
  55078. lowestRoot = getLowestRoot(a, b, c, t);
  55079. if (lowestRoot.found) {
  55080. t = lowestRoot.root;
  55081. found = true;
  55082. this._collisionPoint.copyFrom(p2);
  55083. }
  55084. this._basePoint.subtractToRef(p3, this._tempVector);
  55085. b = 2.0 * (BABYLON.Vector3.Dot(this._velocity, this._tempVector));
  55086. c = this._tempVector.lengthSquared() - 1.0;
  55087. lowestRoot = getLowestRoot(a, b, c, t);
  55088. if (lowestRoot.found) {
  55089. t = lowestRoot.root;
  55090. found = true;
  55091. this._collisionPoint.copyFrom(p3);
  55092. }
  55093. p2.subtractToRef(p1, this._edge);
  55094. p1.subtractToRef(this._basePoint, this._baseToVertex);
  55095. var edgeSquaredLength = this._edge.lengthSquared();
  55096. var edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this._velocity);
  55097. var edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
  55098. a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
  55099. b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this._velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
  55100. c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
  55101. lowestRoot = getLowestRoot(a, b, c, t);
  55102. if (lowestRoot.found) {
  55103. var f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
  55104. if (f >= 0.0 && f <= 1.0) {
  55105. t = lowestRoot.root;
  55106. found = true;
  55107. this._edge.scaleInPlace(f);
  55108. p1.addToRef(this._edge, this._collisionPoint);
  55109. }
  55110. }
  55111. p3.subtractToRef(p2, this._edge);
  55112. p2.subtractToRef(this._basePoint, this._baseToVertex);
  55113. edgeSquaredLength = this._edge.lengthSquared();
  55114. edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this._velocity);
  55115. edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
  55116. a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
  55117. b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this._velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
  55118. c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
  55119. lowestRoot = getLowestRoot(a, b, c, t);
  55120. if (lowestRoot.found) {
  55121. f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
  55122. if (f >= 0.0 && f <= 1.0) {
  55123. t = lowestRoot.root;
  55124. found = true;
  55125. this._edge.scaleInPlace(f);
  55126. p2.addToRef(this._edge, this._collisionPoint);
  55127. }
  55128. }
  55129. p1.subtractToRef(p3, this._edge);
  55130. p3.subtractToRef(this._basePoint, this._baseToVertex);
  55131. edgeSquaredLength = this._edge.lengthSquared();
  55132. edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this._velocity);
  55133. edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
  55134. a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
  55135. b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this._velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
  55136. c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
  55137. lowestRoot = getLowestRoot(a, b, c, t);
  55138. if (lowestRoot.found) {
  55139. f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
  55140. if (f >= 0.0 && f <= 1.0) {
  55141. t = lowestRoot.root;
  55142. found = true;
  55143. this._edge.scaleInPlace(f);
  55144. p3.addToRef(this._edge, this._collisionPoint);
  55145. }
  55146. }
  55147. }
  55148. if (found) {
  55149. var distToCollision = t * this._velocity.length();
  55150. if (!this.collisionFound || distToCollision < this._nearestDistance) {
  55151. if (!this.intersectionPoint) {
  55152. this.intersectionPoint = this._collisionPoint.clone();
  55153. }
  55154. else {
  55155. this.intersectionPoint.copyFrom(this._collisionPoint);
  55156. }
  55157. this._nearestDistance = distToCollision;
  55158. this.collisionFound = true;
  55159. }
  55160. }
  55161. };
  55162. Collider.prototype._collide = function (trianglePlaneArray, pts, indices, indexStart, indexEnd, decal, hasMaterial) {
  55163. for (var i = indexStart; i < indexEnd; i += 3) {
  55164. var p1 = pts[indices[i] - decal];
  55165. var p2 = pts[indices[i + 1] - decal];
  55166. var p3 = pts[indices[i + 2] - decal];
  55167. this._testTriangle(i, trianglePlaneArray, p3, p2, p1, hasMaterial);
  55168. }
  55169. };
  55170. Collider.prototype._getResponse = function (pos, vel) {
  55171. pos.addToRef(vel, this._destinationPoint);
  55172. vel.scaleInPlace((this._nearestDistance / vel.length()));
  55173. this._basePoint.addToRef(vel, pos);
  55174. pos.subtractToRef(this.intersectionPoint, this._slidePlaneNormal);
  55175. this._slidePlaneNormal.normalize();
  55176. this._slidePlaneNormal.scaleToRef(this._epsilon, this._displacementVector);
  55177. pos.addInPlace(this._displacementVector);
  55178. this.intersectionPoint.addInPlace(this._displacementVector);
  55179. this._slidePlaneNormal.scaleInPlace(BABYLON.Plane.SignedDistanceToPlaneFromPositionAndNormal(this.intersectionPoint, this._slidePlaneNormal, this._destinationPoint));
  55180. this._destinationPoint.subtractInPlace(this._slidePlaneNormal);
  55181. this._destinationPoint.subtractToRef(this.intersectionPoint, vel);
  55182. };
  55183. return Collider;
  55184. }());
  55185. BABYLON.Collider = Collider;
  55186. })(BABYLON || (BABYLON = {}));
  55187. //# sourceMappingURL=babylon.collider.js.map
  55188. var BABYLON;
  55189. (function (BABYLON) {
  55190. //WebWorker code will be inserted to this variable.
  55191. BABYLON.CollisionWorker = "";
  55192. /** Defines supported task for worker process */
  55193. var WorkerTaskType;
  55194. (function (WorkerTaskType) {
  55195. /** Initialization */
  55196. WorkerTaskType[WorkerTaskType["INIT"] = 0] = "INIT";
  55197. /** Update of geometry */
  55198. WorkerTaskType[WorkerTaskType["UPDATE"] = 1] = "UPDATE";
  55199. /** Evaluate collision */
  55200. WorkerTaskType[WorkerTaskType["COLLIDE"] = 2] = "COLLIDE";
  55201. })(WorkerTaskType = BABYLON.WorkerTaskType || (BABYLON.WorkerTaskType = {}));
  55202. /** Defines kind of replies returned by worker */
  55203. var WorkerReplyType;
  55204. (function (WorkerReplyType) {
  55205. /** Success */
  55206. WorkerReplyType[WorkerReplyType["SUCCESS"] = 0] = "SUCCESS";
  55207. /** Unkown error */
  55208. WorkerReplyType[WorkerReplyType["UNKNOWN_ERROR"] = 1] = "UNKNOWN_ERROR";
  55209. })(WorkerReplyType = BABYLON.WorkerReplyType || (BABYLON.WorkerReplyType = {}));
  55210. var CollisionCoordinatorWorker = /** @class */ (function () {
  55211. function CollisionCoordinatorWorker() {
  55212. var _this = this;
  55213. this._scaledPosition = BABYLON.Vector3.Zero();
  55214. this._scaledVelocity = BABYLON.Vector3.Zero();
  55215. this.onMeshUpdated = function (transformNode) {
  55216. _this._addUpdateMeshesList[transformNode.uniqueId] = CollisionCoordinatorWorker.SerializeMesh(transformNode);
  55217. };
  55218. this.onGeometryUpdated = function (geometry) {
  55219. _this._addUpdateGeometriesList[geometry.id] = CollisionCoordinatorWorker.SerializeGeometry(geometry);
  55220. };
  55221. this._afterRender = function () {
  55222. if (!_this._init)
  55223. return;
  55224. if (_this._toRemoveGeometryArray.length == 0 && _this._toRemoveMeshesArray.length == 0 && Object.keys(_this._addUpdateGeometriesList).length == 0 && Object.keys(_this._addUpdateMeshesList).length == 0) {
  55225. return;
  55226. }
  55227. //5 concurrent updates were sent to the web worker and were not yet processed. Abort next update.
  55228. //TODO make sure update runs as fast as possible to be able to update 60 FPS.
  55229. if (_this._runningUpdated > 4) {
  55230. return;
  55231. }
  55232. ++_this._runningUpdated;
  55233. var payload = {
  55234. updatedMeshes: _this._addUpdateMeshesList,
  55235. updatedGeometries: _this._addUpdateGeometriesList,
  55236. removedGeometries: _this._toRemoveGeometryArray,
  55237. removedMeshes: _this._toRemoveMeshesArray
  55238. };
  55239. var message = {
  55240. payload: payload,
  55241. taskType: WorkerTaskType.UPDATE
  55242. };
  55243. var serializable = [];
  55244. for (var id in payload.updatedGeometries) {
  55245. if (payload.updatedGeometries.hasOwnProperty(id)) {
  55246. //prepare transferables
  55247. serializable.push(message.payload.updatedGeometries[id].indices.buffer);
  55248. serializable.push(message.payload.updatedGeometries[id].normals.buffer);
  55249. serializable.push(message.payload.updatedGeometries[id].positions.buffer);
  55250. }
  55251. }
  55252. _this._worker.postMessage(message, serializable);
  55253. _this._addUpdateMeshesList = {};
  55254. _this._addUpdateGeometriesList = {};
  55255. _this._toRemoveGeometryArray = [];
  55256. _this._toRemoveMeshesArray = [];
  55257. };
  55258. this._onMessageFromWorker = function (e) {
  55259. var returnData = e.data;
  55260. if (returnData.error != WorkerReplyType.SUCCESS) {
  55261. //TODO what errors can be returned from the worker?
  55262. BABYLON.Tools.Warn("error returned from worker!");
  55263. return;
  55264. }
  55265. switch (returnData.taskType) {
  55266. case WorkerTaskType.INIT:
  55267. _this._init = true;
  55268. //Update the worked with ALL of the scene's current state
  55269. _this._scene.meshes.forEach(function (mesh) {
  55270. _this.onMeshAdded(mesh);
  55271. });
  55272. _this._scene.getGeometries().forEach(function (geometry) {
  55273. _this.onGeometryAdded(geometry);
  55274. });
  55275. break;
  55276. case WorkerTaskType.UPDATE:
  55277. _this._runningUpdated--;
  55278. break;
  55279. case WorkerTaskType.COLLIDE:
  55280. var returnPayload = returnData.payload;
  55281. if (!_this._collisionsCallbackArray[returnPayload.collisionId])
  55282. return;
  55283. var callback = _this._collisionsCallbackArray[returnPayload.collisionId];
  55284. if (callback) {
  55285. var mesh = _this._scene.getMeshByUniqueID(returnPayload.collidedMeshUniqueId);
  55286. if (mesh) {
  55287. callback(returnPayload.collisionId, BABYLON.Vector3.FromArray(returnPayload.newPosition), mesh);
  55288. }
  55289. }
  55290. //cleanup
  55291. _this._collisionsCallbackArray[returnPayload.collisionId] = null;
  55292. break;
  55293. }
  55294. };
  55295. this._collisionsCallbackArray = [];
  55296. this._init = false;
  55297. this._runningUpdated = 0;
  55298. this._addUpdateMeshesList = {};
  55299. this._addUpdateGeometriesList = {};
  55300. this._toRemoveGeometryArray = [];
  55301. this._toRemoveMeshesArray = [];
  55302. }
  55303. CollisionCoordinatorWorker.prototype.getNewPosition = function (position, displacement, collider, maximumRetry, excludedMesh, onNewPosition, collisionIndex) {
  55304. if (!this._init)
  55305. return;
  55306. if (this._collisionsCallbackArray[collisionIndex] || this._collisionsCallbackArray[collisionIndex + 100000])
  55307. return;
  55308. position.divideToRef(collider._radius, this._scaledPosition);
  55309. displacement.divideToRef(collider._radius, this._scaledVelocity);
  55310. this._collisionsCallbackArray[collisionIndex] = onNewPosition;
  55311. var payload = {
  55312. collider: {
  55313. position: this._scaledPosition.asArray(),
  55314. velocity: this._scaledVelocity.asArray(),
  55315. radius: collider._radius.asArray()
  55316. },
  55317. collisionId: collisionIndex,
  55318. excludedMeshUniqueId: excludedMesh ? excludedMesh.uniqueId : null,
  55319. maximumRetry: maximumRetry
  55320. };
  55321. var message = {
  55322. payload: payload,
  55323. taskType: WorkerTaskType.COLLIDE
  55324. };
  55325. this._worker.postMessage(message);
  55326. };
  55327. CollisionCoordinatorWorker.prototype.init = function (scene) {
  55328. this._scene = scene;
  55329. this._scene.registerAfterRender(this._afterRender);
  55330. var workerUrl = BABYLON.WorkerIncluded ? BABYLON.Engine.CodeRepository + "Collisions/babylon.collisionWorker.js" : URL.createObjectURL(new Blob([BABYLON.CollisionWorker], { type: 'application/javascript' }));
  55331. this._worker = new Worker(workerUrl);
  55332. this._worker.onmessage = this._onMessageFromWorker;
  55333. var message = {
  55334. payload: {},
  55335. taskType: WorkerTaskType.INIT
  55336. };
  55337. this._worker.postMessage(message);
  55338. };
  55339. CollisionCoordinatorWorker.prototype.destroy = function () {
  55340. this._scene.unregisterAfterRender(this._afterRender);
  55341. this._worker.terminate();
  55342. };
  55343. CollisionCoordinatorWorker.prototype.onMeshAdded = function (mesh) {
  55344. mesh.registerAfterWorldMatrixUpdate(this.onMeshUpdated);
  55345. this.onMeshUpdated(mesh);
  55346. };
  55347. CollisionCoordinatorWorker.prototype.onMeshRemoved = function (mesh) {
  55348. this._toRemoveMeshesArray.push(mesh.uniqueId);
  55349. };
  55350. CollisionCoordinatorWorker.prototype.onGeometryAdded = function (geometry) {
  55351. //TODO this will break if the user uses his own function. This should be an array of callbacks!
  55352. geometry.onGeometryUpdated = this.onGeometryUpdated;
  55353. this.onGeometryUpdated(geometry);
  55354. };
  55355. CollisionCoordinatorWorker.prototype.onGeometryDeleted = function (geometry) {
  55356. this._toRemoveGeometryArray.push(geometry.id);
  55357. };
  55358. CollisionCoordinatorWorker.SerializeMesh = function (mesh) {
  55359. var submeshes = [];
  55360. if (mesh.subMeshes) {
  55361. submeshes = mesh.subMeshes.map(function (sm, idx) {
  55362. var boundingInfo = sm.getBoundingInfo();
  55363. return {
  55364. position: idx,
  55365. verticesStart: sm.verticesStart,
  55366. verticesCount: sm.verticesCount,
  55367. indexStart: sm.indexStart,
  55368. indexCount: sm.indexCount,
  55369. hasMaterial: !!sm.getMaterial(),
  55370. sphereCenter: boundingInfo.boundingSphere.centerWorld.asArray(),
  55371. sphereRadius: boundingInfo.boundingSphere.radiusWorld,
  55372. boxMinimum: boundingInfo.boundingBox.minimumWorld.asArray(),
  55373. boxMaximum: boundingInfo.boundingBox.maximumWorld.asArray()
  55374. };
  55375. });
  55376. }
  55377. var geometryId = null;
  55378. if (mesh instanceof BABYLON.Mesh) {
  55379. var geometry = mesh.geometry;
  55380. geometryId = geometry ? geometry.id : null;
  55381. }
  55382. else if (mesh instanceof BABYLON.InstancedMesh) {
  55383. var geometry = mesh.sourceMesh && mesh.sourceMesh.geometry;
  55384. geometryId = geometry ? geometry.id : null;
  55385. }
  55386. var boundingInfo = mesh.getBoundingInfo();
  55387. return {
  55388. uniqueId: mesh.uniqueId,
  55389. id: mesh.id,
  55390. name: mesh.name,
  55391. geometryId: geometryId,
  55392. sphereCenter: boundingInfo.boundingSphere.centerWorld.asArray(),
  55393. sphereRadius: boundingInfo.boundingSphere.radiusWorld,
  55394. boxMinimum: boundingInfo.boundingBox.minimumWorld.asArray(),
  55395. boxMaximum: boundingInfo.boundingBox.maximumWorld.asArray(),
  55396. worldMatrixFromCache: mesh.worldMatrixFromCache.asArray(),
  55397. subMeshes: submeshes,
  55398. checkCollisions: mesh.checkCollisions
  55399. };
  55400. };
  55401. CollisionCoordinatorWorker.SerializeGeometry = function (geometry) {
  55402. return {
  55403. id: geometry.id,
  55404. positions: new Float32Array(geometry.getVerticesData(BABYLON.VertexBuffer.PositionKind) || []),
  55405. normals: new Float32Array(geometry.getVerticesData(BABYLON.VertexBuffer.NormalKind) || []),
  55406. indices: new Uint32Array(geometry.getIndices() || []),
  55407. };
  55408. };
  55409. return CollisionCoordinatorWorker;
  55410. }());
  55411. BABYLON.CollisionCoordinatorWorker = CollisionCoordinatorWorker;
  55412. var CollisionCoordinatorLegacy = /** @class */ (function () {
  55413. function CollisionCoordinatorLegacy() {
  55414. this._scaledPosition = BABYLON.Vector3.Zero();
  55415. this._scaledVelocity = BABYLON.Vector3.Zero();
  55416. this._finalPosition = BABYLON.Vector3.Zero();
  55417. }
  55418. CollisionCoordinatorLegacy.prototype.getNewPosition = function (position, displacement, collider, maximumRetry, excludedMesh, onNewPosition, collisionIndex) {
  55419. position.divideToRef(collider._radius, this._scaledPosition);
  55420. displacement.divideToRef(collider._radius, this._scaledVelocity);
  55421. collider.collidedMesh = null;
  55422. collider._retry = 0;
  55423. collider._initialVelocity = this._scaledVelocity;
  55424. collider._initialPosition = this._scaledPosition;
  55425. this._collideWithWorld(this._scaledPosition, this._scaledVelocity, collider, maximumRetry, this._finalPosition, excludedMesh);
  55426. this._finalPosition.multiplyInPlace(collider._radius);
  55427. //run the callback
  55428. onNewPosition(collisionIndex, this._finalPosition, collider.collidedMesh);
  55429. };
  55430. CollisionCoordinatorLegacy.prototype.init = function (scene) {
  55431. this._scene = scene;
  55432. };
  55433. CollisionCoordinatorLegacy.prototype.destroy = function () {
  55434. //Legacy need no destruction method.
  55435. };
  55436. //No update in legacy mode
  55437. CollisionCoordinatorLegacy.prototype.onMeshAdded = function (mesh) { };
  55438. CollisionCoordinatorLegacy.prototype.onMeshUpdated = function (mesh) { };
  55439. CollisionCoordinatorLegacy.prototype.onMeshRemoved = function (mesh) { };
  55440. CollisionCoordinatorLegacy.prototype.onGeometryAdded = function (geometry) { };
  55441. CollisionCoordinatorLegacy.prototype.onGeometryUpdated = function (geometry) { };
  55442. CollisionCoordinatorLegacy.prototype.onGeometryDeleted = function (geometry) { };
  55443. CollisionCoordinatorLegacy.prototype._collideWithWorld = function (position, velocity, collider, maximumRetry, finalPosition, excludedMesh) {
  55444. if (excludedMesh === void 0) { excludedMesh = null; }
  55445. var closeDistance = BABYLON.Engine.CollisionsEpsilon * 10.0;
  55446. if (collider._retry >= maximumRetry) {
  55447. finalPosition.copyFrom(position);
  55448. return;
  55449. }
  55450. // Check if this is a mesh else camera or -1
  55451. var collisionMask = (excludedMesh ? excludedMesh.collisionMask : collider.collisionMask);
  55452. collider._initialize(position, velocity, closeDistance);
  55453. // Check all meshes
  55454. for (var index = 0; index < this._scene.meshes.length; index++) {
  55455. var mesh = this._scene.meshes[index];
  55456. if (mesh.isEnabled() && mesh.checkCollisions && mesh.subMeshes && mesh !== excludedMesh && ((collisionMask & mesh.collisionGroup) !== 0)) {
  55457. mesh._checkCollision(collider);
  55458. }
  55459. }
  55460. if (!collider.collisionFound) {
  55461. position.addToRef(velocity, finalPosition);
  55462. return;
  55463. }
  55464. if (velocity.x !== 0 || velocity.y !== 0 || velocity.z !== 0) {
  55465. collider._getResponse(position, velocity);
  55466. }
  55467. if (velocity.length() <= closeDistance) {
  55468. finalPosition.copyFrom(position);
  55469. return;
  55470. }
  55471. collider._retry++;
  55472. this._collideWithWorld(position, velocity, collider, maximumRetry, finalPosition, excludedMesh);
  55473. };
  55474. return CollisionCoordinatorLegacy;
  55475. }());
  55476. BABYLON.CollisionCoordinatorLegacy = CollisionCoordinatorLegacy;
  55477. })(BABYLON || (BABYLON = {}));
  55478. //# sourceMappingURL=babylon.collisionCoordinator.js.map
  55479. var BABYLON;
  55480. (function (BABYLON) {
  55481. /**
  55482. * A particle represents one of the element emitted by a particle system.
  55483. * This is mainly define by its coordinates, direction, velocity and age.
  55484. */
  55485. var Particle = /** @class */ (function () {
  55486. /**
  55487. * Creates a new instance Particle
  55488. * @param particleSystem the particle system the particle belongs to
  55489. */
  55490. function Particle(
  55491. /**
  55492. * particleSystem the particle system the particle belongs to.
  55493. */
  55494. particleSystem) {
  55495. this.particleSystem = particleSystem;
  55496. /**
  55497. * The world position of the particle in the scene.
  55498. */
  55499. this.position = BABYLON.Vector3.Zero();
  55500. /**
  55501. * The world direction of the particle in the scene.
  55502. */
  55503. this.direction = BABYLON.Vector3.Zero();
  55504. /**
  55505. * The color of the particle.
  55506. */
  55507. this.color = new BABYLON.Color4(0, 0, 0, 0);
  55508. /**
  55509. * The color change of the particle per step.
  55510. */
  55511. this.colorStep = new BABYLON.Color4(0, 0, 0, 0);
  55512. /**
  55513. * Defines how long will the life of the particle be.
  55514. */
  55515. this.lifeTime = 1.0;
  55516. /**
  55517. * The current age of the particle.
  55518. */
  55519. this.age = 0;
  55520. /**
  55521. * The current size of the particle.
  55522. */
  55523. this.size = 0;
  55524. /**
  55525. * The current angle of the particle.
  55526. */
  55527. this.angle = 0;
  55528. /**
  55529. * Defines how fast is the angle changing.
  55530. */
  55531. this.angularSpeed = 0;
  55532. /**
  55533. * Defines the cell index used by the particle to be rendered from a sprite.
  55534. */
  55535. this.cellIndex = 0;
  55536. this._currentFrameCounter = 0;
  55537. if (!this.particleSystem.isAnimationSheetEnabled) {
  55538. return;
  55539. }
  55540. this.updateCellInfoFromSystem();
  55541. }
  55542. Particle.prototype.updateCellInfoFromSystem = function () {
  55543. this.cellIndex = this.particleSystem.startSpriteCellID;
  55544. if (this.particleSystem.spriteCellChangeSpeed == 0) {
  55545. this.updateCellIndex = this._updateCellIndexWithSpeedCalculated;
  55546. }
  55547. else {
  55548. this.updateCellIndex = this._updateCellIndexWithCustomSpeed;
  55549. }
  55550. };
  55551. Particle.prototype._updateCellIndexWithSpeedCalculated = function (scaledUpdateSpeed) {
  55552. // (ageOffset / scaledUpdateSpeed) / available cells
  55553. var numberOfScaledUpdatesPerCell = ((this.lifeTime - this.age) / scaledUpdateSpeed) / (this.particleSystem.endSpriteCellID + 1 - this.cellIndex);
  55554. this._currentFrameCounter += scaledUpdateSpeed;
  55555. if (this._currentFrameCounter >= numberOfScaledUpdatesPerCell * scaledUpdateSpeed) {
  55556. this._currentFrameCounter = 0;
  55557. this.cellIndex++;
  55558. if (this.cellIndex > this.particleSystem.endSpriteCellID) {
  55559. this.cellIndex = this.particleSystem.endSpriteCellID;
  55560. }
  55561. }
  55562. };
  55563. Particle.prototype._updateCellIndexWithCustomSpeed = function () {
  55564. if (this._currentFrameCounter >= this.particleSystem.spriteCellChangeSpeed) {
  55565. this.cellIndex++;
  55566. this._currentFrameCounter = 0;
  55567. if (this.cellIndex > this.particleSystem.endSpriteCellID) {
  55568. if (this.particleSystem.spriteCellLoop) {
  55569. this.cellIndex = this.particleSystem.startSpriteCellID;
  55570. }
  55571. else {
  55572. this.cellIndex = this.particleSystem.endSpriteCellID;
  55573. }
  55574. }
  55575. }
  55576. else {
  55577. this._currentFrameCounter++;
  55578. }
  55579. };
  55580. /**
  55581. * Copy the properties of particle to another one.
  55582. * @param other the particle to copy the information to.
  55583. */
  55584. Particle.prototype.copyTo = function (other) {
  55585. other.position.copyFrom(this.position);
  55586. other.direction.copyFrom(this.direction);
  55587. other.color.copyFrom(this.color);
  55588. other.colorStep.copyFrom(this.colorStep);
  55589. other.lifeTime = this.lifeTime;
  55590. other.age = this.age;
  55591. other.size = this.size;
  55592. other.angle = this.angle;
  55593. other.angularSpeed = this.angularSpeed;
  55594. other.particleSystem = this.particleSystem;
  55595. other.cellIndex = this.cellIndex;
  55596. };
  55597. return Particle;
  55598. }());
  55599. BABYLON.Particle = Particle;
  55600. })(BABYLON || (BABYLON = {}));
  55601. //# sourceMappingURL=babylon.particle.js.map
  55602. var BABYLON;
  55603. (function (BABYLON) {
  55604. /**
  55605. * This represents a particle system in Babylon.
  55606. * 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.
  55607. * Particles can take different shapes while emitted like box, sphere, cone or you can write your custom function.
  55608. * @example https://doc.babylonjs.com/babylon101/particles
  55609. */
  55610. var ParticleSystem = /** @class */ (function () {
  55611. /**
  55612. * Instantiates a particle system.
  55613. * 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.
  55614. * @param name The name of the particle system
  55615. * @param capacity The max number of particles alive at the same time
  55616. * @param scene The scene the particle system belongs to
  55617. * @param customEffect a custom effect used to change the way particles are rendered by default
  55618. * @param isAnimationSheetEnabled Must be true if using a spritesheet to animate the particles texture
  55619. * @param epsilon Offset used to render the particles
  55620. */
  55621. function ParticleSystem(name, capacity, scene, customEffect, isAnimationSheetEnabled, epsilon) {
  55622. if (customEffect === void 0) { customEffect = null; }
  55623. if (isAnimationSheetEnabled === void 0) { isAnimationSheetEnabled = false; }
  55624. if (epsilon === void 0) { epsilon = 0.01; }
  55625. var _this = this;
  55626. /**
  55627. * List of animations used by the particle system.
  55628. */
  55629. this.animations = [];
  55630. /**
  55631. * The rendering group used by the Particle system to chose when to render.
  55632. */
  55633. this.renderingGroupId = 0;
  55634. /**
  55635. * The emitter represents the Mesh or position we are attaching the particle system to.
  55636. */
  55637. this.emitter = null;
  55638. /**
  55639. * The maximum number of particles to emit per frame
  55640. */
  55641. this.emitRate = 10;
  55642. /**
  55643. * If you want to launch only a few particles at once, that can be done, as well.
  55644. */
  55645. this.manualEmitCount = -1;
  55646. /**
  55647. * The overall motion speed (0.01 is default update speed, faster updates = faster animation)
  55648. */
  55649. this.updateSpeed = 0.01;
  55650. /**
  55651. * The amount of time the particle system is running (depends of the overall update speed).
  55652. */
  55653. this.targetStopDuration = 0;
  55654. /**
  55655. * Specifies whether the particle system will be disposed once it reaches the end of the animation.
  55656. */
  55657. this.disposeOnStop = false;
  55658. /**
  55659. * Minimum power of emitting particles.
  55660. */
  55661. this.minEmitPower = 1;
  55662. /**
  55663. * Maximum power of emitting particles.
  55664. */
  55665. this.maxEmitPower = 1;
  55666. /**
  55667. * Minimum life time of emitting particles.
  55668. */
  55669. this.minLifeTime = 1;
  55670. /**
  55671. * Maximum life time of emitting particles.
  55672. */
  55673. this.maxLifeTime = 1;
  55674. /**
  55675. * Minimum Size of emitting particles.
  55676. */
  55677. this.minSize = 1;
  55678. /**
  55679. * Maximum Size of emitting particles.
  55680. */
  55681. this.maxSize = 1;
  55682. /**
  55683. * Minimum angular speed of emitting particles (Z-axis rotation for each particle).
  55684. */
  55685. this.minAngularSpeed = 0;
  55686. /**
  55687. * Maximum angular speed of emitting particles (Z-axis rotation for each particle).
  55688. */
  55689. this.maxAngularSpeed = 0;
  55690. /**
  55691. * The layer mask we are rendering the particles through.
  55692. */
  55693. this.layerMask = 0x0FFFFFFF;
  55694. /**
  55695. * This can help using your own shader to render the particle system.
  55696. * The according effect will be created
  55697. */
  55698. this.customShader = null;
  55699. /**
  55700. * By default particle system starts as soon as they are created. This prevents the
  55701. * automatic start to happen and let you decide when to start emitting particles.
  55702. */
  55703. this.preventAutoStart = false;
  55704. /**
  55705. * Callback triggered when the particle animation is ending.
  55706. */
  55707. this.onAnimationEnd = null;
  55708. /**
  55709. * Blend mode use to render the particle, it can be either ParticleSystem.BLENDMODE_ONEONE or ParticleSystem.BLENDMODE_STANDARD.
  55710. */
  55711. this.blendMode = ParticleSystem.BLENDMODE_ONEONE;
  55712. /**
  55713. * Forces the particle to write their depth information to the depth buffer. This can help preventing other draw calls
  55714. * to override the particles.
  55715. */
  55716. this.forceDepthWrite = false;
  55717. /**
  55718. * You can use gravity if you want to give an orientation to your particles.
  55719. */
  55720. this.gravity = BABYLON.Vector3.Zero();
  55721. /**
  55722. * Random color of each particle after it has been emitted, between color1 and color2 vectors.
  55723. */
  55724. this.color1 = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  55725. /**
  55726. * Random color of each particle after it has been emitted, between color1 and color2 vectors.
  55727. */
  55728. this.color2 = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  55729. /**
  55730. * Color the particle will have at the end of its lifetime.
  55731. */
  55732. this.colorDead = new BABYLON.Color4(0, 0, 0, 1.0);
  55733. /**
  55734. * An optional mask to filter some colors out of the texture, or filter a part of the alpha channel.
  55735. */
  55736. this.textureMask = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  55737. /**
  55738. * If using a spritesheet (isAnimationSheetEnabled), defines if the sprite animation should loop between startSpriteCellID and endSpriteCellID or not.
  55739. */
  55740. this.spriteCellLoop = true;
  55741. /**
  55742. * If using a spritesheet (isAnimationSheetEnabled) and spriteCellLoop defines the speed of the sprite loop.
  55743. */
  55744. this.spriteCellChangeSpeed = 0;
  55745. /**
  55746. * If using a spritesheet (isAnimationSheetEnabled) and spriteCellLoop defines the first sprite cell to display.
  55747. */
  55748. this.startSpriteCellID = 0;
  55749. /**
  55750. * If using a spritesheet (isAnimationSheetEnabled) and spriteCellLoop defines the last sprite cell to display.
  55751. */
  55752. this.endSpriteCellID = 0;
  55753. /**
  55754. * If using a spritesheet (isAnimationSheetEnabled), defines the sprite cell width to use.
  55755. */
  55756. this.spriteCellWidth = 0;
  55757. /**
  55758. * If using a spritesheet (isAnimationSheetEnabled), defines the sprite cell height to use.
  55759. */
  55760. this.spriteCellHeight = 0;
  55761. /**
  55762. * An event triggered when the system is disposed.
  55763. */
  55764. this.onDisposeObservable = new BABYLON.Observable();
  55765. this._particles = new Array();
  55766. this._stockParticles = new Array();
  55767. this._newPartsExcess = 0;
  55768. this._vertexBuffers = {};
  55769. this._scaledColorStep = new BABYLON.Color4(0, 0, 0, 0);
  55770. this._colorDiff = new BABYLON.Color4(0, 0, 0, 0);
  55771. this._scaledDirection = BABYLON.Vector3.Zero();
  55772. this._scaledGravity = BABYLON.Vector3.Zero();
  55773. this._currentRenderId = -1;
  55774. this._started = false;
  55775. this._stopped = false;
  55776. this._actualFrame = 0;
  55777. this._vertexBufferSize = 11;
  55778. // start of sub system methods
  55779. /**
  55780. * "Recycles" one of the particle by copying it back to the "stock" of particles and removing it from the active list.
  55781. * Its lifetime will start back at 0.
  55782. */
  55783. this.recycleParticle = function (particle) {
  55784. var lastParticle = _this._particles.pop();
  55785. if (lastParticle !== particle) {
  55786. lastParticle.copyTo(particle);
  55787. }
  55788. _this._stockParticles.push(lastParticle);
  55789. };
  55790. this._createParticle = function () {
  55791. var particle;
  55792. if (_this._stockParticles.length !== 0) {
  55793. particle = _this._stockParticles.pop();
  55794. particle.age = 0;
  55795. particle.cellIndex = _this.startSpriteCellID;
  55796. }
  55797. else {
  55798. particle = new BABYLON.Particle(_this);
  55799. }
  55800. return particle;
  55801. };
  55802. this._emitFromParticle = function (particle) {
  55803. if (!_this.subEmitters || _this.subEmitters.length === 0) {
  55804. return;
  55805. }
  55806. var templateIndex = Math.floor(Math.random() * _this.subEmitters.length);
  55807. var subSystem = _this.subEmitters[templateIndex].clone(_this.name + "_sub", particle.position.clone());
  55808. subSystem._rootParticleSystem = _this;
  55809. _this.activeSubSystems.push(subSystem);
  55810. subSystem.start();
  55811. };
  55812. this._appendParticleVertexes = null;
  55813. this.id = name;
  55814. this.name = name;
  55815. this._capacity = capacity;
  55816. this._epsilon = epsilon;
  55817. this._isAnimationSheetEnabled = isAnimationSheetEnabled;
  55818. if (isAnimationSheetEnabled) {
  55819. this._vertexBufferSize = 12;
  55820. }
  55821. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  55822. this._customEffect = customEffect;
  55823. scene.particleSystems.push(this);
  55824. this._createIndexBuffer();
  55825. // 11 floats per particle (x, y, z, r, g, b, a, angle, size, offsetX, offsetY) + 1 filler
  55826. this._vertexData = new Float32Array(capacity * this._vertexBufferSize * 4);
  55827. this._vertexBuffer = new BABYLON.Buffer(scene.getEngine(), this._vertexData, true, this._vertexBufferSize);
  55828. var positions = this._vertexBuffer.createVertexBuffer(BABYLON.VertexBuffer.PositionKind, 0, 3);
  55829. var colors = this._vertexBuffer.createVertexBuffer(BABYLON.VertexBuffer.ColorKind, 3, 4);
  55830. var options = this._vertexBuffer.createVertexBuffer("options", 7, 4);
  55831. if (this._isAnimationSheetEnabled) {
  55832. var cellIndexBuffer = this._vertexBuffer.createVertexBuffer("cellIndex", 11, 1);
  55833. this._vertexBuffers["cellIndex"] = cellIndexBuffer;
  55834. }
  55835. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = positions;
  55836. this._vertexBuffers[BABYLON.VertexBuffer.ColorKind] = colors;
  55837. this._vertexBuffers["options"] = options;
  55838. // Default emitter type
  55839. this.particleEmitterType = new BABYLON.BoxParticleEmitter();
  55840. this.updateFunction = function (particles) {
  55841. for (var index = 0; index < particles.length; index++) {
  55842. var particle = particles[index];
  55843. particle.age += _this._scaledUpdateSpeed;
  55844. if (particle.age >= particle.lifeTime) { // Recycle by swapping with last particle
  55845. _this._emitFromParticle(particle);
  55846. _this.recycleParticle(particle);
  55847. index--;
  55848. continue;
  55849. }
  55850. else {
  55851. particle.colorStep.scaleToRef(_this._scaledUpdateSpeed, _this._scaledColorStep);
  55852. particle.color.addInPlace(_this._scaledColorStep);
  55853. if (particle.color.a < 0)
  55854. particle.color.a = 0;
  55855. particle.angle += particle.angularSpeed * _this._scaledUpdateSpeed;
  55856. particle.direction.scaleToRef(_this._scaledUpdateSpeed, _this._scaledDirection);
  55857. particle.position.addInPlace(_this._scaledDirection);
  55858. _this.gravity.scaleToRef(_this._scaledUpdateSpeed, _this._scaledGravity);
  55859. particle.direction.addInPlace(_this._scaledGravity);
  55860. if (_this._isAnimationSheetEnabled) {
  55861. particle.updateCellIndex(_this._scaledUpdateSpeed);
  55862. }
  55863. }
  55864. }
  55865. };
  55866. }
  55867. Object.defineProperty(ParticleSystem.prototype, "direction1", {
  55868. /**
  55869. * Random direction of each particle after it has been emitted, between direction1 and direction2 vectors.
  55870. * This only works when particleEmitterTyps is a BoxParticleEmitter
  55871. */
  55872. get: function () {
  55873. if (this.particleEmitterType.direction1) {
  55874. return this.particleEmitterType.direction1;
  55875. }
  55876. return BABYLON.Vector3.Zero();
  55877. },
  55878. set: function (value) {
  55879. if (this.particleEmitterType.direction1) {
  55880. this.particleEmitterType.direction1 = value;
  55881. }
  55882. },
  55883. enumerable: true,
  55884. configurable: true
  55885. });
  55886. Object.defineProperty(ParticleSystem.prototype, "direction2", {
  55887. /**
  55888. * Random direction of each particle after it has been emitted, between direction1 and direction2 vectors.
  55889. * This only works when particleEmitterTyps is a BoxParticleEmitter
  55890. */
  55891. get: function () {
  55892. if (this.particleEmitterType.direction2) {
  55893. return this.particleEmitterType.direction2;
  55894. }
  55895. return BABYLON.Vector3.Zero();
  55896. },
  55897. set: function (value) {
  55898. if (this.particleEmitterType.direction2) {
  55899. this.particleEmitterType.direction2 = value;
  55900. }
  55901. },
  55902. enumerable: true,
  55903. configurable: true
  55904. });
  55905. Object.defineProperty(ParticleSystem.prototype, "minEmitBox", {
  55906. /**
  55907. * 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.
  55908. * This only works when particleEmitterTyps is a BoxParticleEmitter
  55909. */
  55910. get: function () {
  55911. if (this.particleEmitterType.minEmitBox) {
  55912. return this.particleEmitterType.minEmitBox;
  55913. }
  55914. return BABYLON.Vector3.Zero();
  55915. },
  55916. set: function (value) {
  55917. if (this.particleEmitterType.minEmitBox) {
  55918. this.particleEmitterType.minEmitBox = value;
  55919. }
  55920. },
  55921. enumerable: true,
  55922. configurable: true
  55923. });
  55924. Object.defineProperty(ParticleSystem.prototype, "maxEmitBox", {
  55925. /**
  55926. * 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.
  55927. * This only works when particleEmitterTyps is a BoxParticleEmitter
  55928. */
  55929. get: function () {
  55930. if (this.particleEmitterType.maxEmitBox) {
  55931. return this.particleEmitterType.maxEmitBox;
  55932. }
  55933. return BABYLON.Vector3.Zero();
  55934. },
  55935. set: function (value) {
  55936. if (this.particleEmitterType.maxEmitBox) {
  55937. this.particleEmitterType.maxEmitBox = value;
  55938. }
  55939. },
  55940. enumerable: true,
  55941. configurable: true
  55942. });
  55943. Object.defineProperty(ParticleSystem.prototype, "onDispose", {
  55944. /**
  55945. * Sets a callback that will be triggered when the system is disposed.
  55946. */
  55947. set: function (callback) {
  55948. if (this._onDisposeObserver) {
  55949. this.onDisposeObservable.remove(this._onDisposeObserver);
  55950. }
  55951. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  55952. },
  55953. enumerable: true,
  55954. configurable: true
  55955. });
  55956. Object.defineProperty(ParticleSystem.prototype, "isAnimationSheetEnabled", {
  55957. /**
  55958. * Gets wether an animation sprite sheet is enabled or not on the particle system.
  55959. */
  55960. get: function () {
  55961. return this._isAnimationSheetEnabled;
  55962. },
  55963. enumerable: true,
  55964. configurable: true
  55965. });
  55966. Object.defineProperty(ParticleSystem.prototype, "particles", {
  55967. //end of Sub-emitter
  55968. /**
  55969. * Gets the current list of active particles
  55970. */
  55971. get: function () {
  55972. return this._particles;
  55973. },
  55974. enumerable: true,
  55975. configurable: true
  55976. });
  55977. /**
  55978. * Returns the string "ParticleSystem"
  55979. * @returns a string containing the class name
  55980. */
  55981. ParticleSystem.prototype.getClassName = function () {
  55982. return "ParticleSystem";
  55983. };
  55984. ParticleSystem.prototype._createIndexBuffer = function () {
  55985. var indices = [];
  55986. var index = 0;
  55987. for (var count = 0; count < this._capacity; count++) {
  55988. indices.push(index);
  55989. indices.push(index + 1);
  55990. indices.push(index + 2);
  55991. indices.push(index);
  55992. indices.push(index + 2);
  55993. indices.push(index + 3);
  55994. index += 4;
  55995. }
  55996. this._indexBuffer = this._scene.getEngine().createIndexBuffer(indices);
  55997. };
  55998. /**
  55999. * Gets the maximum number of particles active at the same time.
  56000. * @returns The max number of active particles.
  56001. */
  56002. ParticleSystem.prototype.getCapacity = function () {
  56003. return this._capacity;
  56004. };
  56005. /**
  56006. * Gets Wether there are still active particles in the system.
  56007. * @returns True if it is alive, otherwise false.
  56008. */
  56009. ParticleSystem.prototype.isAlive = function () {
  56010. return this._alive;
  56011. };
  56012. /**
  56013. * Gets Wether the system has been started.
  56014. * @returns True if it has been started, otherwise false.
  56015. */
  56016. ParticleSystem.prototype.isStarted = function () {
  56017. return this._started;
  56018. };
  56019. /**
  56020. * Starts the particle system and begins to emit.
  56021. */
  56022. ParticleSystem.prototype.start = function () {
  56023. this._started = true;
  56024. this._stopped = false;
  56025. this._actualFrame = 0;
  56026. if (this.subEmitters && this.subEmitters.length != 0) {
  56027. this.activeSubSystems = new Array();
  56028. }
  56029. };
  56030. /**
  56031. * Stops the particle system.
  56032. * @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.
  56033. */
  56034. ParticleSystem.prototype.stop = function (stopSubEmitters) {
  56035. if (stopSubEmitters === void 0) { stopSubEmitters = true; }
  56036. this._stopped = true;
  56037. if (stopSubEmitters) {
  56038. this._stopSubEmitters();
  56039. }
  56040. };
  56041. // animation sheet
  56042. /**
  56043. * Remove all active particles
  56044. */
  56045. ParticleSystem.prototype.reset = function () {
  56046. this._stockParticles = [];
  56047. this._particles = [];
  56048. };
  56049. /**
  56050. * @hidden (for internal use only)
  56051. */
  56052. ParticleSystem.prototype._appendParticleVertex = function (index, particle, offsetX, offsetY) {
  56053. var offset = index * this._vertexBufferSize;
  56054. this._vertexData[offset] = particle.position.x;
  56055. this._vertexData[offset + 1] = particle.position.y;
  56056. this._vertexData[offset + 2] = particle.position.z;
  56057. this._vertexData[offset + 3] = particle.color.r;
  56058. this._vertexData[offset + 4] = particle.color.g;
  56059. this._vertexData[offset + 5] = particle.color.b;
  56060. this._vertexData[offset + 6] = particle.color.a;
  56061. this._vertexData[offset + 7] = particle.angle;
  56062. this._vertexData[offset + 8] = particle.size;
  56063. this._vertexData[offset + 9] = offsetX;
  56064. this._vertexData[offset + 10] = offsetY;
  56065. };
  56066. /**
  56067. * @hidden (for internal use only)
  56068. */
  56069. ParticleSystem.prototype._appendParticleVertexWithAnimation = function (index, particle, offsetX, offsetY) {
  56070. if (offsetX === 0)
  56071. offsetX = this._epsilon;
  56072. else if (offsetX === 1)
  56073. offsetX = 1 - this._epsilon;
  56074. if (offsetY === 0)
  56075. offsetY = this._epsilon;
  56076. else if (offsetY === 1)
  56077. offsetY = 1 - this._epsilon;
  56078. var offset = index * this._vertexBufferSize;
  56079. this._vertexData[offset] = particle.position.x;
  56080. this._vertexData[offset + 1] = particle.position.y;
  56081. this._vertexData[offset + 2] = particle.position.z;
  56082. this._vertexData[offset + 3] = particle.color.r;
  56083. this._vertexData[offset + 4] = particle.color.g;
  56084. this._vertexData[offset + 5] = particle.color.b;
  56085. this._vertexData[offset + 6] = particle.color.a;
  56086. this._vertexData[offset + 7] = particle.angle;
  56087. this._vertexData[offset + 8] = particle.size;
  56088. this._vertexData[offset + 9] = offsetX;
  56089. this._vertexData[offset + 10] = offsetY;
  56090. this._vertexData[offset + 11] = particle.cellIndex;
  56091. };
  56092. ParticleSystem.prototype._stopSubEmitters = function () {
  56093. if (!this.activeSubSystems) {
  56094. return;
  56095. }
  56096. this.activeSubSystems.forEach(function (subSystem) {
  56097. subSystem.stop(true);
  56098. });
  56099. this.activeSubSystems = new Array();
  56100. };
  56101. ParticleSystem.prototype._removeFromRoot = function () {
  56102. if (!this._rootParticleSystem) {
  56103. return;
  56104. }
  56105. var index = this._rootParticleSystem.activeSubSystems.indexOf(this);
  56106. if (index !== -1) {
  56107. this._rootParticleSystem.activeSubSystems.splice(index, 1);
  56108. }
  56109. };
  56110. // end of sub system methods
  56111. ParticleSystem.prototype._update = function (newParticles) {
  56112. // Update current
  56113. this._alive = this._particles.length > 0;
  56114. this.updateFunction(this._particles);
  56115. // Add new ones
  56116. var worldMatrix;
  56117. if (this.emitter.position) {
  56118. var emitterMesh = this.emitter;
  56119. worldMatrix = emitterMesh.getWorldMatrix();
  56120. }
  56121. else {
  56122. var emitterPosition = this.emitter;
  56123. worldMatrix = BABYLON.Matrix.Translation(emitterPosition.x, emitterPosition.y, emitterPosition.z);
  56124. }
  56125. var particle;
  56126. for (var index = 0; index < newParticles; index++) {
  56127. if (this._particles.length === this._capacity) {
  56128. break;
  56129. }
  56130. particle = this._createParticle();
  56131. this._particles.push(particle);
  56132. var emitPower = BABYLON.Scalar.RandomRange(this.minEmitPower, this.maxEmitPower);
  56133. if (this.startPositionFunction) {
  56134. this.startPositionFunction(worldMatrix, particle.position, particle);
  56135. }
  56136. else {
  56137. this.particleEmitterType.startPositionFunction(worldMatrix, particle.position, particle);
  56138. }
  56139. if (this.startDirectionFunction) {
  56140. this.startDirectionFunction(emitPower, worldMatrix, particle.direction, particle);
  56141. }
  56142. else {
  56143. this.particleEmitterType.startDirectionFunction(emitPower, worldMatrix, particle.direction, particle);
  56144. }
  56145. particle.lifeTime = BABYLON.Scalar.RandomRange(this.minLifeTime, this.maxLifeTime);
  56146. particle.size = BABYLON.Scalar.RandomRange(this.minSize, this.maxSize);
  56147. particle.angularSpeed = BABYLON.Scalar.RandomRange(this.minAngularSpeed, this.maxAngularSpeed);
  56148. var step = BABYLON.Scalar.RandomRange(0, 1.0);
  56149. BABYLON.Color4.LerpToRef(this.color1, this.color2, step, particle.color);
  56150. this.colorDead.subtractToRef(particle.color, this._colorDiff);
  56151. this._colorDiff.scaleToRef(1.0 / particle.lifeTime, particle.colorStep);
  56152. }
  56153. };
  56154. ParticleSystem.prototype._getEffect = function () {
  56155. if (this._customEffect) {
  56156. return this._customEffect;
  56157. }
  56158. ;
  56159. var defines = [];
  56160. if (this._scene.clipPlane) {
  56161. defines.push("#define CLIPPLANE");
  56162. }
  56163. if (this._isAnimationSheetEnabled) {
  56164. defines.push("#define ANIMATESHEET");
  56165. }
  56166. // Effect
  56167. var join = defines.join("\n");
  56168. if (this._cachedDefines !== join) {
  56169. this._cachedDefines = join;
  56170. var attributesNamesOrOptions;
  56171. var effectCreationOption;
  56172. if (this._isAnimationSheetEnabled) {
  56173. attributesNamesOrOptions = [BABYLON.VertexBuffer.PositionKind, BABYLON.VertexBuffer.ColorKind, "options", "cellIndex"];
  56174. effectCreationOption = ["invView", "view", "projection", "particlesInfos", "vClipPlane", "textureMask"];
  56175. }
  56176. else {
  56177. attributesNamesOrOptions = [BABYLON.VertexBuffer.PositionKind, BABYLON.VertexBuffer.ColorKind, "options"];
  56178. effectCreationOption = ["invView", "view", "projection", "vClipPlane", "textureMask"];
  56179. }
  56180. this._effect = this._scene.getEngine().createEffect("particles", attributesNamesOrOptions, effectCreationOption, ["diffuseSampler"], join);
  56181. }
  56182. return this._effect;
  56183. };
  56184. /**
  56185. * Animates the particle system for the current frame by emitting new particles and or animating the living ones.
  56186. */
  56187. ParticleSystem.prototype.animate = function () {
  56188. if (!this._started)
  56189. return;
  56190. var effect = this._getEffect();
  56191. // Check
  56192. if (!this.emitter || !effect.isReady() || !this.particleTexture || !this.particleTexture.isReady())
  56193. return;
  56194. if (this._currentRenderId === this._scene.getRenderId()) {
  56195. return;
  56196. }
  56197. this._currentRenderId = this._scene.getRenderId();
  56198. this._scaledUpdateSpeed = this.updateSpeed * this._scene.getAnimationRatio();
  56199. // determine the number of particles we need to create
  56200. var newParticles;
  56201. if (this.manualEmitCount > -1) {
  56202. newParticles = this.manualEmitCount;
  56203. this._newPartsExcess = 0;
  56204. this.manualEmitCount = 0;
  56205. }
  56206. else {
  56207. newParticles = ((this.emitRate * this._scaledUpdateSpeed) >> 0);
  56208. this._newPartsExcess += this.emitRate * this._scaledUpdateSpeed - newParticles;
  56209. }
  56210. if (this._newPartsExcess > 1.0) {
  56211. newParticles += this._newPartsExcess >> 0;
  56212. this._newPartsExcess -= this._newPartsExcess >> 0;
  56213. }
  56214. this._alive = false;
  56215. if (!this._stopped) {
  56216. this._actualFrame += this._scaledUpdateSpeed;
  56217. if (this.targetStopDuration && this._actualFrame >= this.targetStopDuration)
  56218. this.stop();
  56219. }
  56220. else {
  56221. newParticles = 0;
  56222. }
  56223. this._update(newParticles);
  56224. // Stopped?
  56225. if (this._stopped) {
  56226. if (!this._alive) {
  56227. this._started = false;
  56228. if (this.onAnimationEnd) {
  56229. this.onAnimationEnd();
  56230. }
  56231. if (this.disposeOnStop) {
  56232. this._scene._toBeDisposed.push(this);
  56233. }
  56234. }
  56235. }
  56236. // Animation sheet
  56237. if (this._isAnimationSheetEnabled) {
  56238. this._appendParticleVertexes = this._appenedParticleVertexesWithSheet;
  56239. }
  56240. else {
  56241. this._appendParticleVertexes = this._appenedParticleVertexesNoSheet;
  56242. }
  56243. // Update VBO
  56244. var offset = 0;
  56245. for (var index = 0; index < this._particles.length; index++) {
  56246. var particle = this._particles[index];
  56247. this._appendParticleVertexes(offset, particle);
  56248. offset += 4;
  56249. }
  56250. if (this._vertexBuffer) {
  56251. this._vertexBuffer.update(this._vertexData);
  56252. }
  56253. if (this.manualEmitCount === 0 && this.disposeOnStop) {
  56254. this.stop();
  56255. }
  56256. };
  56257. ParticleSystem.prototype._appenedParticleVertexesWithSheet = function (offset, particle) {
  56258. this._appendParticleVertexWithAnimation(offset++, particle, 0, 0);
  56259. this._appendParticleVertexWithAnimation(offset++, particle, 1, 0);
  56260. this._appendParticleVertexWithAnimation(offset++, particle, 1, 1);
  56261. this._appendParticleVertexWithAnimation(offset++, particle, 0, 1);
  56262. };
  56263. ParticleSystem.prototype._appenedParticleVertexesNoSheet = function (offset, particle) {
  56264. this._appendParticleVertex(offset++, particle, 0, 0);
  56265. this._appendParticleVertex(offset++, particle, 1, 0);
  56266. this._appendParticleVertex(offset++, particle, 1, 1);
  56267. this._appendParticleVertex(offset++, particle, 0, 1);
  56268. };
  56269. /**
  56270. * Rebuilds the particle system.
  56271. */
  56272. ParticleSystem.prototype.rebuild = function () {
  56273. this._createIndexBuffer();
  56274. if (this._vertexBuffer) {
  56275. this._vertexBuffer._rebuild();
  56276. }
  56277. };
  56278. /**
  56279. * Is this system ready to be used/rendered
  56280. * @return true if the system is ready
  56281. */
  56282. ParticleSystem.prototype.isReady = function () {
  56283. var effect = this._getEffect();
  56284. if (!this.emitter || !effect.isReady() || !this.particleTexture || !this.particleTexture.isReady()) {
  56285. return false;
  56286. }
  56287. return true;
  56288. };
  56289. /**
  56290. * Renders the particle system in its current state.
  56291. * @returns the current number of particles
  56292. */
  56293. ParticleSystem.prototype.render = function () {
  56294. var effect = this._getEffect();
  56295. // Check
  56296. if (!this.isReady() || !this._particles.length) {
  56297. return 0;
  56298. }
  56299. var engine = this._scene.getEngine();
  56300. // Render
  56301. engine.enableEffect(effect);
  56302. engine.setState(false);
  56303. var viewMatrix = this._scene.getViewMatrix();
  56304. effect.setTexture("diffuseSampler", this.particleTexture);
  56305. effect.setMatrix("view", viewMatrix);
  56306. effect.setMatrix("projection", this._scene.getProjectionMatrix());
  56307. if (this._isAnimationSheetEnabled && this.particleTexture) {
  56308. var baseSize = this.particleTexture.getBaseSize();
  56309. effect.setFloat3("particlesInfos", this.spriteCellWidth / baseSize.width, this.spriteCellHeight / baseSize.height, baseSize.width / this.spriteCellWidth);
  56310. }
  56311. effect.setFloat4("textureMask", this.textureMask.r, this.textureMask.g, this.textureMask.b, this.textureMask.a);
  56312. if (this._scene.clipPlane) {
  56313. var clipPlane = this._scene.clipPlane;
  56314. var invView = viewMatrix.clone();
  56315. invView.invert();
  56316. effect.setMatrix("invView", invView);
  56317. effect.setFloat4("vClipPlane", clipPlane.normal.x, clipPlane.normal.y, clipPlane.normal.z, clipPlane.d);
  56318. }
  56319. // VBOs
  56320. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, effect);
  56321. // Draw order
  56322. if (this.blendMode === ParticleSystem.BLENDMODE_ONEONE) {
  56323. engine.setAlphaMode(BABYLON.Engine.ALPHA_ONEONE);
  56324. }
  56325. else {
  56326. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  56327. }
  56328. if (this.forceDepthWrite) {
  56329. engine.setDepthWrite(true);
  56330. }
  56331. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, this._particles.length * 6);
  56332. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  56333. return this._particles.length;
  56334. };
  56335. /**
  56336. * Disposes the particle system and free the associated resources
  56337. * @param disposeTexture defines if the particule texture must be disposed as well (true by default)
  56338. */
  56339. ParticleSystem.prototype.dispose = function (disposeTexture) {
  56340. if (disposeTexture === void 0) { disposeTexture = true; }
  56341. if (this._vertexBuffer) {
  56342. this._vertexBuffer.dispose();
  56343. this._vertexBuffer = null;
  56344. }
  56345. if (this._indexBuffer) {
  56346. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  56347. this._indexBuffer = null;
  56348. }
  56349. if (disposeTexture && this.particleTexture) {
  56350. this.particleTexture.dispose();
  56351. this.particleTexture = null;
  56352. }
  56353. this._removeFromRoot();
  56354. // Remove from scene
  56355. var index = this._scene.particleSystems.indexOf(this);
  56356. if (index > -1) {
  56357. this._scene.particleSystems.splice(index, 1);
  56358. }
  56359. // Callback
  56360. this.onDisposeObservable.notifyObservers(this);
  56361. this.onDisposeObservable.clear();
  56362. };
  56363. /**
  56364. * Creates a Sphere Emitter for the particle system. (emits along the sphere radius)
  56365. * @param radius The radius of the sphere to emit from
  56366. * @returns the emitter
  56367. */
  56368. ParticleSystem.prototype.createSphereEmitter = function (radius) {
  56369. if (radius === void 0) { radius = 1; }
  56370. var particleEmitter = new BABYLON.SphereParticleEmitter(radius);
  56371. this.particleEmitterType = particleEmitter;
  56372. return particleEmitter;
  56373. };
  56374. /**
  56375. * Creates a Directed Sphere Emitter for the particle system. (emits between direction1 and direction2)
  56376. * @param radius The radius of the sphere to emit from
  56377. * @param direction1 Particles are emitted between the direction1 and direction2 from within the sphere
  56378. * @param direction2 Particles are emitted between the direction1 and direction2 from within the sphere
  56379. * @returns the emitter
  56380. */
  56381. ParticleSystem.prototype.createDirectedSphereEmitter = function (radius, direction1, direction2) {
  56382. if (radius === void 0) { radius = 1; }
  56383. if (direction1 === void 0) { direction1 = new BABYLON.Vector3(0, 1.0, 0); }
  56384. if (direction2 === void 0) { direction2 = new BABYLON.Vector3(0, 1.0, 0); }
  56385. var particleEmitter = new BABYLON.SphereDirectedParticleEmitter(radius, direction1, direction2);
  56386. this.particleEmitterType = particleEmitter;
  56387. return particleEmitter;
  56388. };
  56389. /**
  56390. * Creates a Cone Emitter for the particle system. (emits from the cone to the particle position)
  56391. * @param radius The radius of the cone to emit from
  56392. * @param angle The base angle of the cone
  56393. * @returns the emitter
  56394. */
  56395. ParticleSystem.prototype.createConeEmitter = function (radius, angle) {
  56396. if (radius === void 0) { radius = 1; }
  56397. if (angle === void 0) { angle = Math.PI / 4; }
  56398. var particleEmitter = new BABYLON.ConeParticleEmitter(radius, angle);
  56399. this.particleEmitterType = particleEmitter;
  56400. return particleEmitter;
  56401. };
  56402. // 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.
  56403. /**
  56404. * Creates a Box Emitter for the particle system. (emits between direction1 and direction2 from withing the box defined by minEmitBox and maxEmitBox)
  56405. * @param direction1 Particles are emitted between the direction1 and direction2 from within the box
  56406. * @param direction2 Particles are emitted between the direction1 and direction2 from within the box
  56407. * @param minEmitBox Particles are emitted from the box between minEmitBox and maxEmitBox
  56408. * @param maxEmitBox Particles are emitted from the box between minEmitBox and maxEmitBox
  56409. * @returns the emitter
  56410. */
  56411. ParticleSystem.prototype.createBoxEmitter = function (direction1, direction2, minEmitBox, maxEmitBox) {
  56412. var particleEmitter = new BABYLON.BoxParticleEmitter();
  56413. this.particleEmitterType = particleEmitter;
  56414. this.direction1 = direction1;
  56415. this.direction2 = direction2;
  56416. this.minEmitBox = minEmitBox;
  56417. this.maxEmitBox = maxEmitBox;
  56418. return particleEmitter;
  56419. };
  56420. // Clone
  56421. /**
  56422. * Clones the particle system.
  56423. * @param name The name of the cloned object
  56424. * @param newEmitter The new emitter to use
  56425. * @returns the cloned particle system
  56426. */
  56427. ParticleSystem.prototype.clone = function (name, newEmitter) {
  56428. var custom = null;
  56429. var program = null;
  56430. if (this.customShader != null) {
  56431. program = this.customShader;
  56432. var defines = (program.shaderOptions.defines.length > 0) ? program.shaderOptions.defines.join("\n") : "";
  56433. custom = this._scene.getEngine().createEffectForParticles(program.shaderPath.fragmentElement, program.shaderOptions.uniforms, program.shaderOptions.samplers, defines);
  56434. }
  56435. var result = new ParticleSystem(name, this._capacity, this._scene, custom);
  56436. result.customShader = program;
  56437. BABYLON.Tools.DeepCopy(this, result, ["particles", "customShader"]);
  56438. if (newEmitter === undefined) {
  56439. newEmitter = this.emitter;
  56440. }
  56441. result.emitter = newEmitter;
  56442. if (this.particleTexture) {
  56443. result.particleTexture = new BABYLON.Texture(this.particleTexture.url, this._scene);
  56444. }
  56445. if (!this.preventAutoStart) {
  56446. result.start();
  56447. }
  56448. return result;
  56449. };
  56450. /**
  56451. * Serializes the particle system to a JSON object.
  56452. * @returns the JSON object
  56453. */
  56454. ParticleSystem.prototype.serialize = function () {
  56455. var serializationObject = {};
  56456. serializationObject.name = this.name;
  56457. serializationObject.id = this.id;
  56458. // Emitter
  56459. if (this.emitter.position) {
  56460. var emitterMesh = this.emitter;
  56461. serializationObject.emitterId = emitterMesh.id;
  56462. }
  56463. else {
  56464. var emitterPosition = this.emitter;
  56465. serializationObject.emitter = emitterPosition.asArray();
  56466. }
  56467. serializationObject.capacity = this.getCapacity();
  56468. if (this.particleTexture) {
  56469. serializationObject.textureName = this.particleTexture.name;
  56470. }
  56471. // Animations
  56472. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  56473. // Particle system
  56474. serializationObject.minAngularSpeed = this.minAngularSpeed;
  56475. serializationObject.maxAngularSpeed = this.maxAngularSpeed;
  56476. serializationObject.minSize = this.minSize;
  56477. serializationObject.maxSize = this.maxSize;
  56478. serializationObject.minEmitPower = this.minEmitPower;
  56479. serializationObject.maxEmitPower = this.maxEmitPower;
  56480. serializationObject.minLifeTime = this.minLifeTime;
  56481. serializationObject.maxLifeTime = this.maxLifeTime;
  56482. serializationObject.emitRate = this.emitRate;
  56483. serializationObject.minEmitBox = this.minEmitBox.asArray();
  56484. serializationObject.maxEmitBox = this.maxEmitBox.asArray();
  56485. serializationObject.gravity = this.gravity.asArray();
  56486. serializationObject.direction1 = this.direction1.asArray();
  56487. serializationObject.direction2 = this.direction2.asArray();
  56488. serializationObject.color1 = this.color1.asArray();
  56489. serializationObject.color2 = this.color2.asArray();
  56490. serializationObject.colorDead = this.colorDead.asArray();
  56491. serializationObject.updateSpeed = this.updateSpeed;
  56492. serializationObject.targetStopDuration = this.targetStopDuration;
  56493. serializationObject.textureMask = this.textureMask.asArray();
  56494. serializationObject.blendMode = this.blendMode;
  56495. serializationObject.customShader = this.customShader;
  56496. serializationObject.preventAutoStart = this.preventAutoStart;
  56497. serializationObject.startSpriteCellID = this.startSpriteCellID;
  56498. serializationObject.endSpriteCellID = this.endSpriteCellID;
  56499. serializationObject.spriteCellLoop = this.spriteCellLoop;
  56500. serializationObject.spriteCellChangeSpeed = this.spriteCellChangeSpeed;
  56501. serializationObject.spriteCellWidth = this.spriteCellWidth;
  56502. serializationObject.spriteCellHeight = this.spriteCellHeight;
  56503. serializationObject.isAnimationSheetEnabled = this._isAnimationSheetEnabled;
  56504. // Emitter
  56505. if (this.particleEmitterType) {
  56506. serializationObject.particleEmitterType = this.particleEmitterType.serialize();
  56507. }
  56508. return serializationObject;
  56509. };
  56510. /**
  56511. * Parses a JSON object to create a particle system.
  56512. * @param parsedParticleSystem The JSON object to parse
  56513. * @param scene The scene to create the particle system in
  56514. * @param rootUrl The root url to use to load external dependencies like texture
  56515. * @returns the Parsed particle system
  56516. */
  56517. ParticleSystem.Parse = function (parsedParticleSystem, scene, rootUrl) {
  56518. var name = parsedParticleSystem.name;
  56519. var custom = null;
  56520. var program = null;
  56521. if (parsedParticleSystem.customShader) {
  56522. program = parsedParticleSystem.customShader;
  56523. var defines = (program.shaderOptions.defines.length > 0) ? program.shaderOptions.defines.join("\n") : "";
  56524. custom = scene.getEngine().createEffectForParticles(program.shaderPath.fragmentElement, program.shaderOptions.uniforms, program.shaderOptions.samplers, defines);
  56525. }
  56526. var particleSystem = new ParticleSystem(name, parsedParticleSystem.capacity, scene, custom, parsedParticleSystem.isAnimationSheetEnabled);
  56527. particleSystem.customShader = program;
  56528. if (parsedParticleSystem.id) {
  56529. particleSystem.id = parsedParticleSystem.id;
  56530. }
  56531. // Auto start
  56532. if (parsedParticleSystem.preventAutoStart) {
  56533. particleSystem.preventAutoStart = parsedParticleSystem.preventAutoStart;
  56534. }
  56535. // Texture
  56536. if (parsedParticleSystem.textureName) {
  56537. particleSystem.particleTexture = new BABYLON.Texture(rootUrl + parsedParticleSystem.textureName, scene);
  56538. particleSystem.particleTexture.name = parsedParticleSystem.textureName;
  56539. }
  56540. // Emitter
  56541. if (parsedParticleSystem.emitterId) {
  56542. particleSystem.emitter = scene.getLastMeshByID(parsedParticleSystem.emitterId);
  56543. }
  56544. else {
  56545. particleSystem.emitter = BABYLON.Vector3.FromArray(parsedParticleSystem.emitter);
  56546. }
  56547. // Animations
  56548. if (parsedParticleSystem.animations) {
  56549. for (var animationIndex = 0; animationIndex < parsedParticleSystem.animations.length; animationIndex++) {
  56550. var parsedAnimation = parsedParticleSystem.animations[animationIndex];
  56551. particleSystem.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  56552. }
  56553. }
  56554. if (parsedParticleSystem.autoAnimate) {
  56555. scene.beginAnimation(particleSystem, parsedParticleSystem.autoAnimateFrom, parsedParticleSystem.autoAnimateTo, parsedParticleSystem.autoAnimateLoop, parsedParticleSystem.autoAnimateSpeed || 1.0);
  56556. }
  56557. // Particle system
  56558. particleSystem.minAngularSpeed = parsedParticleSystem.minAngularSpeed;
  56559. particleSystem.maxAngularSpeed = parsedParticleSystem.maxAngularSpeed;
  56560. particleSystem.minSize = parsedParticleSystem.minSize;
  56561. particleSystem.maxSize = parsedParticleSystem.maxSize;
  56562. particleSystem.minLifeTime = parsedParticleSystem.minLifeTime;
  56563. particleSystem.maxLifeTime = parsedParticleSystem.maxLifeTime;
  56564. particleSystem.minEmitPower = parsedParticleSystem.minEmitPower;
  56565. particleSystem.maxEmitPower = parsedParticleSystem.maxEmitPower;
  56566. particleSystem.emitRate = parsedParticleSystem.emitRate;
  56567. particleSystem.minEmitBox = BABYLON.Vector3.FromArray(parsedParticleSystem.minEmitBox);
  56568. particleSystem.maxEmitBox = BABYLON.Vector3.FromArray(parsedParticleSystem.maxEmitBox);
  56569. particleSystem.gravity = BABYLON.Vector3.FromArray(parsedParticleSystem.gravity);
  56570. particleSystem.direction1 = BABYLON.Vector3.FromArray(parsedParticleSystem.direction1);
  56571. particleSystem.direction2 = BABYLON.Vector3.FromArray(parsedParticleSystem.direction2);
  56572. particleSystem.color1 = BABYLON.Color4.FromArray(parsedParticleSystem.color1);
  56573. particleSystem.color2 = BABYLON.Color4.FromArray(parsedParticleSystem.color2);
  56574. particleSystem.colorDead = BABYLON.Color4.FromArray(parsedParticleSystem.colorDead);
  56575. particleSystem.updateSpeed = parsedParticleSystem.updateSpeed;
  56576. particleSystem.targetStopDuration = parsedParticleSystem.targetStopDuration;
  56577. particleSystem.textureMask = BABYLON.Color4.FromArray(parsedParticleSystem.textureMask);
  56578. particleSystem.blendMode = parsedParticleSystem.blendMode;
  56579. particleSystem.startSpriteCellID = parsedParticleSystem.startSpriteCellID;
  56580. particleSystem.endSpriteCellID = parsedParticleSystem.endSpriteCellID;
  56581. particleSystem.spriteCellLoop = parsedParticleSystem.spriteCellLoop;
  56582. particleSystem.spriteCellChangeSpeed = parsedParticleSystem.spriteCellChangeSpeed;
  56583. particleSystem.spriteCellWidth = parsedParticleSystem.spriteCellWidth;
  56584. particleSystem.spriteCellHeight = parsedParticleSystem.spriteCellHeight;
  56585. if (!particleSystem.preventAutoStart) {
  56586. particleSystem.start();
  56587. }
  56588. return particleSystem;
  56589. };
  56590. /**
  56591. * Source color is added to the destination color without alpha affecting the result.
  56592. */
  56593. ParticleSystem.BLENDMODE_ONEONE = 0;
  56594. /**
  56595. * Blend current color and particle color using particle’s alpha.
  56596. */
  56597. ParticleSystem.BLENDMODE_STANDARD = 1;
  56598. return ParticleSystem;
  56599. }());
  56600. BABYLON.ParticleSystem = ParticleSystem;
  56601. })(BABYLON || (BABYLON = {}));
  56602. //# sourceMappingURL=babylon.particleSystem.js.map
  56603. //# sourceMappingURL=babylon.IParticleEmitterType.js.map
  56604. var BABYLON;
  56605. (function (BABYLON) {
  56606. /**
  56607. * Particle emitter emitting particles from the inside of a box.
  56608. * It emits the particles randomly between 2 given directions.
  56609. */
  56610. var BoxParticleEmitter = /** @class */ (function () {
  56611. /**
  56612. * Creates a new instance BoxParticleEmitter
  56613. */
  56614. function BoxParticleEmitter() {
  56615. /**
  56616. * Random direction of each particle after it has been emitted, between direction1 and direction2 vectors.
  56617. */
  56618. this.direction1 = new BABYLON.Vector3(0, 1.0, 0);
  56619. /**
  56620. * Random direction of each particle after it has been emitted, between direction1 and direction2 vectors.
  56621. */
  56622. this.direction2 = new BABYLON.Vector3(0, 1.0, 0);
  56623. /**
  56624. * 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.
  56625. */
  56626. this.minEmitBox = new BABYLON.Vector3(-0.5, -0.5, -0.5);
  56627. /**
  56628. * 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.
  56629. */
  56630. this.maxEmitBox = new BABYLON.Vector3(0.5, 0.5, 0.5);
  56631. }
  56632. /**
  56633. * Called by the particle System when the direction is computed for the created particle.
  56634. * @param emitPower is the power of the particle (speed)
  56635. * @param worldMatrix is the world matrix of the particle system
  56636. * @param directionToUpdate is the direction vector to update with the result
  56637. * @param particle is the particle we are computed the direction for
  56638. */
  56639. BoxParticleEmitter.prototype.startDirectionFunction = function (emitPower, worldMatrix, directionToUpdate, particle) {
  56640. var randX = BABYLON.Scalar.RandomRange(this.direction1.x, this.direction2.x);
  56641. var randY = BABYLON.Scalar.RandomRange(this.direction1.y, this.direction2.y);
  56642. var randZ = BABYLON.Scalar.RandomRange(this.direction1.z, this.direction2.z);
  56643. BABYLON.Vector3.TransformNormalFromFloatsToRef(randX * emitPower, randY * emitPower, randZ * emitPower, worldMatrix, directionToUpdate);
  56644. };
  56645. /**
  56646. * Called by the particle System when the position is computed for the created particle.
  56647. * @param worldMatrix is the world matrix of the particle system
  56648. * @param positionToUpdate is the position vector to update with the result
  56649. * @param particle is the particle we are computed the position for
  56650. */
  56651. BoxParticleEmitter.prototype.startPositionFunction = function (worldMatrix, positionToUpdate, particle) {
  56652. var randX = BABYLON.Scalar.RandomRange(this.minEmitBox.x, this.maxEmitBox.x);
  56653. var randY = BABYLON.Scalar.RandomRange(this.minEmitBox.y, this.maxEmitBox.y);
  56654. var randZ = BABYLON.Scalar.RandomRange(this.minEmitBox.z, this.maxEmitBox.z);
  56655. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(randX, randY, randZ, worldMatrix, positionToUpdate);
  56656. };
  56657. /**
  56658. * Clones the current emitter and returns a copy of it
  56659. * @returns the new emitter
  56660. */
  56661. BoxParticleEmitter.prototype.clone = function () {
  56662. var newOne = new BoxParticleEmitter();
  56663. BABYLON.Tools.DeepCopy(this, newOne);
  56664. return newOne;
  56665. };
  56666. /**
  56667. * Called by the {BABYLON.GPUParticleSystem} to setup the update shader
  56668. * @param effect defines the update shader
  56669. */
  56670. BoxParticleEmitter.prototype.applyToShader = function (effect) {
  56671. effect.setVector3("direction1", this.direction1);
  56672. effect.setVector3("direction2", this.direction2);
  56673. effect.setVector3("minEmitBox", this.minEmitBox);
  56674. effect.setVector3("maxEmitBox", this.maxEmitBox);
  56675. };
  56676. /**
  56677. * Returns a string to use to update the GPU particles update shader
  56678. * @returns a string containng the defines string
  56679. */
  56680. BoxParticleEmitter.prototype.getEffectDefines = function () {
  56681. return "#define BOXEMITTER";
  56682. };
  56683. /**
  56684. * Returns the string "BoxEmitter"
  56685. * @returns a string containing the class name
  56686. */
  56687. BoxParticleEmitter.prototype.getClassName = function () {
  56688. return "BoxEmitter";
  56689. };
  56690. /**
  56691. * Serializes the particle system to a JSON object.
  56692. * @returns the JSON object
  56693. */
  56694. BoxParticleEmitter.prototype.serialize = function () {
  56695. var serializationObject = {};
  56696. serializationObject.type = this.getClassName();
  56697. serializationObject.direction1 = this.direction1.asArray();
  56698. ;
  56699. serializationObject.direction2 = this.direction2.asArray();
  56700. ;
  56701. serializationObject.minEmitBox = this.minEmitBox.asArray();
  56702. ;
  56703. serializationObject.maxEmitBox = this.maxEmitBox.asArray();
  56704. ;
  56705. return serializationObject;
  56706. };
  56707. /**
  56708. * Parse properties from a JSON object
  56709. * @param serializationObject defines the JSON object
  56710. */
  56711. BoxParticleEmitter.prototype.parse = function (serializationObject) {
  56712. this.direction1.copyFrom(serializationObject.direction1);
  56713. this.direction2.copyFrom(serializationObject.direction2);
  56714. this.minEmitBox.copyFrom(serializationObject.minEmitBox);
  56715. this.maxEmitBox.copyFrom(serializationObject.maxEmitBox);
  56716. };
  56717. return BoxParticleEmitter;
  56718. }());
  56719. BABYLON.BoxParticleEmitter = BoxParticleEmitter;
  56720. })(BABYLON || (BABYLON = {}));
  56721. //# sourceMappingURL=babylon.boxParticleEmitter.js.map
  56722. var BABYLON;
  56723. (function (BABYLON) {
  56724. /**
  56725. * Particle emitter emitting particles from the inside of a cone.
  56726. * It emits the particles alongside the cone volume from the base to the particle.
  56727. * The emission direction might be randomized.
  56728. */
  56729. var ConeParticleEmitter = /** @class */ (function () {
  56730. /**
  56731. * Creates a new instance ConeParticleEmitter
  56732. * @param radius the radius of the emission cone (1 by default)
  56733. * @param angles the cone base angle (PI by default)
  56734. * @param directionRandomizer defines how much to randomize the particle direction [0-1]
  56735. */
  56736. function ConeParticleEmitter(radius,
  56737. /**
  56738. * The radius of the emission cone.
  56739. */
  56740. angle,
  56741. /**
  56742. * The cone base angle.
  56743. */
  56744. directionRandomizer) {
  56745. if (radius === void 0) { radius = 1; }
  56746. if (angle === void 0) { angle = Math.PI; }
  56747. if (directionRandomizer === void 0) { directionRandomizer = 0; }
  56748. this.angle = angle;
  56749. this.directionRandomizer = directionRandomizer;
  56750. this.radius = radius;
  56751. }
  56752. Object.defineProperty(ConeParticleEmitter.prototype, "radius", {
  56753. /**
  56754. * Gets the radius of the emission cone.
  56755. */
  56756. get: function () {
  56757. return this._radius;
  56758. },
  56759. /**
  56760. * Sets the radius of the emission cone.
  56761. */
  56762. set: function (value) {
  56763. this._radius = value;
  56764. if (this.angle !== 0) {
  56765. this._height = value / Math.tan(this.angle / 2);
  56766. }
  56767. else {
  56768. this._height = 1;
  56769. }
  56770. },
  56771. enumerable: true,
  56772. configurable: true
  56773. });
  56774. /**
  56775. * Called by the particle System when the direction is computed for the created particle.
  56776. * @param emitPower is the power of the particle (speed)
  56777. * @param worldMatrix is the world matrix of the particle system
  56778. * @param directionToUpdate is the direction vector to update with the result
  56779. * @param particle is the particle we are computed the direction for
  56780. */
  56781. ConeParticleEmitter.prototype.startDirectionFunction = function (emitPower, worldMatrix, directionToUpdate, particle) {
  56782. if (this.angle === 0) {
  56783. BABYLON.Vector3.TransformNormalFromFloatsToRef(0, emitPower, 0, worldMatrix, directionToUpdate);
  56784. }
  56785. else {
  56786. // measure the direction Vector from the emitter to the particle.
  56787. var direction = particle.position.subtract(worldMatrix.getTranslation()).normalize();
  56788. var randX = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);
  56789. var randY = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);
  56790. var randZ = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);
  56791. direction.x += randX;
  56792. direction.y += randY;
  56793. direction.z += randZ;
  56794. direction.normalize();
  56795. BABYLON.Vector3.TransformNormalFromFloatsToRef(direction.x * emitPower, direction.y * emitPower, direction.z * emitPower, worldMatrix, directionToUpdate);
  56796. }
  56797. };
  56798. /**
  56799. * Called by the particle System when the position is computed for the created particle.
  56800. * @param worldMatrix is the world matrix of the particle system
  56801. * @param positionToUpdate is the position vector to update with the result
  56802. * @param particle is the particle we are computed the position for
  56803. */
  56804. ConeParticleEmitter.prototype.startPositionFunction = function (worldMatrix, positionToUpdate, particle) {
  56805. var s = BABYLON.Scalar.RandomRange(0, Math.PI * 2);
  56806. var h = BABYLON.Scalar.RandomRange(0, 1);
  56807. // Better distribution in a cone at normal angles.
  56808. h = 1 - h * h;
  56809. var radius = BABYLON.Scalar.RandomRange(0, this._radius);
  56810. radius = radius * h;
  56811. var randX = radius * Math.sin(s);
  56812. var randZ = radius * Math.cos(s);
  56813. var randY = h * this._height;
  56814. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(randX, randY, randZ, worldMatrix, positionToUpdate);
  56815. };
  56816. /**
  56817. * Clones the current emitter and returns a copy of it
  56818. * @returns the new emitter
  56819. */
  56820. ConeParticleEmitter.prototype.clone = function () {
  56821. var newOne = new ConeParticleEmitter(this.radius, this.angle, this.directionRandomizer);
  56822. BABYLON.Tools.DeepCopy(this, newOne);
  56823. return newOne;
  56824. };
  56825. /**
  56826. * Called by the {BABYLON.GPUParticleSystem} to setup the update shader
  56827. * @param effect defines the update shader
  56828. */
  56829. ConeParticleEmitter.prototype.applyToShader = function (effect) {
  56830. effect.setFloat("radius", this.radius);
  56831. effect.setFloat("angle", this.angle);
  56832. effect.setFloat("height", this._height);
  56833. effect.setFloat("directionRandomizer", this.directionRandomizer);
  56834. };
  56835. /**
  56836. * Returns a string to use to update the GPU particles update shader
  56837. * @returns a string containng the defines string
  56838. */
  56839. ConeParticleEmitter.prototype.getEffectDefines = function () {
  56840. return "#define CONEEMITTER";
  56841. };
  56842. /**
  56843. * Returns the string "BoxEmitter"
  56844. * @returns a string containing the class name
  56845. */
  56846. ConeParticleEmitter.prototype.getClassName = function () {
  56847. return "ConeEmitter";
  56848. };
  56849. /**
  56850. * Serializes the particle system to a JSON object.
  56851. * @returns the JSON object
  56852. */
  56853. ConeParticleEmitter.prototype.serialize = function () {
  56854. var serializationObject = {};
  56855. serializationObject.type = this.getClassName();
  56856. serializationObject.radius = this.radius;
  56857. serializationObject.angle = this.angle;
  56858. serializationObject.directionRandomizer = this.directionRandomizer;
  56859. return serializationObject;
  56860. };
  56861. /**
  56862. * Parse properties from a JSON object
  56863. * @param serializationObject defines the JSON object
  56864. */
  56865. ConeParticleEmitter.prototype.parse = function (serializationObject) {
  56866. this.radius = serializationObject.radius;
  56867. this.angle = serializationObject.angle;
  56868. this.directionRandomizer = serializationObject.directionRandomizer;
  56869. };
  56870. return ConeParticleEmitter;
  56871. }());
  56872. BABYLON.ConeParticleEmitter = ConeParticleEmitter;
  56873. })(BABYLON || (BABYLON = {}));
  56874. //# sourceMappingURL=babylon.coneParticleEmitter.js.map
  56875. var BABYLON;
  56876. (function (BABYLON) {
  56877. /**
  56878. * Particle emitter emitting particles from the inside of a sphere.
  56879. * It emits the particles alongside the sphere radius. The emission direction might be randomized.
  56880. */
  56881. var SphereParticleEmitter = /** @class */ (function () {
  56882. /**
  56883. * Creates a new instance SphereParticleEmitter
  56884. * @param radius the radius of the emission sphere (1 by default)
  56885. * @param directionRandomizer defines how much to randomize the particle direction [0-1]
  56886. */
  56887. function SphereParticleEmitter(
  56888. /**
  56889. * The radius of the emission sphere.
  56890. */
  56891. radius,
  56892. /**
  56893. * How much to randomize the particle direction [0-1].
  56894. */
  56895. directionRandomizer) {
  56896. if (radius === void 0) { radius = 1; }
  56897. if (directionRandomizer === void 0) { directionRandomizer = 0; }
  56898. this.radius = radius;
  56899. this.directionRandomizer = directionRandomizer;
  56900. }
  56901. /**
  56902. * Called by the particle System when the direction is computed for the created particle.
  56903. * @param emitPower is the power of the particle (speed)
  56904. * @param worldMatrix is the world matrix of the particle system
  56905. * @param directionToUpdate is the direction vector to update with the result
  56906. * @param particle is the particle we are computed the direction for
  56907. */
  56908. SphereParticleEmitter.prototype.startDirectionFunction = function (emitPower, worldMatrix, directionToUpdate, particle) {
  56909. var direction = particle.position.subtract(worldMatrix.getTranslation()).normalize();
  56910. var randX = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);
  56911. var randY = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);
  56912. var randZ = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);
  56913. direction.x += randX;
  56914. direction.y += randY;
  56915. direction.z += randZ;
  56916. direction.normalize();
  56917. BABYLON.Vector3.TransformNormalFromFloatsToRef(direction.x * emitPower, direction.y * emitPower, direction.z * emitPower, worldMatrix, directionToUpdate);
  56918. };
  56919. /**
  56920. * Called by the particle System when the position is computed for the created particle.
  56921. * @param worldMatrix is the world matrix of the particle system
  56922. * @param positionToUpdate is the position vector to update with the result
  56923. * @param particle is the particle we are computed the position for
  56924. */
  56925. SphereParticleEmitter.prototype.startPositionFunction = function (worldMatrix, positionToUpdate, particle) {
  56926. var phi = BABYLON.Scalar.RandomRange(0, 2 * Math.PI);
  56927. var theta = BABYLON.Scalar.RandomRange(0, Math.PI);
  56928. var randRadius = BABYLON.Scalar.RandomRange(0, this.radius);
  56929. var randX = randRadius * Math.cos(phi) * Math.sin(theta);
  56930. var randY = randRadius * Math.cos(theta);
  56931. var randZ = randRadius * Math.sin(phi) * Math.sin(theta);
  56932. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(randX, randY, randZ, worldMatrix, positionToUpdate);
  56933. };
  56934. /**
  56935. * Clones the current emitter and returns a copy of it
  56936. * @returns the new emitter
  56937. */
  56938. SphereParticleEmitter.prototype.clone = function () {
  56939. var newOne = new SphereParticleEmitter(this.radius, this.directionRandomizer);
  56940. BABYLON.Tools.DeepCopy(this, newOne);
  56941. return newOne;
  56942. };
  56943. /**
  56944. * Called by the {BABYLON.GPUParticleSystem} to setup the update shader
  56945. * @param effect defines the update shader
  56946. */
  56947. SphereParticleEmitter.prototype.applyToShader = function (effect) {
  56948. effect.setFloat("radius", this.radius);
  56949. effect.setFloat("directionRandomizer", this.directionRandomizer);
  56950. };
  56951. /**
  56952. * Returns a string to use to update the GPU particles update shader
  56953. * @returns a string containng the defines string
  56954. */
  56955. SphereParticleEmitter.prototype.getEffectDefines = function () {
  56956. return "#define SPHEREEMITTER";
  56957. };
  56958. /**
  56959. * Returns the string "SphereParticleEmitter"
  56960. * @returns a string containing the class name
  56961. */
  56962. SphereParticleEmitter.prototype.getClassName = function () {
  56963. return "SphereParticleEmitter";
  56964. };
  56965. /**
  56966. * Serializes the particle system to a JSON object.
  56967. * @returns the JSON object
  56968. */
  56969. SphereParticleEmitter.prototype.serialize = function () {
  56970. var serializationObject = {};
  56971. serializationObject.type = this.getClassName();
  56972. serializationObject.radius = this.radius;
  56973. serializationObject.directionRandomizer = this.directionRandomizer;
  56974. return serializationObject;
  56975. };
  56976. /**
  56977. * Parse properties from a JSON object
  56978. * @param serializationObject defines the JSON object
  56979. */
  56980. SphereParticleEmitter.prototype.parse = function (serializationObject) {
  56981. this.radius = serializationObject.radius;
  56982. this.directionRandomizer = serializationObject.directionRandomizer;
  56983. };
  56984. return SphereParticleEmitter;
  56985. }());
  56986. BABYLON.SphereParticleEmitter = SphereParticleEmitter;
  56987. /**
  56988. * Particle emitter emitting particles from the inside of a sphere.
  56989. * It emits the particles randomly between two vectors.
  56990. */
  56991. var SphereDirectedParticleEmitter = /** @class */ (function (_super) {
  56992. __extends(SphereDirectedParticleEmitter, _super);
  56993. /**
  56994. * Creates a new instance SphereDirectedParticleEmitter
  56995. * @param radius the radius of the emission sphere (1 by default)
  56996. * @param direction1 the min limit of the emission direction (up vector by default)
  56997. * @param direction2 the max limit of the emission direction (up vector by default)
  56998. */
  56999. function SphereDirectedParticleEmitter(radius,
  57000. /**
  57001. * The min limit of the emission direction.
  57002. */
  57003. direction1,
  57004. /**
  57005. * The max limit of the emission direction.
  57006. */
  57007. direction2) {
  57008. if (radius === void 0) { radius = 1; }
  57009. if (direction1 === void 0) { direction1 = new BABYLON.Vector3(0, 1, 0); }
  57010. if (direction2 === void 0) { direction2 = new BABYLON.Vector3(0, 1, 0); }
  57011. var _this = _super.call(this, radius) || this;
  57012. _this.direction1 = direction1;
  57013. _this.direction2 = direction2;
  57014. return _this;
  57015. }
  57016. /**
  57017. * Called by the particle System when the direction is computed for the created particle.
  57018. * @param emitPower is the power of the particle (speed)
  57019. * @param worldMatrix is the world matrix of the particle system
  57020. * @param directionToUpdate is the direction vector to update with the result
  57021. * @param particle is the particle we are computed the direction for
  57022. */
  57023. SphereDirectedParticleEmitter.prototype.startDirectionFunction = function (emitPower, worldMatrix, directionToUpdate, particle) {
  57024. var randX = BABYLON.Scalar.RandomRange(this.direction1.x, this.direction2.x);
  57025. var randY = BABYLON.Scalar.RandomRange(this.direction1.y, this.direction2.y);
  57026. var randZ = BABYLON.Scalar.RandomRange(this.direction1.z, this.direction2.z);
  57027. BABYLON.Vector3.TransformNormalFromFloatsToRef(randX * emitPower, randY * emitPower, randZ * emitPower, worldMatrix, directionToUpdate);
  57028. };
  57029. /**
  57030. * Clones the current emitter and returns a copy of it
  57031. * @returns the new emitter
  57032. */
  57033. SphereDirectedParticleEmitter.prototype.clone = function () {
  57034. var newOne = new SphereDirectedParticleEmitter(this.radius, this.direction1, this.direction2);
  57035. BABYLON.Tools.DeepCopy(this, newOne);
  57036. return newOne;
  57037. };
  57038. /**
  57039. * Called by the {BABYLON.GPUParticleSystem} to setup the update shader
  57040. * @param effect defines the update shader
  57041. */
  57042. SphereDirectedParticleEmitter.prototype.applyToShader = function (effect) {
  57043. effect.setFloat("radius", this.radius);
  57044. effect.setVector3("direction1", this.direction1);
  57045. effect.setVector3("direction2", this.direction2);
  57046. };
  57047. /**
  57048. * Returns a string to use to update the GPU particles update shader
  57049. * @returns a string containng the defines string
  57050. */
  57051. SphereDirectedParticleEmitter.prototype.getEffectDefines = function () {
  57052. return "#define SPHEREEMITTER\n#define DIRECTEDSPHEREEMITTER";
  57053. };
  57054. /**
  57055. * Returns the string "SphereDirectedParticleEmitter"
  57056. * @returns a string containing the class name
  57057. */
  57058. SphereDirectedParticleEmitter.prototype.getClassName = function () {
  57059. return "SphereDirectedParticleEmitter";
  57060. };
  57061. /**
  57062. * Serializes the particle system to a JSON object.
  57063. * @returns the JSON object
  57064. */
  57065. SphereDirectedParticleEmitter.prototype.serialize = function () {
  57066. var serializationObject = _super.prototype.serialize.call(this);
  57067. ;
  57068. serializationObject.direction1 = this.direction1.asArray();
  57069. ;
  57070. serializationObject.direction2 = this.direction2.asArray();
  57071. ;
  57072. return serializationObject;
  57073. };
  57074. /**
  57075. * Parse properties from a JSON object
  57076. * @param serializationObject defines the JSON object
  57077. */
  57078. SphereDirectedParticleEmitter.prototype.parse = function (serializationObject) {
  57079. _super.prototype.parse.call(this, serializationObject);
  57080. this.direction1.copyFrom(serializationObject.direction1);
  57081. this.direction2.copyFrom(serializationObject.direction2);
  57082. };
  57083. return SphereDirectedParticleEmitter;
  57084. }(SphereParticleEmitter));
  57085. BABYLON.SphereDirectedParticleEmitter = SphereDirectedParticleEmitter;
  57086. })(BABYLON || (BABYLON = {}));
  57087. //# sourceMappingURL=babylon.sphereParticleEmitter.js.map
  57088. var __assign = (this && this.__assign) || Object.assign || function(t) {
  57089. for (var s, i = 1, n = arguments.length; i < n; i++) {
  57090. s = arguments[i];
  57091. for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
  57092. t[p] = s[p];
  57093. }
  57094. return t;
  57095. };
  57096. var BABYLON;
  57097. (function (BABYLON) {
  57098. /**
  57099. * This represents a GPU particle system in Babylon
  57100. * This is the fastest particle system in Babylon as it uses the GPU to update the individual particle data
  57101. * @see https://www.babylonjs-playground.com/#PU4WYI#4
  57102. */
  57103. var GPUParticleSystem = /** @class */ (function () {
  57104. /**
  57105. * Instantiates a GPU particle system.
  57106. * 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.
  57107. * @param name The name of the particle system
  57108. * @param capacity The max number of particles alive at the same time
  57109. * @param scene The scene the particle system belongs to
  57110. */
  57111. function GPUParticleSystem(name, options, scene) {
  57112. /**
  57113. * The emitter represents the Mesh or position we are attaching the particle system to.
  57114. */
  57115. this.emitter = null;
  57116. /**
  57117. * The rendering group used by the Particle system to chose when to render.
  57118. */
  57119. this.renderingGroupId = 0;
  57120. /**
  57121. * The layer mask we are rendering the particles through.
  57122. */
  57123. this.layerMask = 0x0FFFFFFF;
  57124. this._targetIndex = 0;
  57125. this._currentRenderId = -1;
  57126. this._started = false;
  57127. this._stopped = false;
  57128. this._timeDelta = 0;
  57129. this._attributesStrideSize = 14;
  57130. this._actualFrame = 0;
  57131. /**
  57132. * List of animations used by the particle system.
  57133. */
  57134. this.animations = [];
  57135. /**
  57136. * An event triggered when the system is disposed.
  57137. */
  57138. this.onDisposeObservable = new BABYLON.Observable();
  57139. /**
  57140. * The overall motion speed (0.01 is default update speed, faster updates = faster animation)
  57141. */
  57142. this.updateSpeed = 0.01;
  57143. /**
  57144. * The amount of time the particle system is running (depends of the overall update speed).
  57145. */
  57146. this.targetStopDuration = 0;
  57147. /**
  57148. * Blend mode use to render the particle, it can be either ParticleSystem.BLENDMODE_ONEONE or ParticleSystem.BLENDMODE_STANDARD.
  57149. */
  57150. this.blendMode = BABYLON.ParticleSystem.BLENDMODE_ONEONE;
  57151. /**
  57152. * Minimum life time of emitting particles.
  57153. */
  57154. this.minLifeTime = 1;
  57155. /**
  57156. * Maximum life time of emitting particles.
  57157. */
  57158. this.maxLifeTime = 1;
  57159. /**
  57160. * Minimum Size of emitting particles.
  57161. */
  57162. this.minSize = 1;
  57163. /**
  57164. * Maximum Size of emitting particles.
  57165. */
  57166. this.maxSize = 1;
  57167. /**
  57168. * Random color of each particle after it has been emitted, between color1 and color2 vectors.
  57169. */
  57170. this.color1 = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  57171. /**
  57172. * Random color of each particle after it has been emitted, between color1 and color2 vectors.
  57173. */
  57174. this.color2 = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  57175. /**
  57176. * Color the particle will have at the end of its lifetime.
  57177. */
  57178. this.colorDead = new BABYLON.Color4(0, 0, 0, 0);
  57179. /**
  57180. * The maximum number of particles to emit per frame until we reach the activeParticleCount value
  57181. */
  57182. this.emitRate = 100;
  57183. /**
  57184. * You can use gravity if you want to give an orientation to your particles.
  57185. */
  57186. this.gravity = BABYLON.Vector3.Zero();
  57187. /**
  57188. * Minimum power of emitting particles.
  57189. */
  57190. this.minEmitPower = 1;
  57191. /**
  57192. * Maximum power of emitting particles.
  57193. */
  57194. this.maxEmitPower = 1;
  57195. /**
  57196. * Forces the particle to write their depth information to the depth buffer. This can help preventing other draw calls
  57197. * to override the particles.
  57198. */
  57199. this.forceDepthWrite = false;
  57200. this.id = name;
  57201. this.name = name;
  57202. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  57203. this._engine = this._scene.getEngine();
  57204. var fullOptions = __assign({ capacity: 50000, randomTextureSize: this._engine.getCaps().maxTextureSize }, options);
  57205. this._capacity = fullOptions.capacity;
  57206. this._activeCount = fullOptions.capacity;
  57207. this._currentActiveCount = 0;
  57208. this._scene.particleSystems.push(this);
  57209. this._updateEffectOptions = {
  57210. attributes: ["position", "age", "life", "seed", "size", "color", "direction"],
  57211. uniformsNames: ["currentCount", "timeDelta", "generalRandoms", "emitterWM", "lifeTime", "color1", "color2", "sizeRange", "gravity", "emitPower",
  57212. "direction1", "direction2", "minEmitBox", "maxEmitBox", "radius", "directionRandomizer", "height", "angle", "stopFactor"],
  57213. uniformBuffersNames: [],
  57214. samplers: ["randomSampler"],
  57215. defines: "",
  57216. fallbacks: null,
  57217. onCompiled: null,
  57218. onError: null,
  57219. indexParameters: null,
  57220. maxSimultaneousLights: 0,
  57221. transformFeedbackVaryings: ["outPosition", "outAge", "outLife", "outSeed", "outSize", "outColor", "outDirection"]
  57222. };
  57223. // Random data
  57224. var maxTextureSize = Math.min(this._engine.getCaps().maxTextureSize, fullOptions.randomTextureSize);
  57225. var d = [];
  57226. for (var i = 0; i < maxTextureSize; ++i) {
  57227. d.push(Math.random());
  57228. d.push(Math.random());
  57229. d.push(Math.random());
  57230. d.push(Math.random());
  57231. }
  57232. 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);
  57233. this._randomTexture.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  57234. this._randomTexture.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  57235. this._randomTextureSize = maxTextureSize;
  57236. this.particleEmitterType = new BABYLON.BoxParticleEmitter();
  57237. }
  57238. Object.defineProperty(GPUParticleSystem, "IsSupported", {
  57239. /**
  57240. * Gets a boolean indicating if the GPU particles can be rendered on current browser
  57241. */
  57242. get: function () {
  57243. if (!BABYLON.Engine.LastCreatedEngine) {
  57244. return false;
  57245. }
  57246. return BABYLON.Engine.LastCreatedEngine.webGLVersion > 1;
  57247. },
  57248. enumerable: true,
  57249. configurable: true
  57250. });
  57251. Object.defineProperty(GPUParticleSystem.prototype, "direction1", {
  57252. /**
  57253. * Random direction of each particle after it has been emitted, between direction1 and direction2 vectors.
  57254. * This only works when particleEmitterTyps is a BoxParticleEmitter
  57255. */
  57256. get: function () {
  57257. if (this.particleEmitterType.direction1) {
  57258. return this.particleEmitterType.direction1;
  57259. }
  57260. return BABYLON.Vector3.Zero();
  57261. },
  57262. set: function (value) {
  57263. if (this.particleEmitterType.direction1) {
  57264. this.particleEmitterType.direction1 = value;
  57265. }
  57266. },
  57267. enumerable: true,
  57268. configurable: true
  57269. });
  57270. Object.defineProperty(GPUParticleSystem.prototype, "direction2", {
  57271. /**
  57272. * Random direction of each particle after it has been emitted, between direction1 and direction2 vectors.
  57273. * This only works when particleEmitterTyps is a BoxParticleEmitter
  57274. */
  57275. get: function () {
  57276. if (this.particleEmitterType.direction2) {
  57277. return this.particleEmitterType.direction2;
  57278. }
  57279. return BABYLON.Vector3.Zero();
  57280. },
  57281. set: function (value) {
  57282. if (this.particleEmitterType.direction2) {
  57283. this.particleEmitterType.direction2 = value;
  57284. }
  57285. },
  57286. enumerable: true,
  57287. configurable: true
  57288. });
  57289. Object.defineProperty(GPUParticleSystem.prototype, "minEmitBox", {
  57290. /**
  57291. * 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.
  57292. * This only works when particleEmitterTyps is a BoxParticleEmitter
  57293. */
  57294. get: function () {
  57295. if (this.particleEmitterType.minEmitBox) {
  57296. return this.particleEmitterType.minEmitBox;
  57297. }
  57298. return BABYLON.Vector3.Zero();
  57299. },
  57300. set: function (value) {
  57301. if (this.particleEmitterType.minEmitBox) {
  57302. this.particleEmitterType.minEmitBox = value;
  57303. }
  57304. },
  57305. enumerable: true,
  57306. configurable: true
  57307. });
  57308. Object.defineProperty(GPUParticleSystem.prototype, "maxEmitBox", {
  57309. /**
  57310. * 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.
  57311. * This only works when particleEmitterTyps is a BoxParticleEmitter
  57312. */
  57313. get: function () {
  57314. if (this.particleEmitterType.maxEmitBox) {
  57315. return this.particleEmitterType.maxEmitBox;
  57316. }
  57317. return BABYLON.Vector3.Zero();
  57318. },
  57319. set: function (value) {
  57320. if (this.particleEmitterType.maxEmitBox) {
  57321. this.particleEmitterType.maxEmitBox = value;
  57322. }
  57323. },
  57324. enumerable: true,
  57325. configurable: true
  57326. });
  57327. /**
  57328. * Gets the maximum number of particles active at the same time.
  57329. * @returns The max number of active particles.
  57330. */
  57331. GPUParticleSystem.prototype.getCapacity = function () {
  57332. return this._capacity;
  57333. };
  57334. Object.defineProperty(GPUParticleSystem.prototype, "activeParticleCount", {
  57335. /**
  57336. * Gets or set the number of active particles
  57337. */
  57338. get: function () {
  57339. return this._activeCount;
  57340. },
  57341. set: function (value) {
  57342. this._activeCount = Math.min(value, this._capacity);
  57343. },
  57344. enumerable: true,
  57345. configurable: true
  57346. });
  57347. /**
  57348. * Is this system ready to be used/rendered
  57349. * @return true if the system is ready
  57350. */
  57351. GPUParticleSystem.prototype.isReady = function () {
  57352. if (!this._updateEffect) {
  57353. this._recreateUpdateEffect();
  57354. this._recreateRenderEffect();
  57355. return false;
  57356. }
  57357. if (!this.emitter || !this._updateEffect.isReady() || !this._renderEffect.isReady() || !this.particleTexture || !this.particleTexture.isReady()) {
  57358. return false;
  57359. }
  57360. return true;
  57361. };
  57362. /**
  57363. * Gets Wether the system has been started.
  57364. * @returns True if it has been started, otherwise false.
  57365. */
  57366. GPUParticleSystem.prototype.isStarted = function () {
  57367. return this._started;
  57368. };
  57369. /**
  57370. * Starts the particle system and begins to emit.
  57371. */
  57372. GPUParticleSystem.prototype.start = function () {
  57373. this._started = true;
  57374. this._stopped = false;
  57375. };
  57376. /**
  57377. * Stops the particle system.
  57378. */
  57379. GPUParticleSystem.prototype.stop = function () {
  57380. this._stopped = true;
  57381. };
  57382. /**
  57383. * Remove all active particles
  57384. */
  57385. GPUParticleSystem.prototype.reset = function () {
  57386. this._releaseBuffers();
  57387. this._releaseVAOs();
  57388. this._currentActiveCount = 0;
  57389. this._targetIndex = 0;
  57390. };
  57391. /**
  57392. * Returns the string "GPUParticleSystem"
  57393. * @returns a string containing the class name
  57394. */
  57395. GPUParticleSystem.prototype.getClassName = function () {
  57396. return "GPUParticleSystem";
  57397. };
  57398. GPUParticleSystem.prototype._createUpdateVAO = function (source) {
  57399. var updateVertexBuffers = {};
  57400. updateVertexBuffers["position"] = source.createVertexBuffer("position", 0, 3);
  57401. updateVertexBuffers["age"] = source.createVertexBuffer("age", 3, 1);
  57402. updateVertexBuffers["life"] = source.createVertexBuffer("life", 4, 1);
  57403. updateVertexBuffers["seed"] = source.createVertexBuffer("seed", 5, 1);
  57404. updateVertexBuffers["size"] = source.createVertexBuffer("size", 6, 1);
  57405. updateVertexBuffers["color"] = source.createVertexBuffer("color", 7, 4);
  57406. updateVertexBuffers["direction"] = source.createVertexBuffer("direction", 11, 3);
  57407. var vao = this._engine.recordVertexArrayObject(updateVertexBuffers, null, this._updateEffect);
  57408. this._engine.bindArrayBuffer(null);
  57409. return vao;
  57410. };
  57411. GPUParticleSystem.prototype._createRenderVAO = function (source, spriteSource) {
  57412. var renderVertexBuffers = {};
  57413. renderVertexBuffers["position"] = source.createVertexBuffer("position", 0, 3, this._attributesStrideSize, true);
  57414. renderVertexBuffers["age"] = source.createVertexBuffer("age", 3, 1, this._attributesStrideSize, true);
  57415. renderVertexBuffers["life"] = source.createVertexBuffer("life", 4, 1, this._attributesStrideSize, true);
  57416. renderVertexBuffers["size"] = source.createVertexBuffer("size", 6, 1, this._attributesStrideSize, true);
  57417. renderVertexBuffers["color"] = source.createVertexBuffer("color", 7, 4, this._attributesStrideSize, true);
  57418. renderVertexBuffers["offset"] = spriteSource.createVertexBuffer("offset", 0, 2);
  57419. renderVertexBuffers["uv"] = spriteSource.createVertexBuffer("uv", 2, 2);
  57420. var vao = this._engine.recordVertexArrayObject(renderVertexBuffers, null, this._renderEffect);
  57421. this._engine.bindArrayBuffer(null);
  57422. return vao;
  57423. };
  57424. GPUParticleSystem.prototype._initialize = function (force) {
  57425. if (force === void 0) { force = false; }
  57426. if (this._buffer0 && !force) {
  57427. return;
  57428. }
  57429. var engine = this._scene.getEngine();
  57430. var data = new Array();
  57431. for (var particleIndex = 0; particleIndex < this._capacity; particleIndex++) {
  57432. // position
  57433. data.push(0.0);
  57434. data.push(0.0);
  57435. data.push(0.0);
  57436. // Age and life
  57437. data.push(0.0); // create the particle as a dead one to create a new one at start
  57438. data.push(0.0);
  57439. // Seed
  57440. data.push(Math.random());
  57441. // Size
  57442. data.push(0.0);
  57443. // color
  57444. data.push(0.0);
  57445. data.push(0.0);
  57446. data.push(0.0);
  57447. data.push(0.0);
  57448. // direction
  57449. data.push(0.0);
  57450. data.push(0.0);
  57451. data.push(0.0);
  57452. }
  57453. // Sprite data
  57454. var spriteData = new Float32Array([0.5, 0.5, 1, 1,
  57455. -0.5, 0.5, 0, 1,
  57456. -0.5, -0.5, 0, 0,
  57457. 0.5, -0.5, 1, 0]);
  57458. // Buffers
  57459. this._buffer0 = new BABYLON.Buffer(engine, data, false, this._attributesStrideSize);
  57460. this._buffer1 = new BABYLON.Buffer(engine, data, false, this._attributesStrideSize);
  57461. this._spriteBuffer = new BABYLON.Buffer(engine, spriteData, false, 4);
  57462. // Update VAO
  57463. this._updateVAO = [];
  57464. this._updateVAO.push(this._createUpdateVAO(this._buffer0));
  57465. this._updateVAO.push(this._createUpdateVAO(this._buffer1));
  57466. // Render VAO
  57467. this._renderVAO = [];
  57468. this._renderVAO.push(this._createRenderVAO(this._buffer1, this._spriteBuffer));
  57469. this._renderVAO.push(this._createRenderVAO(this._buffer0, this._spriteBuffer));
  57470. // Links
  57471. this._sourceBuffer = this._buffer0;
  57472. this._targetBuffer = this._buffer1;
  57473. };
  57474. /** @hidden */
  57475. GPUParticleSystem.prototype._recreateUpdateEffect = function () {
  57476. var defines = this.particleEmitterType ? this.particleEmitterType.getEffectDefines() : "";
  57477. if (this._updateEffect && this._updateEffectOptions.defines === defines) {
  57478. return;
  57479. }
  57480. this._updateEffectOptions.defines = defines;
  57481. this._updateEffect = new BABYLON.Effect("gpuUpdateParticles", this._updateEffectOptions, this._scene.getEngine());
  57482. };
  57483. /** @hidden */
  57484. GPUParticleSystem.prototype._recreateRenderEffect = function () {
  57485. var defines = "";
  57486. if (this._scene.clipPlane) {
  57487. defines = "\n#define CLIPPLANE";
  57488. }
  57489. if (this._renderEffect && this._renderEffect.defines === defines) {
  57490. return;
  57491. }
  57492. this._renderEffect = new BABYLON.Effect("gpuRenderParticles", ["position", "age", "life", "size", "color", "offset", "uv"], ["view", "projection", "colorDead", "invView", "vClipPlane"], ["textureSampler"], this._scene.getEngine(), defines);
  57493. };
  57494. /**
  57495. * Animates the particle system for the current frame by emitting new particles and or animating the living ones.
  57496. */
  57497. GPUParticleSystem.prototype.animate = function () {
  57498. this._timeDelta = this.updateSpeed * this._scene.getAnimationRatio();
  57499. this._actualFrame += this._timeDelta;
  57500. if (!this._stopped) {
  57501. if (this.targetStopDuration && this._actualFrame >= this.targetStopDuration) {
  57502. this.stop();
  57503. }
  57504. }
  57505. };
  57506. /**
  57507. * Renders the particle system in its current state.
  57508. * @returns the current number of particles
  57509. */
  57510. GPUParticleSystem.prototype.render = function () {
  57511. if (!this._started) {
  57512. return 0;
  57513. }
  57514. this._recreateUpdateEffect();
  57515. this._recreateRenderEffect();
  57516. if (!this.isReady()) {
  57517. return 0;
  57518. }
  57519. if (this._currentRenderId === this._scene.getRenderId()) {
  57520. return 0;
  57521. }
  57522. this._currentRenderId = this._scene.getRenderId();
  57523. // Get everything ready to render
  57524. this._initialize();
  57525. this._currentActiveCount = Math.min(this._activeCount, this._currentActiveCount + (this.emitRate * this._timeDelta) | 0);
  57526. // Enable update effect
  57527. this._engine.enableEffect(this._updateEffect);
  57528. this._engine.setState(false);
  57529. this._updateEffect.setFloat("currentCount", this._currentActiveCount);
  57530. this._updateEffect.setFloat("timeDelta", this._timeDelta);
  57531. this._updateEffect.setFloat("stopFactor", this._stopped ? 0 : 1);
  57532. this._updateEffect.setFloat3("generalRandoms", Math.random(), Math.random(), Math.random());
  57533. this._updateEffect.setTexture("randomSampler", this._randomTexture);
  57534. this._updateEffect.setFloat2("lifeTime", this.minLifeTime, this.maxLifeTime);
  57535. this._updateEffect.setFloat2("emitPower", this.minEmitPower, this.maxEmitPower);
  57536. this._updateEffect.setDirectColor4("color1", this.color1);
  57537. this._updateEffect.setDirectColor4("color2", this.color2);
  57538. this._updateEffect.setFloat2("sizeRange", this.minSize, this.maxSize);
  57539. this._updateEffect.setVector3("gravity", this.gravity);
  57540. if (this.particleEmitterType) {
  57541. this.particleEmitterType.applyToShader(this._updateEffect);
  57542. }
  57543. var emitterWM;
  57544. if (this.emitter.position) {
  57545. var emitterMesh = this.emitter;
  57546. emitterWM = emitterMesh.getWorldMatrix();
  57547. }
  57548. else {
  57549. var emitterPosition = this.emitter;
  57550. emitterWM = BABYLON.Matrix.Translation(emitterPosition.x, emitterPosition.y, emitterPosition.z);
  57551. }
  57552. this._updateEffect.setMatrix("emitterWM", emitterWM);
  57553. // Bind source VAO
  57554. this._engine.bindVertexArrayObject(this._updateVAO[this._targetIndex], null);
  57555. // Update
  57556. this._engine.bindTransformFeedbackBuffer(this._targetBuffer.getBuffer());
  57557. this._engine.setRasterizerState(false);
  57558. this._engine.beginTransformFeedback();
  57559. this._engine.drawArraysType(BABYLON.Material.PointListDrawMode, 0, this._currentActiveCount);
  57560. this._engine.endTransformFeedback();
  57561. this._engine.setRasterizerState(true);
  57562. this._engine.bindTransformFeedbackBuffer(null);
  57563. // Enable render effect
  57564. this._engine.enableEffect(this._renderEffect);
  57565. var viewMatrix = this._scene.getViewMatrix();
  57566. this._renderEffect.setMatrix("view", viewMatrix);
  57567. this._renderEffect.setMatrix("projection", this._scene.getProjectionMatrix());
  57568. this._renderEffect.setTexture("textureSampler", this.particleTexture);
  57569. this._renderEffect.setDirectColor4("colorDead", this.colorDead);
  57570. if (this._scene.clipPlane) {
  57571. var clipPlane = this._scene.clipPlane;
  57572. var invView = viewMatrix.clone();
  57573. invView.invert();
  57574. this._renderEffect.setMatrix("invView", invView);
  57575. this._renderEffect.setFloat4("vClipPlane", clipPlane.normal.x, clipPlane.normal.y, clipPlane.normal.z, clipPlane.d);
  57576. }
  57577. // Draw order
  57578. if (this.blendMode === BABYLON.ParticleSystem.BLENDMODE_ONEONE) {
  57579. this._engine.setAlphaMode(BABYLON.Engine.ALPHA_ONEONE);
  57580. }
  57581. else {
  57582. this._engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  57583. }
  57584. if (this.forceDepthWrite) {
  57585. this._engine.setDepthWrite(true);
  57586. }
  57587. // Bind source VAO
  57588. this._engine.bindVertexArrayObject(this._renderVAO[this._targetIndex], null);
  57589. // Render
  57590. this._engine.drawArraysType(BABYLON.Material.TriangleFanDrawMode, 0, 4, this._currentActiveCount);
  57591. this._engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  57592. // Switch VAOs
  57593. this._targetIndex++;
  57594. if (this._targetIndex === 2) {
  57595. this._targetIndex = 0;
  57596. }
  57597. // Switch buffers
  57598. var tmpBuffer = this._sourceBuffer;
  57599. this._sourceBuffer = this._targetBuffer;
  57600. this._targetBuffer = tmpBuffer;
  57601. return this._currentActiveCount;
  57602. };
  57603. /**
  57604. * Rebuilds the particle system
  57605. */
  57606. GPUParticleSystem.prototype.rebuild = function () {
  57607. this._initialize(true);
  57608. };
  57609. GPUParticleSystem.prototype._releaseBuffers = function () {
  57610. if (this._buffer0) {
  57611. this._buffer0.dispose();
  57612. this._buffer0 = null;
  57613. }
  57614. if (this._buffer1) {
  57615. this._buffer1.dispose();
  57616. this._buffer1 = null;
  57617. }
  57618. if (this._spriteBuffer) {
  57619. this._spriteBuffer.dispose();
  57620. this._spriteBuffer = null;
  57621. }
  57622. };
  57623. GPUParticleSystem.prototype._releaseVAOs = function () {
  57624. if (!this._updateVAO) {
  57625. return;
  57626. }
  57627. for (var index = 0; index < this._updateVAO.length; index++) {
  57628. this._engine.releaseVertexArrayObject(this._updateVAO[index]);
  57629. }
  57630. this._updateVAO = [];
  57631. for (var index = 0; index < this._renderVAO.length; index++) {
  57632. this._engine.releaseVertexArrayObject(this._renderVAO[index]);
  57633. }
  57634. this._renderVAO = [];
  57635. };
  57636. /**
  57637. * Disposes the particle system and free the associated resources
  57638. * @param disposeTexture defines if the particule texture must be disposed as well (true by default)
  57639. */
  57640. GPUParticleSystem.prototype.dispose = function (disposeTexture) {
  57641. if (disposeTexture === void 0) { disposeTexture = true; }
  57642. var index = this._scene.particleSystems.indexOf(this);
  57643. if (index > -1) {
  57644. this._scene.particleSystems.splice(index, 1);
  57645. }
  57646. this._releaseBuffers();
  57647. this._releaseVAOs();
  57648. if (this._randomTexture) {
  57649. this._randomTexture.dispose();
  57650. this._randomTexture = null;
  57651. }
  57652. if (disposeTexture && this.particleTexture) {
  57653. this.particleTexture.dispose();
  57654. this.particleTexture = null;
  57655. }
  57656. // Callback
  57657. this.onDisposeObservable.notifyObservers(this);
  57658. this.onDisposeObservable.clear();
  57659. };
  57660. /**
  57661. * Clones the particle system.
  57662. * @param name The name of the cloned object
  57663. * @param newEmitter The new emitter to use
  57664. * @returns the cloned particle system
  57665. */
  57666. GPUParticleSystem.prototype.clone = function (name, newEmitter) {
  57667. var result = new GPUParticleSystem(name, { capacity: this._capacity, randomTextureSize: this._randomTextureSize }, this._scene);
  57668. BABYLON.Tools.DeepCopy(this, result);
  57669. if (newEmitter === undefined) {
  57670. newEmitter = this.emitter;
  57671. }
  57672. result.emitter = newEmitter;
  57673. if (this.particleTexture) {
  57674. result.particleTexture = new BABYLON.Texture(this.particleTexture.url, this._scene);
  57675. }
  57676. return result;
  57677. };
  57678. /**
  57679. * Serializes the particle system to a JSON object.
  57680. * @returns the JSON object
  57681. */
  57682. GPUParticleSystem.prototype.serialize = function () {
  57683. var serializationObject = {};
  57684. serializationObject.name = this.name;
  57685. serializationObject.id = this.id;
  57686. // Emitter
  57687. if (this.emitter.position) {
  57688. var emitterMesh = this.emitter;
  57689. serializationObject.emitterId = emitterMesh.id;
  57690. }
  57691. else {
  57692. var emitterPosition = this.emitter;
  57693. serializationObject.emitter = emitterPosition.asArray();
  57694. }
  57695. serializationObject.capacity = this.getCapacity();
  57696. if (this.particleTexture) {
  57697. serializationObject.textureName = this.particleTexture.name;
  57698. }
  57699. // Animations
  57700. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  57701. // Particle system
  57702. serializationObject.activeParticleCount = this.activeParticleCount;
  57703. serializationObject.randomTextureSize = this._randomTextureSize;
  57704. serializationObject.minSize = this.minSize;
  57705. serializationObject.maxSize = this.maxSize;
  57706. serializationObject.minEmitPower = this.minEmitPower;
  57707. serializationObject.maxEmitPower = this.maxEmitPower;
  57708. serializationObject.minLifeTime = this.minLifeTime;
  57709. serializationObject.maxLifeTime = this.maxLifeTime;
  57710. serializationObject.emitRate = this.emitRate;
  57711. serializationObject.gravity = this.gravity.asArray();
  57712. serializationObject.color1 = this.color1.asArray();
  57713. serializationObject.color2 = this.color2.asArray();
  57714. serializationObject.colorDead = this.colorDead.asArray();
  57715. serializationObject.updateSpeed = this.updateSpeed;
  57716. serializationObject.targetStopDuration = this.targetStopDuration;
  57717. serializationObject.blendMode = this.blendMode;
  57718. // Emitter
  57719. if (this.particleEmitterType) {
  57720. serializationObject.particleEmitterType = this.particleEmitterType.serialize();
  57721. }
  57722. return serializationObject;
  57723. };
  57724. /**
  57725. * Parses a JSON object to create a GPU particle system.
  57726. * @param parsedParticleSystem The JSON object to parse
  57727. * @param scene The scene to create the particle system in
  57728. * @param rootUrl The root url to use to load external dependencies like texture
  57729. * @returns the parsed GPU particle system
  57730. */
  57731. GPUParticleSystem.Parse = function (parsedParticleSystem, scene, rootUrl) {
  57732. var name = parsedParticleSystem.name;
  57733. var particleSystem = new GPUParticleSystem(name, { capacity: parsedParticleSystem.capacity, randomTextureSize: parsedParticleSystem.randomTextureSize }, scene);
  57734. if (parsedParticleSystem.id) {
  57735. particleSystem.id = parsedParticleSystem.id;
  57736. }
  57737. // Texture
  57738. if (parsedParticleSystem.textureName) {
  57739. particleSystem.particleTexture = new BABYLON.Texture(rootUrl + parsedParticleSystem.textureName, scene);
  57740. particleSystem.particleTexture.name = parsedParticleSystem.textureName;
  57741. }
  57742. // Emitter
  57743. if (parsedParticleSystem.emitterId) {
  57744. particleSystem.emitter = scene.getLastMeshByID(parsedParticleSystem.emitterId);
  57745. }
  57746. else {
  57747. particleSystem.emitter = BABYLON.Vector3.FromArray(parsedParticleSystem.emitter);
  57748. }
  57749. // Animations
  57750. if (parsedParticleSystem.animations) {
  57751. for (var animationIndex = 0; animationIndex < parsedParticleSystem.animations.length; animationIndex++) {
  57752. var parsedAnimation = parsedParticleSystem.animations[animationIndex];
  57753. particleSystem.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  57754. }
  57755. }
  57756. // Particle system
  57757. particleSystem.activeParticleCount = parsedParticleSystem.activeParticleCount;
  57758. particleSystem.minSize = parsedParticleSystem.minSize;
  57759. particleSystem.maxSize = parsedParticleSystem.maxSize;
  57760. particleSystem.minLifeTime = parsedParticleSystem.minLifeTime;
  57761. particleSystem.maxLifeTime = parsedParticleSystem.maxLifeTime;
  57762. particleSystem.minEmitPower = parsedParticleSystem.minEmitPower;
  57763. particleSystem.maxEmitPower = parsedParticleSystem.maxEmitPower;
  57764. particleSystem.emitRate = parsedParticleSystem.emitRate;
  57765. particleSystem.gravity = BABYLON.Vector3.FromArray(parsedParticleSystem.gravity);
  57766. particleSystem.color1 = BABYLON.Color4.FromArray(parsedParticleSystem.color1);
  57767. particleSystem.color2 = BABYLON.Color4.FromArray(parsedParticleSystem.color2);
  57768. particleSystem.colorDead = BABYLON.Color4.FromArray(parsedParticleSystem.colorDead);
  57769. particleSystem.updateSpeed = parsedParticleSystem.updateSpeed;
  57770. particleSystem.targetStopDuration = parsedParticleSystem.targetStopDuration;
  57771. particleSystem.blendMode = parsedParticleSystem.blendMode;
  57772. // Emitter
  57773. if (parsedParticleSystem.particleEmitterType) {
  57774. var emitterType = void 0;
  57775. switch (parsedParticleSystem.particleEmitterType.type) {
  57776. case "SphereEmitter":
  57777. emitterType = new BABYLON.SphereParticleEmitter();
  57778. break;
  57779. case "SphereDirectedParticleEmitter":
  57780. emitterType = new BABYLON.SphereDirectedParticleEmitter();
  57781. break;
  57782. case "ConeEmitter":
  57783. emitterType = new BABYLON.ConeParticleEmitter();
  57784. break;
  57785. case "BoxEmitter":
  57786. default:
  57787. emitterType = new BABYLON.BoxParticleEmitter();
  57788. break;
  57789. }
  57790. emitterType.parse(parsedParticleSystem.particleEmitterType);
  57791. particleSystem.particleEmitterType = emitterType;
  57792. }
  57793. return particleSystem;
  57794. };
  57795. return GPUParticleSystem;
  57796. }());
  57797. BABYLON.GPUParticleSystem = GPUParticleSystem;
  57798. })(BABYLON || (BABYLON = {}));
  57799. //# sourceMappingURL=babylon.gpuParticleSystem.js.map
  57800. var BABYLON;
  57801. (function (BABYLON) {
  57802. /**
  57803. * Represents one particle of a solid particle system.
  57804. */
  57805. var SolidParticle = /** @class */ (function () {
  57806. /**
  57807. * Creates a Solid Particle object.
  57808. * Don't create particles manually, use instead the Solid Particle System internal tools like _addParticle()
  57809. * @param particleIndex (integer) is the particle index in the Solid Particle System pool. It's also the particle identifier.
  57810. * @param positionIndex (integer) is the starting index of the particle vertices in the SPS "positions" array.
  57811. * @param indiceIndex (integer) is the starting index of the particle indices in the SPS "indices" array.
  57812. * @param model (ModelShape) is a reference to the model shape on what the particle is designed.
  57813. * @param shapeId (integer) is the model shape identifier in the SPS.
  57814. * @param idxInShape (integer) is the index of the particle in the current model (ex: the 10th box of addShape(box, 30))
  57815. * @param modelBoundingInfo is the reference to the model BoundingInfo used for intersection computations.
  57816. */
  57817. function SolidParticle(particleIndex, positionIndex, indiceIndex, model, shapeId, idxInShape, sps, modelBoundingInfo) {
  57818. if (modelBoundingInfo === void 0) { modelBoundingInfo = null; }
  57819. /**
  57820. * particle global index
  57821. */
  57822. this.idx = 0;
  57823. /**
  57824. * The color of the particle
  57825. */
  57826. this.color = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  57827. /**
  57828. * The world space position of the particle.
  57829. */
  57830. this.position = BABYLON.Vector3.Zero();
  57831. /**
  57832. * The world space rotation of the particle. (Not use if rotationQuaternion is set)
  57833. */
  57834. this.rotation = BABYLON.Vector3.Zero();
  57835. /**
  57836. * The scaling of the particle.
  57837. */
  57838. this.scaling = BABYLON.Vector3.One();
  57839. /**
  57840. * The uvs of the particle.
  57841. */
  57842. this.uvs = new BABYLON.Vector4(0.0, 0.0, 1.0, 1.0);
  57843. /**
  57844. * The current speed of the particle.
  57845. */
  57846. this.velocity = BABYLON.Vector3.Zero();
  57847. /**
  57848. * The pivot point in the particle local space.
  57849. */
  57850. this.pivot = BABYLON.Vector3.Zero();
  57851. /**
  57852. * Must the particle be translated from its pivot point in its local space ?
  57853. * In this case, the pivot point is set at the origin of the particle local space and the particle is translated.
  57854. * Default : false
  57855. */
  57856. this.translateFromPivot = false;
  57857. /**
  57858. * Is the particle active or not ?
  57859. */
  57860. this.alive = true;
  57861. /**
  57862. * Is the particle visible or not ?
  57863. */
  57864. this.isVisible = true;
  57865. /**
  57866. * Index of this particle in the global "positions" array (Internal use)
  57867. */
  57868. this._pos = 0;
  57869. /**
  57870. * Index of this particle in the global "indices" array (Internal use)
  57871. */
  57872. this._ind = 0;
  57873. /**
  57874. * ModelShape id of this particle
  57875. */
  57876. this.shapeId = 0;
  57877. /**
  57878. * Index of the particle in its shape id (Internal use)
  57879. */
  57880. this.idxInShape = 0;
  57881. /**
  57882. * Still set as invisible in order to skip useless computations (Internal use)
  57883. */
  57884. this._stillInvisible = false;
  57885. /**
  57886. * Last computed particle rotation matrix
  57887. */
  57888. this._rotationMatrix = [1.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 1.0];
  57889. /**
  57890. * Parent particle Id, if any.
  57891. * Default null.
  57892. */
  57893. this.parentId = null;
  57894. /**
  57895. * Internal global position in the SPS.
  57896. */
  57897. this._globalPosition = BABYLON.Vector3.Zero();
  57898. this.idx = particleIndex;
  57899. this._pos = positionIndex;
  57900. this._ind = indiceIndex;
  57901. this._model = model;
  57902. this.shapeId = shapeId;
  57903. this.idxInShape = idxInShape;
  57904. this._sps = sps;
  57905. if (modelBoundingInfo) {
  57906. this._modelBoundingInfo = modelBoundingInfo;
  57907. this._boundingInfo = new BABYLON.BoundingInfo(modelBoundingInfo.minimum, modelBoundingInfo.maximum);
  57908. }
  57909. }
  57910. Object.defineProperty(SolidParticle.prototype, "scale", {
  57911. /**
  57912. * Legacy support, changed scale to scaling
  57913. */
  57914. get: function () {
  57915. return this.scaling;
  57916. },
  57917. /**
  57918. * Legacy support, changed scale to scaling
  57919. */
  57920. set: function (scale) {
  57921. this.scaling = scale;
  57922. },
  57923. enumerable: true,
  57924. configurable: true
  57925. });
  57926. Object.defineProperty(SolidParticle.prototype, "quaternion", {
  57927. /**
  57928. * Legacy support, changed quaternion to rotationQuaternion
  57929. */
  57930. get: function () {
  57931. return this.rotationQuaternion;
  57932. },
  57933. /**
  57934. * Legacy support, changed quaternion to rotationQuaternion
  57935. */
  57936. set: function (q) {
  57937. this.rotationQuaternion = q;
  57938. },
  57939. enumerable: true,
  57940. configurable: true
  57941. });
  57942. /**
  57943. * Returns a boolean. True if the particle intersects another particle or another mesh, else false.
  57944. * The intersection is computed on the particle bounding sphere and Axis Aligned Bounding Box (AABB)
  57945. * @param target is the object (solid particle or mesh) what the intersection is computed against.
  57946. * @returns true if it intersects
  57947. */
  57948. SolidParticle.prototype.intersectsMesh = function (target) {
  57949. if (!this._boundingInfo || !target._boundingInfo) {
  57950. return false;
  57951. }
  57952. if (this._sps._bSphereOnly) {
  57953. return BABYLON.BoundingSphere.Intersects(this._boundingInfo.boundingSphere, target._boundingInfo.boundingSphere);
  57954. }
  57955. return this._boundingInfo.intersects(target._boundingInfo, false);
  57956. };
  57957. return SolidParticle;
  57958. }());
  57959. BABYLON.SolidParticle = SolidParticle;
  57960. /**
  57961. * Represents the shape of the model used by one particle of a solid particle system.
  57962. * SPS internal tool, don't use it manually.
  57963. */
  57964. var ModelShape = /** @class */ (function () {
  57965. /**
  57966. * 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.
  57967. * SPS internal tool, don't use it manually.
  57968. * @hidden
  57969. */
  57970. function ModelShape(id, shape, indicesLength, shapeUV, posFunction, vtxFunction) {
  57971. /**
  57972. * length of the shape in the model indices array (internal use)
  57973. */
  57974. this._indicesLength = 0;
  57975. this.shapeID = id;
  57976. this._shape = shape;
  57977. this._indicesLength = indicesLength;
  57978. this._shapeUV = shapeUV;
  57979. this._positionFunction = posFunction;
  57980. this._vertexFunction = vtxFunction;
  57981. }
  57982. return ModelShape;
  57983. }());
  57984. BABYLON.ModelShape = ModelShape;
  57985. /**
  57986. * Represents a Depth Sorted Particle in the solid particle system.
  57987. */
  57988. var DepthSortedParticle = /** @class */ (function () {
  57989. function DepthSortedParticle() {
  57990. /**
  57991. * Index of the particle in the "indices" array
  57992. */
  57993. this.ind = 0;
  57994. /**
  57995. * Length of the particle shape in the "indices" array
  57996. */
  57997. this.indicesLength = 0;
  57998. /**
  57999. * Squared distance from the particle to the camera
  58000. */
  58001. this.sqDistance = 0.0;
  58002. }
  58003. return DepthSortedParticle;
  58004. }());
  58005. BABYLON.DepthSortedParticle = DepthSortedParticle;
  58006. })(BABYLON || (BABYLON = {}));
  58007. //# sourceMappingURL=babylon.solidParticle.js.map
  58008. var BABYLON;
  58009. (function (BABYLON) {
  58010. /**
  58011. * The SPS is a single updatable mesh. The solid particles are simply separate parts or faces fo this big mesh.
  58012. *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.
  58013. * The SPS is also a particle system. It provides some methods to manage the particles.
  58014. * However it is behavior agnostic. This means it has no emitter, no particle physics, no particle recycler. You have to implement your own behavior.
  58015. *
  58016. * Full documentation here : http://doc.babylonjs.com/overviews/Solid_Particle_System
  58017. */
  58018. var SolidParticleSystem = /** @class */ (function () {
  58019. /**
  58020. * Creates a SPS (Solid Particle System) object.
  58021. * @param name (String) is the SPS name, this will be the underlying mesh name.
  58022. * @param scene (Scene) is the scene in which the SPS is added.
  58023. * @param updatable (optional boolean, default true) : if the SPS must be updatable or immutable.
  58024. * @param isPickable (optional boolean, default false) : if the solid particles must be pickable.
  58025. * @param enableDepthSort (optional boolean, default false) : if the solid particles must be sorted in the geometry according to their distance to the camera.
  58026. * @param particleIntersection (optional boolean, default false) : if the solid particle intersections must be computed.
  58027. * @param boundingSphereOnly (optional boolean, default false) : if the particle intersection must be computed only with the bounding sphere (no bounding box computation, so faster).
  58028. * @param bSphereRadiusFactor (optional float, default 1.0) : a number to multiply the boundind sphere radius by in order to reduce it for instance.
  58029. * @example bSphereRadiusFactor = 1.0 / Math.sqrt(3.0) => the bounding sphere exactly matches a spherical mesh.
  58030. */
  58031. function SolidParticleSystem(name, scene, options) {
  58032. /**
  58033. * The SPS array of Solid Particle objects. Just access each particle as with any classic array.
  58034. * Example : var p = SPS.particles[i];
  58035. */
  58036. this.particles = new Array();
  58037. /**
  58038. * The SPS total number of particles. Read only. Use SPS.counter instead if you need to set your own value.
  58039. */
  58040. this.nbParticles = 0;
  58041. /**
  58042. * If the particles must ever face the camera (default false). Useful for planar particles.
  58043. */
  58044. this.billboard = false;
  58045. /**
  58046. * Recompute normals when adding a shape
  58047. */
  58048. this.recomputeNormals = true;
  58049. /**
  58050. * This a counter ofr your own usage. It's not set by any SPS functions.
  58051. */
  58052. this.counter = 0;
  58053. /**
  58054. * This empty object is intended to store some SPS specific or temporary values in order to lower the Garbage Collector activity.
  58055. * Please read : http://doc.babylonjs.com/overviews/Solid_Particle_System#garbage-collector-concerns
  58056. */
  58057. this.vars = {};
  58058. /**
  58059. * If the particle intersection must be computed only with the bounding sphere (no bounding box computation, so faster). (Internal use only)
  58060. */
  58061. this._bSphereOnly = false;
  58062. /**
  58063. * A number to multiply the boundind sphere radius by in order to reduce it for instance. (Internal use only)
  58064. */
  58065. this._bSphereRadiusFactor = 1.0;
  58066. this._positions = new Array();
  58067. this._indices = new Array();
  58068. this._normals = new Array();
  58069. this._colors = new Array();
  58070. this._uvs = new Array();
  58071. this._index = 0; // indices index
  58072. this._updatable = true;
  58073. this._pickable = false;
  58074. this._isVisibilityBoxLocked = false;
  58075. this._alwaysVisible = false;
  58076. this._depthSort = false;
  58077. this._shapeCounter = 0;
  58078. this._copy = new BABYLON.SolidParticle(0, 0, 0, null, 0, 0, this);
  58079. this._color = new BABYLON.Color4(0, 0, 0, 0);
  58080. this._computeParticleColor = true;
  58081. this._computeParticleTexture = true;
  58082. this._computeParticleRotation = true;
  58083. this._computeParticleVertex = false;
  58084. this._computeBoundingBox = false;
  58085. this._depthSortParticles = true;
  58086. this._cam_axisZ = BABYLON.Vector3.Zero();
  58087. this._cam_axisY = BABYLON.Vector3.Zero();
  58088. this._cam_axisX = BABYLON.Vector3.Zero();
  58089. this._axisZ = BABYLON.Axis.Z;
  58090. this._camDir = BABYLON.Vector3.Zero();
  58091. this._camInvertedPosition = BABYLON.Vector3.Zero();
  58092. this._rotMatrix = new BABYLON.Matrix();
  58093. this._invertMatrix = new BABYLON.Matrix();
  58094. this._rotated = BABYLON.Vector3.Zero();
  58095. this._quaternion = new BABYLON.Quaternion();
  58096. this._vertex = BABYLON.Vector3.Zero();
  58097. this._normal = BABYLON.Vector3.Zero();
  58098. this._yaw = 0.0;
  58099. this._pitch = 0.0;
  58100. this._roll = 0.0;
  58101. this._halfroll = 0.0;
  58102. this._halfpitch = 0.0;
  58103. this._halfyaw = 0.0;
  58104. this._sinRoll = 0.0;
  58105. this._cosRoll = 0.0;
  58106. this._sinPitch = 0.0;
  58107. this._cosPitch = 0.0;
  58108. this._sinYaw = 0.0;
  58109. this._cosYaw = 0.0;
  58110. this._mustUnrotateFixedNormals = false;
  58111. this._minimum = BABYLON.Vector3.Zero();
  58112. this._maximum = BABYLON.Vector3.Zero();
  58113. this._minBbox = BABYLON.Vector3.Zero();
  58114. this._maxBbox = BABYLON.Vector3.Zero();
  58115. this._particlesIntersect = false;
  58116. this._depthSortFunction = function (p1, p2) {
  58117. return (p2.sqDistance - p1.sqDistance);
  58118. };
  58119. this._needs32Bits = false;
  58120. this._pivotBackTranslation = BABYLON.Vector3.Zero();
  58121. this._scaledPivot = BABYLON.Vector3.Zero();
  58122. this._particleHasParent = false;
  58123. this.name = name;
  58124. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  58125. this._camera = scene.activeCamera;
  58126. this._pickable = options ? options.isPickable : false;
  58127. this._depthSort = options ? options.enableDepthSort : false;
  58128. this._particlesIntersect = options ? options.particleIntersection : false;
  58129. this._bSphereOnly = options ? options.boundingSphereOnly : false;
  58130. this._bSphereRadiusFactor = (options && options.bSphereRadiusFactor) ? options.bSphereRadiusFactor : 1.0;
  58131. if (options && options.updatable) {
  58132. this._updatable = options.updatable;
  58133. }
  58134. else {
  58135. this._updatable = true;
  58136. }
  58137. if (this._pickable) {
  58138. this.pickedParticles = [];
  58139. }
  58140. if (this._depthSort) {
  58141. this.depthSortedParticles = [];
  58142. }
  58143. }
  58144. /**
  58145. * Builds the SPS underlying mesh. Returns a standard Mesh.
  58146. * If no model shape was added to the SPS, the returned mesh is just a single triangular plane.
  58147. * @returns the created mesh
  58148. */
  58149. SolidParticleSystem.prototype.buildMesh = function () {
  58150. if (this.nbParticles === 0) {
  58151. var triangle = BABYLON.MeshBuilder.CreateDisc("", { radius: 1, tessellation: 3 }, this._scene);
  58152. this.addShape(triangle, 1);
  58153. triangle.dispose();
  58154. }
  58155. this._indices32 = (this._needs32Bits) ? new Uint32Array(this._indices) : new Uint16Array(this._indices);
  58156. this._positions32 = new Float32Array(this._positions);
  58157. this._uvs32 = new Float32Array(this._uvs);
  58158. this._colors32 = new Float32Array(this._colors);
  58159. if (this.recomputeNormals) {
  58160. BABYLON.VertexData.ComputeNormals(this._positions32, this._indices32, this._normals);
  58161. }
  58162. this._normals32 = new Float32Array(this._normals);
  58163. this._fixedNormal32 = new Float32Array(this._normals);
  58164. if (this._mustUnrotateFixedNormals) { // the particles could be created already rotated in the mesh with a positionFunction
  58165. this._unrotateFixedNormals();
  58166. }
  58167. var vertexData = new BABYLON.VertexData();
  58168. vertexData.indices = (this._depthSort) ? this._indices : this._indices32;
  58169. vertexData.set(this._positions32, BABYLON.VertexBuffer.PositionKind);
  58170. vertexData.set(this._normals32, BABYLON.VertexBuffer.NormalKind);
  58171. if (this._uvs32) {
  58172. vertexData.set(this._uvs32, BABYLON.VertexBuffer.UVKind);
  58173. ;
  58174. }
  58175. if (this._colors32) {
  58176. vertexData.set(this._colors32, BABYLON.VertexBuffer.ColorKind);
  58177. }
  58178. var mesh = new BABYLON.Mesh(this.name, this._scene);
  58179. vertexData.applyToMesh(mesh, this._updatable);
  58180. this.mesh = mesh;
  58181. this.mesh.isPickable = this._pickable;
  58182. // free memory
  58183. if (!this._depthSort) {
  58184. this._indices = null;
  58185. }
  58186. this._positions = null;
  58187. this._normals = null;
  58188. this._uvs = null;
  58189. this._colors = null;
  58190. if (!this._updatable) {
  58191. this.particles.length = 0;
  58192. }
  58193. return mesh;
  58194. };
  58195. /**
  58196. * Digests the mesh and generates as many solid particles in the system as wanted. Returns the SPS.
  58197. * These particles will have the same geometry than the mesh parts and will be positioned at the same localisation than the mesh original places.
  58198. * Thus the particles generated from `digest()` have their property `position` set yet.
  58199. * @param mesh ( Mesh ) is the mesh to be digested
  58200. * @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
  58201. * {delta} (optional integer, default 0) is the random extra number of facets per particle , each particle will have between `facetNb` and `facetNb + delta` facets
  58202. * {number} (optional positive integer) is the wanted number of particles : each particle is built with `mesh_total_facets / number` facets
  58203. * @returns the current SPS
  58204. */
  58205. SolidParticleSystem.prototype.digest = function (mesh, options) {
  58206. var size = (options && options.facetNb) || 1;
  58207. var number = (options && options.number) || 0;
  58208. var delta = (options && options.delta) || 0;
  58209. var meshPos = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  58210. var meshInd = mesh.getIndices();
  58211. var meshUV = mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  58212. var meshCol = mesh.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  58213. var meshNor = mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  58214. var f = 0; // facet counter
  58215. var totalFacets = meshInd.length / 3; // a facet is a triangle, so 3 indices
  58216. // compute size from number
  58217. if (number) {
  58218. number = (number > totalFacets) ? totalFacets : number;
  58219. size = Math.round(totalFacets / number);
  58220. delta = 0;
  58221. }
  58222. else {
  58223. size = (size > totalFacets) ? totalFacets : size;
  58224. }
  58225. var facetPos = []; // submesh positions
  58226. var facetInd = []; // submesh indices
  58227. var facetUV = []; // submesh UV
  58228. var facetCol = []; // submesh colors
  58229. var barycenter = BABYLON.Vector3.Zero();
  58230. var sizeO = size;
  58231. while (f < totalFacets) {
  58232. size = sizeO + Math.floor((1 + delta) * Math.random());
  58233. if (f > totalFacets - size) {
  58234. size = totalFacets - f;
  58235. }
  58236. // reset temp arrays
  58237. facetPos.length = 0;
  58238. facetInd.length = 0;
  58239. facetUV.length = 0;
  58240. facetCol.length = 0;
  58241. // iterate over "size" facets
  58242. var fi = 0;
  58243. for (var j = f * 3; j < (f + size) * 3; j++) {
  58244. facetInd.push(fi);
  58245. var i = meshInd[j];
  58246. facetPos.push(meshPos[i * 3], meshPos[i * 3 + 1], meshPos[i * 3 + 2]);
  58247. if (meshUV) {
  58248. facetUV.push(meshUV[i * 2], meshUV[i * 2 + 1]);
  58249. }
  58250. if (meshCol) {
  58251. facetCol.push(meshCol[i * 4], meshCol[i * 4 + 1], meshCol[i * 4 + 2], meshCol[i * 4 + 3]);
  58252. }
  58253. fi++;
  58254. }
  58255. // create a model shape for each single particle
  58256. var idx = this.nbParticles;
  58257. var shape = this._posToShape(facetPos);
  58258. var shapeUV = this._uvsToShapeUV(facetUV);
  58259. // compute the barycenter of the shape
  58260. var v;
  58261. for (v = 0; v < shape.length; v++) {
  58262. barycenter.addInPlace(shape[v]);
  58263. }
  58264. barycenter.scaleInPlace(1 / shape.length);
  58265. // shift the shape from its barycenter to the origin
  58266. for (v = 0; v < shape.length; v++) {
  58267. shape[v].subtractInPlace(barycenter);
  58268. }
  58269. var bInfo;
  58270. if (this._particlesIntersect) {
  58271. bInfo = new BABYLON.BoundingInfo(barycenter, barycenter);
  58272. }
  58273. var modelShape = new BABYLON.ModelShape(this._shapeCounter, shape, size * 3, shapeUV, null, null);
  58274. // add the particle in the SPS
  58275. var currentPos = this._positions.length;
  58276. var currentInd = this._indices.length;
  58277. this._meshBuilder(this._index, shape, this._positions, facetInd, this._indices, facetUV, this._uvs, facetCol, this._colors, meshNor, this._normals, idx, 0, null);
  58278. this._addParticle(idx, currentPos, currentInd, modelShape, this._shapeCounter, 0, bInfo);
  58279. // initialize the particle position
  58280. this.particles[this.nbParticles].position.addInPlace(barycenter);
  58281. this._index += shape.length;
  58282. idx++;
  58283. this.nbParticles++;
  58284. this._shapeCounter++;
  58285. f += size;
  58286. }
  58287. return this;
  58288. };
  58289. // unrotate the fixed normals in case the mesh was built with pre-rotated particles, ex : use of positionFunction in addShape()
  58290. SolidParticleSystem.prototype._unrotateFixedNormals = function () {
  58291. var index = 0;
  58292. var idx = 0;
  58293. for (var p = 0; p < this.particles.length; p++) {
  58294. this._particle = this.particles[p];
  58295. this._shape = this._particle._model._shape;
  58296. if (this._particle.rotationQuaternion) {
  58297. this._quaternion.copyFrom(this._particle.rotationQuaternion);
  58298. }
  58299. else {
  58300. this._yaw = this._particle.rotation.y;
  58301. this._pitch = this._particle.rotation.x;
  58302. this._roll = this._particle.rotation.z;
  58303. this._quaternionRotationYPR();
  58304. }
  58305. this._quaternionToRotationMatrix();
  58306. this._rotMatrix.invertToRef(this._invertMatrix);
  58307. for (var pt = 0; pt < this._shape.length; pt++) {
  58308. idx = index + pt * 3;
  58309. BABYLON.Vector3.TransformNormalFromFloatsToRef(this._normals32[idx], this._normals32[idx + 1], this._normals32[idx + 2], this._invertMatrix, this._normal);
  58310. this._fixedNormal32[idx] = this._normal.x;
  58311. this._fixedNormal32[idx + 1] = this._normal.y;
  58312. this._fixedNormal32[idx + 2] = this._normal.z;
  58313. }
  58314. index = idx + 3;
  58315. }
  58316. };
  58317. //reset copy
  58318. SolidParticleSystem.prototype._resetCopy = function () {
  58319. this._copy.position.x = 0;
  58320. this._copy.position.y = 0;
  58321. this._copy.position.z = 0;
  58322. this._copy.rotation.x = 0;
  58323. this._copy.rotation.y = 0;
  58324. this._copy.rotation.z = 0;
  58325. this._copy.rotationQuaternion = null;
  58326. this._copy.scaling.x = 1.0;
  58327. this._copy.scaling.y = 1.0;
  58328. this._copy.scaling.z = 1.0;
  58329. this._copy.uvs.x = 0;
  58330. this._copy.uvs.y = 0;
  58331. this._copy.uvs.z = 1.0;
  58332. this._copy.uvs.w = 1.0;
  58333. this._copy.color = null;
  58334. this._copy.translateFromPivot = false;
  58335. };
  58336. // _meshBuilder : inserts the shape model in the global SPS mesh
  58337. SolidParticleSystem.prototype._meshBuilder = function (p, shape, positions, meshInd, indices, meshUV, uvs, meshCol, colors, meshNor, normals, idx, idxInShape, options) {
  58338. var i;
  58339. var u = 0;
  58340. var c = 0;
  58341. var n = 0;
  58342. this._resetCopy();
  58343. if (options && options.positionFunction) { // call to custom positionFunction
  58344. options.positionFunction(this._copy, idx, idxInShape);
  58345. this._mustUnrotateFixedNormals = true;
  58346. }
  58347. if (this._copy.rotationQuaternion) {
  58348. this._quaternion.copyFrom(this._copy.rotationQuaternion);
  58349. }
  58350. else {
  58351. this._yaw = this._copy.rotation.y;
  58352. this._pitch = this._copy.rotation.x;
  58353. this._roll = this._copy.rotation.z;
  58354. this._quaternionRotationYPR();
  58355. }
  58356. this._quaternionToRotationMatrix();
  58357. this._scaledPivot.x = this._copy.pivot.x * this._copy.scaling.x;
  58358. this._scaledPivot.y = this._copy.pivot.y * this._copy.scaling.y;
  58359. this._scaledPivot.z = this._copy.pivot.z * this._copy.scaling.z;
  58360. if (this._copy.translateFromPivot) {
  58361. this._pivotBackTranslation.copyFromFloats(0.0, 0.0, 0.0);
  58362. }
  58363. else {
  58364. this._pivotBackTranslation.copyFrom(this._scaledPivot);
  58365. }
  58366. for (i = 0; i < shape.length; i++) {
  58367. this._vertex.x = shape[i].x;
  58368. this._vertex.y = shape[i].y;
  58369. this._vertex.z = shape[i].z;
  58370. if (options && options.vertexFunction) {
  58371. options.vertexFunction(this._copy, this._vertex, i);
  58372. }
  58373. this._vertex.x *= this._copy.scaling.x;
  58374. this._vertex.y *= this._copy.scaling.y;
  58375. this._vertex.z *= this._copy.scaling.z;
  58376. this._vertex.x -= this._scaledPivot.x;
  58377. this._vertex.y -= this._scaledPivot.y;
  58378. this._vertex.z -= this._scaledPivot.z;
  58379. BABYLON.Vector3.TransformCoordinatesToRef(this._vertex, this._rotMatrix, this._rotated);
  58380. this._rotated.addInPlace(this._pivotBackTranslation);
  58381. positions.push(this._copy.position.x + this._rotated.x, this._copy.position.y + this._rotated.y, this._copy.position.z + this._rotated.z);
  58382. if (meshUV) {
  58383. 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);
  58384. u += 2;
  58385. }
  58386. if (this._copy.color) {
  58387. this._color = this._copy.color;
  58388. }
  58389. else if (meshCol && meshCol[c] !== undefined) {
  58390. this._color.r = meshCol[c];
  58391. this._color.g = meshCol[c + 1];
  58392. this._color.b = meshCol[c + 2];
  58393. this._color.a = meshCol[c + 3];
  58394. }
  58395. else {
  58396. this._color.r = 1.0;
  58397. this._color.g = 1.0;
  58398. this._color.b = 1.0;
  58399. this._color.a = 1.0;
  58400. }
  58401. colors.push(this._color.r, this._color.g, this._color.b, this._color.a);
  58402. c += 4;
  58403. if (!this.recomputeNormals && meshNor) {
  58404. this._normal.x = meshNor[n];
  58405. this._normal.y = meshNor[n + 1];
  58406. this._normal.z = meshNor[n + 2];
  58407. BABYLON.Vector3.TransformNormalToRef(this._normal, this._rotMatrix, this._normal);
  58408. normals.push(this._normal.x, this._normal.y, this._normal.z);
  58409. n += 3;
  58410. }
  58411. }
  58412. for (i = 0; i < meshInd.length; i++) {
  58413. var current_ind = p + meshInd[i];
  58414. indices.push(current_ind);
  58415. if (current_ind > 65535) {
  58416. this._needs32Bits = true;
  58417. }
  58418. }
  58419. if (this._pickable) {
  58420. var nbfaces = meshInd.length / 3;
  58421. for (i = 0; i < nbfaces; i++) {
  58422. this.pickedParticles.push({ idx: idx, faceId: i });
  58423. }
  58424. }
  58425. if (this._depthSort) {
  58426. this.depthSortedParticles.push(new BABYLON.DepthSortedParticle());
  58427. }
  58428. return this._copy;
  58429. };
  58430. // returns a shape array from positions array
  58431. SolidParticleSystem.prototype._posToShape = function (positions) {
  58432. var shape = [];
  58433. for (var i = 0; i < positions.length; i += 3) {
  58434. shape.push(new BABYLON.Vector3(positions[i], positions[i + 1], positions[i + 2]));
  58435. }
  58436. return shape;
  58437. };
  58438. // returns a shapeUV array from a Vector4 uvs
  58439. SolidParticleSystem.prototype._uvsToShapeUV = function (uvs) {
  58440. var shapeUV = [];
  58441. if (uvs) {
  58442. for (var i = 0; i < uvs.length; i++)
  58443. shapeUV.push(uvs[i]);
  58444. }
  58445. return shapeUV;
  58446. };
  58447. // adds a new particle object in the particles array
  58448. SolidParticleSystem.prototype._addParticle = function (idx, idxpos, idxind, model, shapeId, idxInShape, bInfo) {
  58449. if (bInfo === void 0) { bInfo = null; }
  58450. var sp = new BABYLON.SolidParticle(idx, idxpos, idxind, model, shapeId, idxInShape, this, bInfo);
  58451. this.particles.push(sp);
  58452. return sp;
  58453. };
  58454. /**
  58455. * Adds some particles to the SPS from the model shape. Returns the shape id.
  58456. * Please read the doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#create-an-immutable-sps
  58457. * @param mesh is any Mesh object that will be used as a model for the solid particles.
  58458. * @param nb (positive integer) the number of particles to be created from this model
  58459. * @param options {positionFunction} is an optional javascript function to called for each particle on SPS creation.
  58460. * {vertexFunction} is an optional javascript function to called for each vertex of each particle on SPS creation
  58461. * @returns the number of shapes in the system
  58462. */
  58463. SolidParticleSystem.prototype.addShape = function (mesh, nb, options) {
  58464. var meshPos = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  58465. var meshInd = mesh.getIndices();
  58466. var meshUV = mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  58467. var meshCol = mesh.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  58468. var meshNor = mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  58469. var bbInfo;
  58470. if (this._particlesIntersect) {
  58471. bbInfo = mesh.getBoundingInfo();
  58472. }
  58473. var shape = this._posToShape(meshPos);
  58474. var shapeUV = this._uvsToShapeUV(meshUV);
  58475. var posfunc = options ? options.positionFunction : null;
  58476. var vtxfunc = options ? options.vertexFunction : null;
  58477. var modelShape = new BABYLON.ModelShape(this._shapeCounter, shape, meshInd.length, shapeUV, posfunc, vtxfunc);
  58478. // particles
  58479. var sp;
  58480. var currentCopy;
  58481. var idx = this.nbParticles;
  58482. for (var i = 0; i < nb; i++) {
  58483. var currentPos = this._positions.length;
  58484. var currentInd = this._indices.length;
  58485. currentCopy = this._meshBuilder(this._index, shape, this._positions, meshInd, this._indices, meshUV, this._uvs, meshCol, this._colors, meshNor, this._normals, idx, i, options);
  58486. if (this._updatable) {
  58487. sp = this._addParticle(idx, currentPos, currentInd, modelShape, this._shapeCounter, i, bbInfo);
  58488. sp.position.copyFrom(currentCopy.position);
  58489. sp.rotation.copyFrom(currentCopy.rotation);
  58490. if (currentCopy.rotationQuaternion && sp.rotationQuaternion) {
  58491. sp.rotationQuaternion.copyFrom(currentCopy.rotationQuaternion);
  58492. }
  58493. if (currentCopy.color && sp.color) {
  58494. sp.color.copyFrom(currentCopy.color);
  58495. }
  58496. sp.scaling.copyFrom(currentCopy.scaling);
  58497. sp.uvs.copyFrom(currentCopy.uvs);
  58498. }
  58499. this._index += shape.length;
  58500. idx++;
  58501. }
  58502. this.nbParticles += nb;
  58503. this._shapeCounter++;
  58504. return this._shapeCounter - 1;
  58505. };
  58506. // rebuilds a particle back to its just built status : if needed, recomputes the custom positions and vertices
  58507. SolidParticleSystem.prototype._rebuildParticle = function (particle) {
  58508. this._resetCopy();
  58509. if (particle._model._positionFunction) { // recall to stored custom positionFunction
  58510. particle._model._positionFunction(this._copy, particle.idx, particle.idxInShape);
  58511. }
  58512. if (this._copy.rotationQuaternion) {
  58513. this._quaternion.copyFrom(this._copy.rotationQuaternion);
  58514. }
  58515. else {
  58516. this._yaw = this._copy.rotation.y;
  58517. this._pitch = this._copy.rotation.x;
  58518. this._roll = this._copy.rotation.z;
  58519. this._quaternionRotationYPR();
  58520. }
  58521. this._quaternionToRotationMatrix();
  58522. this._scaledPivot.x = this._particle.pivot.x * this._particle.scaling.x;
  58523. this._scaledPivot.y = this._particle.pivot.y * this._particle.scaling.y;
  58524. this._scaledPivot.z = this._particle.pivot.z * this._particle.scaling.z;
  58525. if (this._copy.translateFromPivot) {
  58526. this._pivotBackTranslation.copyFromFloats(0.0, 0.0, 0.0);
  58527. }
  58528. else {
  58529. this._pivotBackTranslation.copyFrom(this._scaledPivot);
  58530. }
  58531. this._shape = particle._model._shape;
  58532. for (var pt = 0; pt < this._shape.length; pt++) {
  58533. this._vertex.x = this._shape[pt].x;
  58534. this._vertex.y = this._shape[pt].y;
  58535. this._vertex.z = this._shape[pt].z;
  58536. if (particle._model._vertexFunction) {
  58537. particle._model._vertexFunction(this._copy, this._vertex, pt); // recall to stored vertexFunction
  58538. }
  58539. this._vertex.x *= this._copy.scaling.x;
  58540. this._vertex.y *= this._copy.scaling.y;
  58541. this._vertex.z *= this._copy.scaling.z;
  58542. this._vertex.x -= this._scaledPivot.x;
  58543. this._vertex.y -= this._scaledPivot.y;
  58544. this._vertex.z -= this._scaledPivot.z;
  58545. BABYLON.Vector3.TransformCoordinatesToRef(this._vertex, this._rotMatrix, this._rotated);
  58546. this._rotated.addInPlace(this._pivotBackTranslation);
  58547. this._positions32[particle._pos + pt * 3] = this._copy.position.x + this._rotated.x;
  58548. this._positions32[particle._pos + pt * 3 + 1] = this._copy.position.y + this._rotated.y;
  58549. this._positions32[particle._pos + pt * 3 + 2] = this._copy.position.z + this._rotated.z;
  58550. }
  58551. particle.position.x = 0.0;
  58552. particle.position.y = 0.0;
  58553. particle.position.z = 0.0;
  58554. particle.rotation.x = 0.0;
  58555. particle.rotation.y = 0.0;
  58556. particle.rotation.z = 0.0;
  58557. particle.rotationQuaternion = null;
  58558. particle.scaling.x = 1.0;
  58559. particle.scaling.y = 1.0;
  58560. particle.scaling.z = 1.0;
  58561. particle.uvs.x = 0.0;
  58562. particle.uvs.y = 0.0;
  58563. particle.uvs.z = 1.0;
  58564. particle.uvs.w = 1.0;
  58565. particle.pivot.x = 0.0;
  58566. particle.pivot.y = 0.0;
  58567. particle.pivot.z = 0.0;
  58568. particle.translateFromPivot = false;
  58569. particle.parentId = null;
  58570. };
  58571. /**
  58572. * Rebuilds the whole mesh and updates the VBO : custom positions and vertices are recomputed if needed.
  58573. * @returns the SPS.
  58574. */
  58575. SolidParticleSystem.prototype.rebuildMesh = function () {
  58576. for (var p = 0; p < this.particles.length; p++) {
  58577. this._rebuildParticle(this.particles[p]);
  58578. }
  58579. this.mesh.updateVerticesData(BABYLON.VertexBuffer.PositionKind, this._positions32, false, false);
  58580. return this;
  58581. };
  58582. /**
  58583. * Sets all the particles : this method actually really updates the mesh according to the particle positions, rotations, colors, textures, etc.
  58584. * This method calls `updateParticle()` for each particle of the SPS.
  58585. * For an animated SPS, it is usually called within the render loop.
  58586. * @param start The particle index in the particle array where to start to compute the particle property values _(default 0)_
  58587. * @param end The particle index in the particle array where to stop to compute the particle property values _(default nbParticle - 1)_
  58588. * @param update If the mesh must be finally updated on this call after all the particle computations _(default true)_
  58589. * @returns the SPS.
  58590. */
  58591. SolidParticleSystem.prototype.setParticles = function (start, end, update) {
  58592. if (start === void 0) { start = 0; }
  58593. if (end === void 0) { end = this.nbParticles - 1; }
  58594. if (update === void 0) { update = true; }
  58595. if (!this._updatable) {
  58596. return this;
  58597. }
  58598. // custom beforeUpdate
  58599. this.beforeUpdateParticles(start, end, update);
  58600. this._cam_axisX.x = 1.0;
  58601. this._cam_axisX.y = 0.0;
  58602. this._cam_axisX.z = 0.0;
  58603. this._cam_axisY.x = 0.0;
  58604. this._cam_axisY.y = 1.0;
  58605. this._cam_axisY.z = 0.0;
  58606. this._cam_axisZ.x = 0.0;
  58607. this._cam_axisZ.y = 0.0;
  58608. this._cam_axisZ.z = 1.0;
  58609. // cases when the World Matrix is to be computed first
  58610. if (this.billboard || this._depthSort) {
  58611. this.mesh.computeWorldMatrix(true);
  58612. this.mesh._worldMatrix.invertToRef(this._invertMatrix);
  58613. }
  58614. // if the particles will always face the camera
  58615. if (this.billboard) {
  58616. // compute the camera position and un-rotate it by the current mesh rotation
  58617. this._camera.getDirectionToRef(this._axisZ, this._camDir);
  58618. BABYLON.Vector3.TransformNormalToRef(this._camDir, this._invertMatrix, this._cam_axisZ);
  58619. this._cam_axisZ.normalize();
  58620. // same for camera up vector extracted from the cam view matrix
  58621. var view = this._camera.getViewMatrix(true);
  58622. BABYLON.Vector3.TransformNormalFromFloatsToRef(view.m[1], view.m[5], view.m[9], this._invertMatrix, this._cam_axisY);
  58623. BABYLON.Vector3.CrossToRef(this._cam_axisY, this._cam_axisZ, this._cam_axisX);
  58624. this._cam_axisY.normalize();
  58625. this._cam_axisX.normalize();
  58626. }
  58627. // if depthSort, compute the camera global position in the mesh local system
  58628. if (this._depthSort) {
  58629. BABYLON.Vector3.TransformCoordinatesToRef(this._camera.globalPosition, this._invertMatrix, this._camInvertedPosition); // then un-rotate the camera
  58630. }
  58631. BABYLON.Matrix.IdentityToRef(this._rotMatrix);
  58632. var idx = 0; // current position index in the global array positions32
  58633. var index = 0; // position start index in the global array positions32 of the current particle
  58634. var colidx = 0; // current color index in the global array colors32
  58635. var colorIndex = 0; // color start index in the global array colors32 of the current particle
  58636. var uvidx = 0; // current uv index in the global array uvs32
  58637. var uvIndex = 0; // uv start index in the global array uvs32 of the current particle
  58638. var pt = 0; // current index in the particle model shape
  58639. if (this.mesh.isFacetDataEnabled) {
  58640. this._computeBoundingBox = true;
  58641. }
  58642. end = (end >= this.nbParticles) ? this.nbParticles - 1 : end;
  58643. if (this._computeBoundingBox) {
  58644. if (start == 0 && end == this.nbParticles - 1) { // all the particles are updated, then recompute the BBox from scratch
  58645. BABYLON.Vector3.FromFloatsToRef(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, this._minimum);
  58646. BABYLON.Vector3.FromFloatsToRef(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE, this._maximum);
  58647. }
  58648. else { // only some particles are updated, then use the current existing BBox basis. Note : it can only increase.
  58649. if (this.mesh._boundingInfo) {
  58650. this._minimum.copyFrom(this.mesh._boundingInfo.boundingBox.minimum);
  58651. this._maximum.copyFrom(this.mesh._boundingInfo.boundingBox.maximum);
  58652. }
  58653. }
  58654. }
  58655. // particle loop
  58656. index = this.particles[start]._pos;
  58657. var vpos = (index / 3) | 0;
  58658. colorIndex = vpos * 4;
  58659. uvIndex = vpos * 2;
  58660. for (var p = start; p <= end; p++) {
  58661. this._particle = this.particles[p];
  58662. this._shape = this._particle._model._shape;
  58663. this._shapeUV = this._particle._model._shapeUV;
  58664. // call to custom user function to update the particle properties
  58665. this.updateParticle(this._particle);
  58666. // camera-particle distance for depth sorting
  58667. if (this._depthSort && this._depthSortParticles) {
  58668. var dsp = this.depthSortedParticles[p];
  58669. dsp.ind = this._particle._ind;
  58670. dsp.indicesLength = this._particle._model._indicesLength;
  58671. dsp.sqDistance = BABYLON.Vector3.DistanceSquared(this._particle.position, this._camInvertedPosition);
  58672. }
  58673. // skip the computations for inactive or already invisible particles
  58674. if (!this._particle.alive || (this._particle._stillInvisible && !this._particle.isVisible)) {
  58675. // increment indexes for the next particle
  58676. pt = this._shape.length;
  58677. index += pt * 3;
  58678. colorIndex += pt * 4;
  58679. uvIndex += pt * 2;
  58680. continue;
  58681. }
  58682. if (this._particle.isVisible) {
  58683. this._particle._stillInvisible = false; // un-mark permanent invisibility
  58684. this._particleHasParent = (this._particle.parentId !== null);
  58685. this._scaledPivot.x = this._particle.pivot.x * this._particle.scaling.x;
  58686. this._scaledPivot.y = this._particle.pivot.y * this._particle.scaling.y;
  58687. this._scaledPivot.z = this._particle.pivot.z * this._particle.scaling.z;
  58688. // particle rotation matrix
  58689. if (this.billboard) {
  58690. this._particle.rotation.x = 0.0;
  58691. this._particle.rotation.y = 0.0;
  58692. }
  58693. if (this._computeParticleRotation || this.billboard) {
  58694. if (this._particle.rotationQuaternion) {
  58695. this._quaternion.copyFrom(this._particle.rotationQuaternion);
  58696. }
  58697. else {
  58698. this._yaw = this._particle.rotation.y;
  58699. this._pitch = this._particle.rotation.x;
  58700. this._roll = this._particle.rotation.z;
  58701. this._quaternionRotationYPR();
  58702. }
  58703. this._quaternionToRotationMatrix();
  58704. }
  58705. if (this._particleHasParent) {
  58706. this._parent = this.particles[this._particle.parentId];
  58707. 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];
  58708. 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];
  58709. 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];
  58710. this._particle._globalPosition.x = this._parent._globalPosition.x + this._rotated.x;
  58711. this._particle._globalPosition.y = this._parent._globalPosition.y + this._rotated.y;
  58712. this._particle._globalPosition.z = this._parent._globalPosition.z + this._rotated.z;
  58713. if (this._computeParticleRotation || this.billboard) {
  58714. 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];
  58715. 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];
  58716. 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];
  58717. 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];
  58718. 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];
  58719. 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];
  58720. 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];
  58721. 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];
  58722. 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];
  58723. }
  58724. }
  58725. else {
  58726. this._particle._globalPosition.x = this._particle.position.x;
  58727. this._particle._globalPosition.y = this._particle.position.y;
  58728. this._particle._globalPosition.z = this._particle.position.z;
  58729. if (this._computeParticleRotation || this.billboard) {
  58730. this._particle._rotationMatrix[0] = this._rotMatrix.m[0];
  58731. this._particle._rotationMatrix[1] = this._rotMatrix.m[1];
  58732. this._particle._rotationMatrix[2] = this._rotMatrix.m[2];
  58733. this._particle._rotationMatrix[3] = this._rotMatrix.m[4];
  58734. this._particle._rotationMatrix[4] = this._rotMatrix.m[5];
  58735. this._particle._rotationMatrix[5] = this._rotMatrix.m[6];
  58736. this._particle._rotationMatrix[6] = this._rotMatrix.m[8];
  58737. this._particle._rotationMatrix[7] = this._rotMatrix.m[9];
  58738. this._particle._rotationMatrix[8] = this._rotMatrix.m[10];
  58739. }
  58740. }
  58741. if (this._particle.translateFromPivot) {
  58742. this._pivotBackTranslation.x = 0.0;
  58743. this._pivotBackTranslation.y = 0.0;
  58744. this._pivotBackTranslation.z = 0.0;
  58745. }
  58746. else {
  58747. this._pivotBackTranslation.x = this._scaledPivot.x;
  58748. this._pivotBackTranslation.y = this._scaledPivot.y;
  58749. this._pivotBackTranslation.z = this._scaledPivot.z;
  58750. }
  58751. // particle vertex loop
  58752. for (pt = 0; pt < this._shape.length; pt++) {
  58753. idx = index + pt * 3;
  58754. colidx = colorIndex + pt * 4;
  58755. uvidx = uvIndex + pt * 2;
  58756. this._vertex.x = this._shape[pt].x;
  58757. this._vertex.y = this._shape[pt].y;
  58758. this._vertex.z = this._shape[pt].z;
  58759. if (this._computeParticleVertex) {
  58760. this.updateParticleVertex(this._particle, this._vertex, pt);
  58761. }
  58762. // positions
  58763. this._vertex.x *= this._particle.scaling.x;
  58764. this._vertex.y *= this._particle.scaling.y;
  58765. this._vertex.z *= this._particle.scaling.z;
  58766. this._vertex.x -= this._scaledPivot.x;
  58767. this._vertex.y -= this._scaledPivot.y;
  58768. this._vertex.z -= this._scaledPivot.z;
  58769. this._rotated.x = this._vertex.x * this._particle._rotationMatrix[0] + this._vertex.y * this._particle._rotationMatrix[3] + this._vertex.z * this._particle._rotationMatrix[6];
  58770. this._rotated.y = this._vertex.x * this._particle._rotationMatrix[1] + this._vertex.y * this._particle._rotationMatrix[4] + this._vertex.z * this._particle._rotationMatrix[7];
  58771. this._rotated.z = this._vertex.x * this._particle._rotationMatrix[2] + this._vertex.y * this._particle._rotationMatrix[5] + this._vertex.z * this._particle._rotationMatrix[8];
  58772. this._rotated.x += this._pivotBackTranslation.x;
  58773. this._rotated.y += this._pivotBackTranslation.y;
  58774. this._rotated.z += this._pivotBackTranslation.z;
  58775. 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;
  58776. 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;
  58777. 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;
  58778. if (this._computeBoundingBox) {
  58779. if (this._positions32[idx] < this._minimum.x) {
  58780. this._minimum.x = this._positions32[idx];
  58781. }
  58782. if (this._positions32[idx] > this._maximum.x) {
  58783. this._maximum.x = this._positions32[idx];
  58784. }
  58785. if (this._positions32[idx + 1] < this._minimum.y) {
  58786. this._minimum.y = this._positions32[idx + 1];
  58787. }
  58788. if (this._positions32[idx + 1] > this._maximum.y) {
  58789. this._maximum.y = this._positions32[idx + 1];
  58790. }
  58791. if (this._positions32[idx + 2] < this._minimum.z) {
  58792. this._minimum.z = this._positions32[idx + 2];
  58793. }
  58794. if (this._positions32[idx + 2] > this._maximum.z) {
  58795. this._maximum.z = this._positions32[idx + 2];
  58796. }
  58797. }
  58798. // normals : if the particles can't be morphed then just rotate the normals, what is much more faster than ComputeNormals()
  58799. if (!this._computeParticleVertex) {
  58800. this._normal.x = this._fixedNormal32[idx];
  58801. this._normal.y = this._fixedNormal32[idx + 1];
  58802. this._normal.z = this._fixedNormal32[idx + 2];
  58803. this._rotated.x = this._normal.x * this._particle._rotationMatrix[0] + this._normal.y * this._particle._rotationMatrix[3] + this._normal.z * this._particle._rotationMatrix[6];
  58804. this._rotated.y = this._normal.x * this._particle._rotationMatrix[1] + this._normal.y * this._particle._rotationMatrix[4] + this._normal.z * this._particle._rotationMatrix[7];
  58805. this._rotated.z = this._normal.x * this._particle._rotationMatrix[2] + this._normal.y * this._particle._rotationMatrix[5] + this._normal.z * this._particle._rotationMatrix[8];
  58806. this._normals32[idx] = this._cam_axisX.x * this._rotated.x + this._cam_axisY.x * this._rotated.y + this._cam_axisZ.x * this._rotated.z;
  58807. 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;
  58808. 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;
  58809. }
  58810. if (this._computeParticleColor && this._particle.color) {
  58811. this._colors32[colidx] = this._particle.color.r;
  58812. this._colors32[colidx + 1] = this._particle.color.g;
  58813. this._colors32[colidx + 2] = this._particle.color.b;
  58814. this._colors32[colidx + 3] = this._particle.color.a;
  58815. }
  58816. if (this._computeParticleTexture) {
  58817. this._uvs32[uvidx] = this._shapeUV[pt * 2] * (this._particle.uvs.z - this._particle.uvs.x) + this._particle.uvs.x;
  58818. this._uvs32[uvidx + 1] = this._shapeUV[pt * 2 + 1] * (this._particle.uvs.w - this._particle.uvs.y) + this._particle.uvs.y;
  58819. }
  58820. }
  58821. }
  58822. // particle just set invisible : scaled to zero and positioned at the origin
  58823. else {
  58824. this._particle._stillInvisible = true; // mark the particle as invisible
  58825. for (pt = 0; pt < this._shape.length; pt++) {
  58826. idx = index + pt * 3;
  58827. colidx = colorIndex + pt * 4;
  58828. uvidx = uvIndex + pt * 2;
  58829. this._positions32[idx] = 0.0;
  58830. this._positions32[idx + 1] = 0.0;
  58831. this._positions32[idx + 2] = 0.0;
  58832. this._normals32[idx] = 0.0;
  58833. this._normals32[idx + 1] = 0.0;
  58834. this._normals32[idx + 2] = 0.0;
  58835. if (this._computeParticleColor && this._particle.color) {
  58836. this._colors32[colidx] = this._particle.color.r;
  58837. this._colors32[colidx + 1] = this._particle.color.g;
  58838. this._colors32[colidx + 2] = this._particle.color.b;
  58839. this._colors32[colidx + 3] = this._particle.color.a;
  58840. }
  58841. if (this._computeParticleTexture) {
  58842. this._uvs32[uvidx] = this._shapeUV[pt * 2] * (this._particle.uvs.z - this._particle.uvs.x) + this._particle.uvs.x;
  58843. this._uvs32[uvidx + 1] = this._shapeUV[pt * 2 + 1] * (this._particle.uvs.w - this._particle.uvs.y) + this._particle.uvs.y;
  58844. }
  58845. }
  58846. }
  58847. // if the particle intersections must be computed : update the bbInfo
  58848. if (this._particlesIntersect) {
  58849. var bInfo = this._particle._boundingInfo;
  58850. var bBox = bInfo.boundingBox;
  58851. var bSphere = bInfo.boundingSphere;
  58852. if (!this._bSphereOnly) {
  58853. // place, scale and rotate the particle bbox within the SPS local system, then update it
  58854. for (var b = 0; b < bBox.vectors.length; b++) {
  58855. this._vertex.x = this._particle._modelBoundingInfo.boundingBox.vectors[b].x * this._particle.scaling.x;
  58856. this._vertex.y = this._particle._modelBoundingInfo.boundingBox.vectors[b].y * this._particle.scaling.y;
  58857. this._vertex.z = this._particle._modelBoundingInfo.boundingBox.vectors[b].z * this._particle.scaling.z;
  58858. this._rotated.x = this._vertex.x * this._particle._rotationMatrix[0] + this._vertex.y * this._particle._rotationMatrix[3] + this._vertex.z * this._particle._rotationMatrix[6];
  58859. this._rotated.y = this._vertex.x * this._particle._rotationMatrix[1] + this._vertex.y * this._particle._rotationMatrix[4] + this._vertex.z * this._particle._rotationMatrix[7];
  58860. this._rotated.z = this._vertex.x * this._particle._rotationMatrix[2] + this._vertex.y * this._particle._rotationMatrix[5] + this._vertex.z * this._particle._rotationMatrix[8];
  58861. 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;
  58862. 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;
  58863. 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;
  58864. }
  58865. bBox._update(this.mesh._worldMatrix);
  58866. }
  58867. // place and scale the particle bouding sphere in the SPS local system, then update it
  58868. this._minBbox.x = this._particle._modelBoundingInfo.minimum.x * this._particle.scaling.x;
  58869. this._minBbox.y = this._particle._modelBoundingInfo.minimum.y * this._particle.scaling.y;
  58870. this._minBbox.z = this._particle._modelBoundingInfo.minimum.z * this._particle.scaling.z;
  58871. this._maxBbox.x = this._particle._modelBoundingInfo.maximum.x * this._particle.scaling.x;
  58872. this._maxBbox.y = this._particle._modelBoundingInfo.maximum.y * this._particle.scaling.y;
  58873. this._maxBbox.z = this._particle._modelBoundingInfo.maximum.z * this._particle.scaling.z;
  58874. bSphere.center.x = this._particle._globalPosition.x + (this._minBbox.x + this._maxBbox.x) * 0.5;
  58875. bSphere.center.y = this._particle._globalPosition.y + (this._minBbox.y + this._maxBbox.y) * 0.5;
  58876. bSphere.center.z = this._particle._globalPosition.z + (this._minBbox.z + this._maxBbox.z) * 0.5;
  58877. 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));
  58878. bSphere._update(this.mesh._worldMatrix);
  58879. }
  58880. // increment indexes for the next particle
  58881. index = idx + 3;
  58882. colorIndex = colidx + 4;
  58883. uvIndex = uvidx + 2;
  58884. }
  58885. // if the VBO must be updated
  58886. if (update) {
  58887. if (this._computeParticleColor) {
  58888. this.mesh.updateVerticesData(BABYLON.VertexBuffer.ColorKind, this._colors32, false, false);
  58889. }
  58890. if (this._computeParticleTexture) {
  58891. this.mesh.updateVerticesData(BABYLON.VertexBuffer.UVKind, this._uvs32, false, false);
  58892. }
  58893. this.mesh.updateVerticesData(BABYLON.VertexBuffer.PositionKind, this._positions32, false, false);
  58894. if (!this.mesh.areNormalsFrozen || this.mesh.isFacetDataEnabled) {
  58895. if (this._computeParticleVertex || this.mesh.isFacetDataEnabled) {
  58896. // recompute the normals only if the particles can be morphed, update then also the normal reference array _fixedNormal32[]
  58897. var params = this.mesh.isFacetDataEnabled ? this.mesh.getFacetDataParameters() : null;
  58898. BABYLON.VertexData.ComputeNormals(this._positions32, this._indices32, this._normals32, params);
  58899. for (var i = 0; i < this._normals32.length; i++) {
  58900. this._fixedNormal32[i] = this._normals32[i];
  58901. }
  58902. }
  58903. if (!this.mesh.areNormalsFrozen) {
  58904. this.mesh.updateVerticesData(BABYLON.VertexBuffer.NormalKind, this._normals32, false, false);
  58905. }
  58906. }
  58907. if (this._depthSort && this._depthSortParticles) {
  58908. this.depthSortedParticles.sort(this._depthSortFunction);
  58909. var dspl = this.depthSortedParticles.length;
  58910. var sorted = 0;
  58911. var lind = 0;
  58912. var sind = 0;
  58913. var sid = 0;
  58914. for (sorted = 0; sorted < dspl; sorted++) {
  58915. lind = this.depthSortedParticles[sorted].indicesLength;
  58916. sind = this.depthSortedParticles[sorted].ind;
  58917. for (var i = 0; i < lind; i++) {
  58918. this._indices32[sid] = this._indices[sind + i];
  58919. sid++;
  58920. }
  58921. }
  58922. this.mesh.updateIndices(this._indices32);
  58923. }
  58924. }
  58925. if (this._computeBoundingBox) {
  58926. this.mesh._boundingInfo = new BABYLON.BoundingInfo(this._minimum, this._maximum);
  58927. this.mesh._boundingInfo.update(this.mesh._worldMatrix);
  58928. }
  58929. this.afterUpdateParticles(start, end, update);
  58930. return this;
  58931. };
  58932. SolidParticleSystem.prototype._quaternionRotationYPR = function () {
  58933. this._halfroll = this._roll * 0.5;
  58934. this._halfpitch = this._pitch * 0.5;
  58935. this._halfyaw = this._yaw * 0.5;
  58936. this._sinRoll = Math.sin(this._halfroll);
  58937. this._cosRoll = Math.cos(this._halfroll);
  58938. this._sinPitch = Math.sin(this._halfpitch);
  58939. this._cosPitch = Math.cos(this._halfpitch);
  58940. this._sinYaw = Math.sin(this._halfyaw);
  58941. this._cosYaw = Math.cos(this._halfyaw);
  58942. this._quaternion.x = this._cosYaw * this._sinPitch * this._cosRoll + this._sinYaw * this._cosPitch * this._sinRoll;
  58943. this._quaternion.y = this._sinYaw * this._cosPitch * this._cosRoll - this._cosYaw * this._sinPitch * this._sinRoll;
  58944. this._quaternion.z = this._cosYaw * this._cosPitch * this._sinRoll - this._sinYaw * this._sinPitch * this._cosRoll;
  58945. this._quaternion.w = this._cosYaw * this._cosPitch * this._cosRoll + this._sinYaw * this._sinPitch * this._sinRoll;
  58946. };
  58947. SolidParticleSystem.prototype._quaternionToRotationMatrix = function () {
  58948. this._rotMatrix.m[0] = 1.0 - (2.0 * (this._quaternion.y * this._quaternion.y + this._quaternion.z * this._quaternion.z));
  58949. this._rotMatrix.m[1] = 2.0 * (this._quaternion.x * this._quaternion.y + this._quaternion.z * this._quaternion.w);
  58950. this._rotMatrix.m[2] = 2.0 * (this._quaternion.z * this._quaternion.x - this._quaternion.y * this._quaternion.w);
  58951. this._rotMatrix.m[3] = 0;
  58952. this._rotMatrix.m[4] = 2.0 * (this._quaternion.x * this._quaternion.y - this._quaternion.z * this._quaternion.w);
  58953. this._rotMatrix.m[5] = 1.0 - (2.0 * (this._quaternion.z * this._quaternion.z + this._quaternion.x * this._quaternion.x));
  58954. this._rotMatrix.m[6] = 2.0 * (this._quaternion.y * this._quaternion.z + this._quaternion.x * this._quaternion.w);
  58955. this._rotMatrix.m[7] = 0;
  58956. this._rotMatrix.m[8] = 2.0 * (this._quaternion.z * this._quaternion.x + this._quaternion.y * this._quaternion.w);
  58957. this._rotMatrix.m[9] = 2.0 * (this._quaternion.y * this._quaternion.z - this._quaternion.x * this._quaternion.w);
  58958. this._rotMatrix.m[10] = 1.0 - (2.0 * (this._quaternion.y * this._quaternion.y + this._quaternion.x * this._quaternion.x));
  58959. this._rotMatrix.m[11] = 0;
  58960. this._rotMatrix.m[12] = 0;
  58961. this._rotMatrix.m[13] = 0;
  58962. this._rotMatrix.m[14] = 0;
  58963. this._rotMatrix.m[15] = 1.0;
  58964. };
  58965. /**
  58966. * Disposes the SPS.
  58967. */
  58968. SolidParticleSystem.prototype.dispose = function () {
  58969. this.mesh.dispose();
  58970. this.vars = null;
  58971. // drop references to internal big arrays for the GC
  58972. this._positions = null;
  58973. this._indices = null;
  58974. this._normals = null;
  58975. this._uvs = null;
  58976. this._colors = null;
  58977. this._indices32 = null;
  58978. this._positions32 = null;
  58979. this._normals32 = null;
  58980. this._fixedNormal32 = null;
  58981. this._uvs32 = null;
  58982. this._colors32 = null;
  58983. this.pickedParticles = null;
  58984. };
  58985. /**
  58986. * Visibilty helper : Recomputes the visible size according to the mesh bounding box
  58987. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  58988. * @returns the SPS.
  58989. */
  58990. SolidParticleSystem.prototype.refreshVisibleSize = function () {
  58991. if (!this._isVisibilityBoxLocked) {
  58992. this.mesh.refreshBoundingInfo();
  58993. }
  58994. return this;
  58995. };
  58996. /**
  58997. * Visibility helper : Sets the size of a visibility box, this sets the underlying mesh bounding box.
  58998. * @param size the size (float) of the visibility box
  58999. * note : this doesn't lock the SPS mesh bounding box.
  59000. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  59001. */
  59002. SolidParticleSystem.prototype.setVisibilityBox = function (size) {
  59003. var vis = size / 2;
  59004. this.mesh._boundingInfo = new BABYLON.BoundingInfo(new BABYLON.Vector3(-vis, -vis, -vis), new BABYLON.Vector3(vis, vis, vis));
  59005. };
  59006. Object.defineProperty(SolidParticleSystem.prototype, "isAlwaysVisible", {
  59007. /**
  59008. * Gets whether the SPS as always visible or not
  59009. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  59010. */
  59011. get: function () {
  59012. return this._alwaysVisible;
  59013. },
  59014. /**
  59015. * Sets the SPS as always visible or not
  59016. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  59017. */
  59018. set: function (val) {
  59019. this._alwaysVisible = val;
  59020. this.mesh.alwaysSelectAsActiveMesh = val;
  59021. },
  59022. enumerable: true,
  59023. configurable: true
  59024. });
  59025. Object.defineProperty(SolidParticleSystem.prototype, "isVisibilityBoxLocked", {
  59026. /**
  59027. * Gets if the SPS visibility box as locked or not. This enables/disables the underlying mesh bounding box updates.
  59028. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  59029. */
  59030. get: function () {
  59031. return this._isVisibilityBoxLocked;
  59032. },
  59033. /**
  59034. * Sets the SPS visibility box as locked or not. This enables/disables the underlying mesh bounding box updates.
  59035. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  59036. */
  59037. set: function (val) {
  59038. this._isVisibilityBoxLocked = val;
  59039. var boundingInfo = this.mesh.getBoundingInfo();
  59040. boundingInfo.isLocked = val;
  59041. },
  59042. enumerable: true,
  59043. configurable: true
  59044. });
  59045. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleRotation", {
  59046. /**
  59047. * Gets if `setParticles()` computes the particle rotations or not.
  59048. * Default value : true. The SPS is faster when it's set to false.
  59049. * Note : the particle rotations aren't stored values, so setting `computeParticleRotation` to false will prevents the particle to rotate.
  59050. */
  59051. get: function () {
  59052. return this._computeParticleRotation;
  59053. },
  59054. /**
  59055. * Tells to `setParticles()` to compute the particle rotations or not.
  59056. * Default value : true. The SPS is faster when it's set to false.
  59057. * Note : the particle rotations aren't stored values, so setting `computeParticleRotation` to false will prevents the particle to rotate.
  59058. */
  59059. set: function (val) {
  59060. this._computeParticleRotation = val;
  59061. },
  59062. enumerable: true,
  59063. configurable: true
  59064. });
  59065. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleColor", {
  59066. /**
  59067. * Gets if `setParticles()` computes the particle colors or not.
  59068. * Default value : true. The SPS is faster when it's set to false.
  59069. * Note : the particle colors are stored values, so setting `computeParticleColor` to false will keep yet the last colors set.
  59070. */
  59071. get: function () {
  59072. return this._computeParticleColor;
  59073. },
  59074. /**
  59075. * Tells to `setParticles()` to compute the particle colors or not.
  59076. * Default value : true. The SPS is faster when it's set to false.
  59077. * Note : the particle colors are stored values, so setting `computeParticleColor` to false will keep yet the last colors set.
  59078. */
  59079. set: function (val) {
  59080. this._computeParticleColor = val;
  59081. },
  59082. enumerable: true,
  59083. configurable: true
  59084. });
  59085. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleTexture", {
  59086. /**
  59087. * Gets if `setParticles()` computes the particle textures or not.
  59088. * Default value : true. The SPS is faster when it's set to false.
  59089. * Note : the particle textures are stored values, so setting `computeParticleTexture` to false will keep yet the last colors set.
  59090. */
  59091. get: function () {
  59092. return this._computeParticleTexture;
  59093. },
  59094. set: function (val) {
  59095. this._computeParticleTexture = val;
  59096. },
  59097. enumerable: true,
  59098. configurable: true
  59099. });
  59100. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleVertex", {
  59101. /**
  59102. * Gets if `setParticles()` calls the vertex function for each vertex of each particle, or not.
  59103. * Default value : false. The SPS is faster when it's set to false.
  59104. * Note : the particle custom vertex positions aren't stored values.
  59105. */
  59106. get: function () {
  59107. return this._computeParticleVertex;
  59108. },
  59109. /**
  59110. * Tells to `setParticles()` to call the vertex function for each vertex of each particle, or not.
  59111. * Default value : false. The SPS is faster when it's set to false.
  59112. * Note : the particle custom vertex positions aren't stored values.
  59113. */
  59114. set: function (val) {
  59115. this._computeParticleVertex = val;
  59116. },
  59117. enumerable: true,
  59118. configurable: true
  59119. });
  59120. Object.defineProperty(SolidParticleSystem.prototype, "computeBoundingBox", {
  59121. /**
  59122. * Gets if `setParticles()` computes or not the mesh bounding box when computing the particle positions.
  59123. */
  59124. get: function () {
  59125. return this._computeBoundingBox;
  59126. },
  59127. /**
  59128. * Tells to `setParticles()` to compute or not the mesh bounding box when computing the particle positions.
  59129. */
  59130. set: function (val) {
  59131. this._computeBoundingBox = val;
  59132. },
  59133. enumerable: true,
  59134. configurable: true
  59135. });
  59136. Object.defineProperty(SolidParticleSystem.prototype, "depthSortParticles", {
  59137. /**
  59138. * Gets if `setParticles()` sorts or not the distance between each particle and the camera.
  59139. * Skipped when `enableDepthSort` is set to `false` (default) at construction time.
  59140. * Default : `true`
  59141. */
  59142. get: function () {
  59143. return this._depthSortParticles;
  59144. },
  59145. /**
  59146. * Tells to `setParticles()` to sort or not the distance between each particle and the camera.
  59147. * Skipped when `enableDepthSort` is set to `false` (default) at construction time.
  59148. * Default : `true`
  59149. */
  59150. set: function (val) {
  59151. this._depthSortParticles = val;
  59152. },
  59153. enumerable: true,
  59154. configurable: true
  59155. });
  59156. // =======================================================================
  59157. // Particle behavior logic
  59158. // these following methods may be overwritten by the user to fit his needs
  59159. /**
  59160. * This function does nothing. It may be overwritten to set all the particle first values.
  59161. * The SPS doesn't call this function, you may have to call it by your own.
  59162. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#particle-management
  59163. */
  59164. SolidParticleSystem.prototype.initParticles = function () {
  59165. };
  59166. /**
  59167. * This function does nothing. It may be overwritten to recycle a particle.
  59168. * The SPS doesn't call this function, you may have to call it by your own.
  59169. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#particle-management
  59170. * @param particle The particle to recycle
  59171. * @returns the recycled particle
  59172. */
  59173. SolidParticleSystem.prototype.recycleParticle = function (particle) {
  59174. return particle;
  59175. };
  59176. /**
  59177. * Updates a particle : this function should be overwritten by the user.
  59178. * It is called on each particle by `setParticles()`. This is the place to code each particle behavior.
  59179. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#particle-management
  59180. * @example : just set a particle position or velocity and recycle conditions
  59181. * @param particle The particle to update
  59182. * @returns the updated particle
  59183. */
  59184. SolidParticleSystem.prototype.updateParticle = function (particle) {
  59185. return particle;
  59186. };
  59187. /**
  59188. * Updates a vertex of a particle : it can be overwritten by the user.
  59189. * This will be called on each vertex particle by `setParticles()` if `computeParticleVertex` is set to true only.
  59190. * @param particle the current particle
  59191. * @param vertex the current index of the current particle
  59192. * @param pt the index of the current vertex in the particle shape
  59193. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#update-each-particle-shape
  59194. * @example : just set a vertex particle position
  59195. * @returns the updated vertex
  59196. */
  59197. SolidParticleSystem.prototype.updateParticleVertex = function (particle, vertex, pt) {
  59198. return vertex;
  59199. };
  59200. /**
  59201. * This will be called before any other treatment by `setParticles()` and will be passed three parameters.
  59202. * This does nothing and may be overwritten by the user.
  59203. * @param start the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  59204. * @param stop the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  59205. * @param update the boolean update value actually passed to setParticles()
  59206. */
  59207. SolidParticleSystem.prototype.beforeUpdateParticles = function (start, stop, update) {
  59208. };
  59209. /**
  59210. * This will be called by `setParticles()` after all the other treatments and just before the actual mesh update.
  59211. * This will be passed three parameters.
  59212. * This does nothing and may be overwritten by the user.
  59213. * @param start the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  59214. * @param stop the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  59215. * @param update the boolean update value actually passed to setParticles()
  59216. */
  59217. SolidParticleSystem.prototype.afterUpdateParticles = function (start, stop, update) {
  59218. };
  59219. return SolidParticleSystem;
  59220. }());
  59221. BABYLON.SolidParticleSystem = SolidParticleSystem;
  59222. })(BABYLON || (BABYLON = {}));
  59223. //# sourceMappingURL=babylon.solidParticleSystem.js.map
  59224. var BABYLON;
  59225. (function (BABYLON) {
  59226. var ShaderMaterial = /** @class */ (function (_super) {
  59227. __extends(ShaderMaterial, _super);
  59228. function ShaderMaterial(name, scene, shaderPath, options) {
  59229. var _this = _super.call(this, name, scene) || this;
  59230. _this._textures = {};
  59231. _this._textureArrays = {};
  59232. _this._floats = {};
  59233. _this._ints = {};
  59234. _this._floatsArrays = {};
  59235. _this._colors3 = {};
  59236. _this._colors3Arrays = {};
  59237. _this._colors4 = {};
  59238. _this._vectors2 = {};
  59239. _this._vectors3 = {};
  59240. _this._vectors4 = {};
  59241. _this._matrices = {};
  59242. _this._matrices3x3 = {};
  59243. _this._matrices2x2 = {};
  59244. _this._vectors2Arrays = {};
  59245. _this._vectors3Arrays = {};
  59246. _this._cachedWorldViewMatrix = new BABYLON.Matrix();
  59247. _this._shaderPath = shaderPath;
  59248. options.needAlphaBlending = options.needAlphaBlending || false;
  59249. options.needAlphaTesting = options.needAlphaTesting || false;
  59250. options.attributes = options.attributes || ["position", "normal", "uv"];
  59251. options.uniforms = options.uniforms || ["worldViewProjection"];
  59252. options.uniformBuffers = options.uniformBuffers || [];
  59253. options.samplers = options.samplers || [];
  59254. options.defines = options.defines || [];
  59255. _this._options = options;
  59256. return _this;
  59257. }
  59258. ShaderMaterial.prototype.getClassName = function () {
  59259. return "ShaderMaterial";
  59260. };
  59261. ShaderMaterial.prototype.needAlphaBlending = function () {
  59262. return this._options.needAlphaBlending;
  59263. };
  59264. ShaderMaterial.prototype.needAlphaTesting = function () {
  59265. return this._options.needAlphaTesting;
  59266. };
  59267. ShaderMaterial.prototype._checkUniform = function (uniformName) {
  59268. if (this._options.uniforms.indexOf(uniformName) === -1) {
  59269. this._options.uniforms.push(uniformName);
  59270. }
  59271. };
  59272. ShaderMaterial.prototype.setTexture = function (name, texture) {
  59273. if (this._options.samplers.indexOf(name) === -1) {
  59274. this._options.samplers.push(name);
  59275. }
  59276. this._textures[name] = texture;
  59277. return this;
  59278. };
  59279. ShaderMaterial.prototype.setTextureArray = function (name, textures) {
  59280. if (this._options.samplers.indexOf(name) === -1) {
  59281. this._options.samplers.push(name);
  59282. }
  59283. this._checkUniform(name);
  59284. this._textureArrays[name] = textures;
  59285. return this;
  59286. };
  59287. ShaderMaterial.prototype.setFloat = function (name, value) {
  59288. this._checkUniform(name);
  59289. this._floats[name] = value;
  59290. return this;
  59291. };
  59292. ShaderMaterial.prototype.setInt = function (name, value) {
  59293. this._checkUniform(name);
  59294. this._ints[name] = value;
  59295. return this;
  59296. };
  59297. ShaderMaterial.prototype.setFloats = function (name, value) {
  59298. this._checkUniform(name);
  59299. this._floatsArrays[name] = value;
  59300. return this;
  59301. };
  59302. ShaderMaterial.prototype.setColor3 = function (name, value) {
  59303. this._checkUniform(name);
  59304. this._colors3[name] = value;
  59305. return this;
  59306. };
  59307. ShaderMaterial.prototype.setColor3Array = function (name, value) {
  59308. this._checkUniform(name);
  59309. this._colors3Arrays[name] = value.reduce(function (arr, color) {
  59310. color.toArray(arr, arr.length);
  59311. return arr;
  59312. }, []);
  59313. return this;
  59314. };
  59315. ShaderMaterial.prototype.setColor4 = function (name, value) {
  59316. this._checkUniform(name);
  59317. this._colors4[name] = value;
  59318. return this;
  59319. };
  59320. ShaderMaterial.prototype.setVector2 = function (name, value) {
  59321. this._checkUniform(name);
  59322. this._vectors2[name] = value;
  59323. return this;
  59324. };
  59325. ShaderMaterial.prototype.setVector3 = function (name, value) {
  59326. this._checkUniform(name);
  59327. this._vectors3[name] = value;
  59328. return this;
  59329. };
  59330. ShaderMaterial.prototype.setVector4 = function (name, value) {
  59331. this._checkUniform(name);
  59332. this._vectors4[name] = value;
  59333. return this;
  59334. };
  59335. ShaderMaterial.prototype.setMatrix = function (name, value) {
  59336. this._checkUniform(name);
  59337. this._matrices[name] = value;
  59338. return this;
  59339. };
  59340. ShaderMaterial.prototype.setMatrix3x3 = function (name, value) {
  59341. this._checkUniform(name);
  59342. this._matrices3x3[name] = value;
  59343. return this;
  59344. };
  59345. ShaderMaterial.prototype.setMatrix2x2 = function (name, value) {
  59346. this._checkUniform(name);
  59347. this._matrices2x2[name] = value;
  59348. return this;
  59349. };
  59350. ShaderMaterial.prototype.setArray2 = function (name, value) {
  59351. this._checkUniform(name);
  59352. this._vectors2Arrays[name] = value;
  59353. return this;
  59354. };
  59355. ShaderMaterial.prototype.setArray3 = function (name, value) {
  59356. this._checkUniform(name);
  59357. this._vectors3Arrays[name] = value;
  59358. return this;
  59359. };
  59360. ShaderMaterial.prototype._checkCache = function (scene, mesh, useInstances) {
  59361. if (!mesh) {
  59362. return true;
  59363. }
  59364. if (this._effect && (this._effect.defines.indexOf("#define INSTANCES") !== -1) !== useInstances) {
  59365. return false;
  59366. }
  59367. return false;
  59368. };
  59369. ShaderMaterial.prototype.isReady = function (mesh, useInstances) {
  59370. var scene = this.getScene();
  59371. var engine = scene.getEngine();
  59372. if (!this.checkReadyOnEveryCall) {
  59373. if (this._renderId === scene.getRenderId()) {
  59374. if (this._checkCache(scene, mesh, useInstances)) {
  59375. return true;
  59376. }
  59377. }
  59378. }
  59379. // Instances
  59380. var defines = [];
  59381. var attribs = [];
  59382. var fallbacks = new BABYLON.EffectFallbacks();
  59383. if (useInstances) {
  59384. defines.push("#define INSTANCES");
  59385. }
  59386. for (var index = 0; index < this._options.defines.length; index++) {
  59387. defines.push(this._options.defines[index]);
  59388. }
  59389. for (var index = 0; index < this._options.attributes.length; index++) {
  59390. attribs.push(this._options.attributes[index]);
  59391. }
  59392. if (mesh && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  59393. attribs.push(BABYLON.VertexBuffer.ColorKind);
  59394. defines.push("#define VERTEXCOLOR");
  59395. }
  59396. // Bones
  59397. if (mesh && mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  59398. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  59399. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  59400. if (mesh.numBoneInfluencers > 4) {
  59401. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  59402. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  59403. }
  59404. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  59405. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  59406. fallbacks.addCPUSkinningFallback(0, mesh);
  59407. if (this._options.uniforms.indexOf("mBones") === -1) {
  59408. this._options.uniforms.push("mBones");
  59409. }
  59410. }
  59411. else {
  59412. defines.push("#define NUM_BONE_INFLUENCERS 0");
  59413. }
  59414. // Textures
  59415. for (var name in this._textures) {
  59416. if (!this._textures[name].isReady()) {
  59417. return false;
  59418. }
  59419. }
  59420. // Alpha test
  59421. if (mesh && this._shouldTurnAlphaTestOn(mesh)) {
  59422. defines.push("#define ALPHATEST");
  59423. }
  59424. var previousEffect = this._effect;
  59425. var join = defines.join("\n");
  59426. this._effect = engine.createEffect(this._shaderPath, {
  59427. attributes: attribs,
  59428. uniformsNames: this._options.uniforms,
  59429. uniformBuffersNames: this._options.uniformBuffers,
  59430. samplers: this._options.samplers,
  59431. defines: join,
  59432. fallbacks: fallbacks,
  59433. onCompiled: this.onCompiled,
  59434. onError: this.onError
  59435. }, engine);
  59436. if (!this._effect.isReady()) {
  59437. return false;
  59438. }
  59439. if (previousEffect !== this._effect) {
  59440. scene.resetCachedMaterial();
  59441. }
  59442. this._renderId = scene.getRenderId();
  59443. return true;
  59444. };
  59445. ShaderMaterial.prototype.bindOnlyWorldMatrix = function (world) {
  59446. var scene = this.getScene();
  59447. if (!this._effect) {
  59448. return;
  59449. }
  59450. if (this._options.uniforms.indexOf("world") !== -1) {
  59451. this._effect.setMatrix("world", world);
  59452. }
  59453. if (this._options.uniforms.indexOf("worldView") !== -1) {
  59454. world.multiplyToRef(scene.getViewMatrix(), this._cachedWorldViewMatrix);
  59455. this._effect.setMatrix("worldView", this._cachedWorldViewMatrix);
  59456. }
  59457. if (this._options.uniforms.indexOf("worldViewProjection") !== -1) {
  59458. this._effect.setMatrix("worldViewProjection", world.multiply(scene.getTransformMatrix()));
  59459. }
  59460. };
  59461. ShaderMaterial.prototype.bind = function (world, mesh) {
  59462. // Std values
  59463. this.bindOnlyWorldMatrix(world);
  59464. if (this._effect && this.getScene().getCachedMaterial() !== this) {
  59465. if (this._options.uniforms.indexOf("view") !== -1) {
  59466. this._effect.setMatrix("view", this.getScene().getViewMatrix());
  59467. }
  59468. if (this._options.uniforms.indexOf("projection") !== -1) {
  59469. this._effect.setMatrix("projection", this.getScene().getProjectionMatrix());
  59470. }
  59471. if (this._options.uniforms.indexOf("viewProjection") !== -1) {
  59472. this._effect.setMatrix("viewProjection", this.getScene().getTransformMatrix());
  59473. }
  59474. // Bones
  59475. BABYLON.MaterialHelper.BindBonesParameters(mesh, this._effect);
  59476. var name;
  59477. // Texture
  59478. for (name in this._textures) {
  59479. this._effect.setTexture(name, this._textures[name]);
  59480. }
  59481. // Texture arrays
  59482. for (name in this._textureArrays) {
  59483. this._effect.setTextureArray(name, this._textureArrays[name]);
  59484. }
  59485. // Int
  59486. for (name in this._ints) {
  59487. this._effect.setInt(name, this._ints[name]);
  59488. }
  59489. // Float
  59490. for (name in this._floats) {
  59491. this._effect.setFloat(name, this._floats[name]);
  59492. }
  59493. // Floats
  59494. for (name in this._floatsArrays) {
  59495. this._effect.setArray(name, this._floatsArrays[name]);
  59496. }
  59497. // Color3
  59498. for (name in this._colors3) {
  59499. this._effect.setColor3(name, this._colors3[name]);
  59500. }
  59501. for (name in this._colors3Arrays) {
  59502. this._effect.setArray3(name, this._colors3Arrays[name]);
  59503. }
  59504. // Color4
  59505. for (name in this._colors4) {
  59506. var color = this._colors4[name];
  59507. this._effect.setFloat4(name, color.r, color.g, color.b, color.a);
  59508. }
  59509. // Vector2
  59510. for (name in this._vectors2) {
  59511. this._effect.setVector2(name, this._vectors2[name]);
  59512. }
  59513. // Vector3
  59514. for (name in this._vectors3) {
  59515. this._effect.setVector3(name, this._vectors3[name]);
  59516. }
  59517. // Vector4
  59518. for (name in this._vectors4) {
  59519. this._effect.setVector4(name, this._vectors4[name]);
  59520. }
  59521. // Matrix
  59522. for (name in this._matrices) {
  59523. this._effect.setMatrix(name, this._matrices[name]);
  59524. }
  59525. // Matrix 3x3
  59526. for (name in this._matrices3x3) {
  59527. this._effect.setMatrix3x3(name, this._matrices3x3[name]);
  59528. }
  59529. // Matrix 2x2
  59530. for (name in this._matrices2x2) {
  59531. this._effect.setMatrix2x2(name, this._matrices2x2[name]);
  59532. }
  59533. // Vector2Array
  59534. for (name in this._vectors2Arrays) {
  59535. this._effect.setArray2(name, this._vectors2Arrays[name]);
  59536. }
  59537. // Vector3Array
  59538. for (name in this._vectors3Arrays) {
  59539. this._effect.setArray3(name, this._vectors3Arrays[name]);
  59540. }
  59541. }
  59542. this._afterBind(mesh);
  59543. };
  59544. ShaderMaterial.prototype.getActiveTextures = function () {
  59545. var activeTextures = _super.prototype.getActiveTextures.call(this);
  59546. for (var name in this._textures) {
  59547. activeTextures.push(this._textures[name]);
  59548. }
  59549. for (var name in this._textureArrays) {
  59550. var array = this._textureArrays[name];
  59551. for (var index = 0; index < array.length; index++) {
  59552. activeTextures.push(array[index]);
  59553. }
  59554. }
  59555. return activeTextures;
  59556. };
  59557. ShaderMaterial.prototype.hasTexture = function (texture) {
  59558. if (_super.prototype.hasTexture.call(this, texture)) {
  59559. return true;
  59560. }
  59561. for (var name in this._textures) {
  59562. if (this._textures[name] === texture) {
  59563. return true;
  59564. }
  59565. }
  59566. for (var name in this._textureArrays) {
  59567. var array = this._textureArrays[name];
  59568. for (var index = 0; index < array.length; index++) {
  59569. if (array[index] === texture) {
  59570. return true;
  59571. }
  59572. }
  59573. }
  59574. return false;
  59575. };
  59576. ShaderMaterial.prototype.clone = function (name) {
  59577. var newShaderMaterial = new ShaderMaterial(name, this.getScene(), this._shaderPath, this._options);
  59578. return newShaderMaterial;
  59579. };
  59580. ShaderMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  59581. if (forceDisposeTextures) {
  59582. var name;
  59583. for (name in this._textures) {
  59584. this._textures[name].dispose();
  59585. }
  59586. for (name in this._textureArrays) {
  59587. var array = this._textureArrays[name];
  59588. for (var index = 0; index < array.length; index++) {
  59589. array[index].dispose();
  59590. }
  59591. }
  59592. }
  59593. this._textures = {};
  59594. _super.prototype.dispose.call(this, forceDisposeEffect, forceDisposeTextures);
  59595. };
  59596. ShaderMaterial.prototype.serialize = function () {
  59597. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  59598. serializationObject.customType = "BABYLON.ShaderMaterial";
  59599. serializationObject.options = this._options;
  59600. serializationObject.shaderPath = this._shaderPath;
  59601. var name;
  59602. // Texture
  59603. serializationObject.textures = {};
  59604. for (name in this._textures) {
  59605. serializationObject.textures[name] = this._textures[name].serialize();
  59606. }
  59607. // Texture arrays
  59608. serializationObject.textureArrays = {};
  59609. for (name in this._textureArrays) {
  59610. serializationObject.textureArrays[name] = [];
  59611. var array = this._textureArrays[name];
  59612. for (var index = 0; index < array.length; index++) {
  59613. serializationObject.textureArrays[name].push(array[index].serialize());
  59614. }
  59615. }
  59616. // Float
  59617. serializationObject.floats = {};
  59618. for (name in this._floats) {
  59619. serializationObject.floats[name] = this._floats[name];
  59620. }
  59621. // Float s
  59622. serializationObject.FloatArrays = {};
  59623. for (name in this._floatsArrays) {
  59624. serializationObject.FloatArrays[name] = this._floatsArrays[name];
  59625. }
  59626. // Color3
  59627. serializationObject.colors3 = {};
  59628. for (name in this._colors3) {
  59629. serializationObject.colors3[name] = this._colors3[name].asArray();
  59630. }
  59631. // Color3 array
  59632. serializationObject.colors3Arrays = {};
  59633. for (name in this._colors3Arrays) {
  59634. serializationObject.colors3Arrays[name] = this._colors3Arrays[name];
  59635. }
  59636. // Color4
  59637. serializationObject.colors4 = {};
  59638. for (name in this._colors4) {
  59639. serializationObject.colors4[name] = this._colors4[name].asArray();
  59640. }
  59641. // Vector2
  59642. serializationObject.vectors2 = {};
  59643. for (name in this._vectors2) {
  59644. serializationObject.vectors2[name] = this._vectors2[name].asArray();
  59645. }
  59646. // Vector3
  59647. serializationObject.vectors3 = {};
  59648. for (name in this._vectors3) {
  59649. serializationObject.vectors3[name] = this._vectors3[name].asArray();
  59650. }
  59651. // Vector4
  59652. serializationObject.vectors4 = {};
  59653. for (name in this._vectors4) {
  59654. serializationObject.vectors4[name] = this._vectors4[name].asArray();
  59655. }
  59656. // Matrix
  59657. serializationObject.matrices = {};
  59658. for (name in this._matrices) {
  59659. serializationObject.matrices[name] = this._matrices[name].asArray();
  59660. }
  59661. // Matrix 3x3
  59662. serializationObject.matrices3x3 = {};
  59663. for (name in this._matrices3x3) {
  59664. serializationObject.matrices3x3[name] = this._matrices3x3[name];
  59665. }
  59666. // Matrix 2x2
  59667. serializationObject.matrices2x2 = {};
  59668. for (name in this._matrices2x2) {
  59669. serializationObject.matrices2x2[name] = this._matrices2x2[name];
  59670. }
  59671. // Vector2Array
  59672. serializationObject.vectors2Arrays = {};
  59673. for (name in this._vectors2Arrays) {
  59674. serializationObject.vectors2Arrays[name] = this._vectors2Arrays[name];
  59675. }
  59676. // Vector3Array
  59677. serializationObject.vectors3Arrays = {};
  59678. for (name in this._vectors3Arrays) {
  59679. serializationObject.vectors3Arrays[name] = this._vectors3Arrays[name];
  59680. }
  59681. return serializationObject;
  59682. };
  59683. ShaderMaterial.Parse = function (source, scene, rootUrl) {
  59684. var material = BABYLON.SerializationHelper.Parse(function () { return new ShaderMaterial(source.name, scene, source.shaderPath, source.options); }, source, scene, rootUrl);
  59685. var name;
  59686. // Texture
  59687. for (name in source.textures) {
  59688. material.setTexture(name, BABYLON.Texture.Parse(source.textures[name], scene, rootUrl));
  59689. }
  59690. // Texture arrays
  59691. for (name in source.textureArrays) {
  59692. var array = source.textureArrays[name];
  59693. var textureArray = new Array();
  59694. for (var index = 0; index < array.length; index++) {
  59695. textureArray.push(BABYLON.Texture.Parse(array[index], scene, rootUrl));
  59696. }
  59697. material.setTextureArray(name, textureArray);
  59698. }
  59699. // Float
  59700. for (name in source.floats) {
  59701. material.setFloat(name, source.floats[name]);
  59702. }
  59703. // Float s
  59704. for (name in source.floatsArrays) {
  59705. material.setFloats(name, source.floatsArrays[name]);
  59706. }
  59707. // Color3
  59708. for (name in source.colors3) {
  59709. material.setColor3(name, BABYLON.Color3.FromArray(source.colors3[name]));
  59710. }
  59711. // Color3 arrays
  59712. for (name in source.colors3Arrays) {
  59713. var colors = source.colors3Arrays[name].reduce(function (arr, num, i) {
  59714. if (i % 3 === 0) {
  59715. arr.push([num]);
  59716. }
  59717. else {
  59718. arr[arr.length - 1].push(num);
  59719. }
  59720. return arr;
  59721. }, []).map(function (color) { return BABYLON.Color3.FromArray(color); });
  59722. material.setColor3Array(name, colors);
  59723. }
  59724. // Color4
  59725. for (name in source.colors4) {
  59726. material.setColor4(name, BABYLON.Color4.FromArray(source.colors4[name]));
  59727. }
  59728. // Vector2
  59729. for (name in source.vectors2) {
  59730. material.setVector2(name, BABYLON.Vector2.FromArray(source.vectors2[name]));
  59731. }
  59732. // Vector3
  59733. for (name in source.vectors3) {
  59734. material.setVector3(name, BABYLON.Vector3.FromArray(source.vectors3[name]));
  59735. }
  59736. // Vector4
  59737. for (name in source.vectors4) {
  59738. material.setVector4(name, BABYLON.Vector4.FromArray(source.vectors4[name]));
  59739. }
  59740. // Matrix
  59741. for (name in source.matrices) {
  59742. material.setMatrix(name, BABYLON.Matrix.FromArray(source.matrices[name]));
  59743. }
  59744. // Matrix 3x3
  59745. for (name in source.matrices3x3) {
  59746. material.setMatrix3x3(name, source.matrices3x3[name]);
  59747. }
  59748. // Matrix 2x2
  59749. for (name in source.matrices2x2) {
  59750. material.setMatrix2x2(name, source.matrices2x2[name]);
  59751. }
  59752. // Vector2Array
  59753. for (name in source.vectors2Arrays) {
  59754. material.setArray2(name, source.vectors2Arrays[name]);
  59755. }
  59756. // Vector3Array
  59757. for (name in source.vectors3Arrays) {
  59758. material.setArray3(name, source.vectors3Arrays[name]);
  59759. }
  59760. return material;
  59761. };
  59762. return ShaderMaterial;
  59763. }(BABYLON.Material));
  59764. BABYLON.ShaderMaterial = ShaderMaterial;
  59765. })(BABYLON || (BABYLON = {}));
  59766. //# sourceMappingURL=babylon.shaderMaterial.js.map
  59767. var BABYLON;
  59768. (function (BABYLON) {
  59769. var GroundMesh = /** @class */ (function (_super) {
  59770. __extends(GroundMesh, _super);
  59771. function GroundMesh(name, scene) {
  59772. var _this = _super.call(this, name, scene) || this;
  59773. _this.generateOctree = false;
  59774. return _this;
  59775. }
  59776. GroundMesh.prototype.getClassName = function () {
  59777. return "GroundMesh";
  59778. };
  59779. Object.defineProperty(GroundMesh.prototype, "subdivisions", {
  59780. get: function () {
  59781. return Math.min(this._subdivisionsX, this._subdivisionsY);
  59782. },
  59783. enumerable: true,
  59784. configurable: true
  59785. });
  59786. Object.defineProperty(GroundMesh.prototype, "subdivisionsX", {
  59787. get: function () {
  59788. return this._subdivisionsX;
  59789. },
  59790. enumerable: true,
  59791. configurable: true
  59792. });
  59793. Object.defineProperty(GroundMesh.prototype, "subdivisionsY", {
  59794. get: function () {
  59795. return this._subdivisionsY;
  59796. },
  59797. enumerable: true,
  59798. configurable: true
  59799. });
  59800. GroundMesh.prototype.optimize = function (chunksCount, octreeBlocksSize) {
  59801. if (octreeBlocksSize === void 0) { octreeBlocksSize = 32; }
  59802. this._subdivisionsX = chunksCount;
  59803. this._subdivisionsY = chunksCount;
  59804. this.subdivide(chunksCount);
  59805. this.createOrUpdateSubmeshesOctree(octreeBlocksSize);
  59806. };
  59807. /**
  59808. * Returns a height (y) value in the Worl system :
  59809. * the ground altitude at the coordinates (x, z) expressed in the World system.
  59810. * Returns the ground y position if (x, z) are outside the ground surface.
  59811. */
  59812. GroundMesh.prototype.getHeightAtCoordinates = function (x, z) {
  59813. var world = this.getWorldMatrix();
  59814. var invMat = BABYLON.Tmp.Matrix[5];
  59815. world.invertToRef(invMat);
  59816. var tmpVect = BABYLON.Tmp.Vector3[8];
  59817. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, 0.0, z, invMat, tmpVect); // transform x,z in the mesh local space
  59818. x = tmpVect.x;
  59819. z = tmpVect.z;
  59820. if (x < this._minX || x > this._maxX || z < this._minZ || z > this._maxZ) {
  59821. return this.position.y;
  59822. }
  59823. if (!this._heightQuads || this._heightQuads.length == 0) {
  59824. this._initHeightQuads();
  59825. this._computeHeightQuads();
  59826. }
  59827. var facet = this._getFacetAt(x, z);
  59828. var y = -(facet.x * x + facet.z * z + facet.w) / facet.y;
  59829. // return y in the World system
  59830. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(0.0, y, 0.0, world, tmpVect);
  59831. return tmpVect.y;
  59832. };
  59833. /**
  59834. * Returns a normalized vector (Vector3) orthogonal to the ground
  59835. * at the ground coordinates (x, z) expressed in the World system.
  59836. * Returns Vector3(0.0, 1.0, 0.0) if (x, z) are outside the ground surface.
  59837. */
  59838. GroundMesh.prototype.getNormalAtCoordinates = function (x, z) {
  59839. var normal = new BABYLON.Vector3(0.0, 1.0, 0.0);
  59840. this.getNormalAtCoordinatesToRef(x, z, normal);
  59841. return normal;
  59842. };
  59843. /**
  59844. * Updates the Vector3 passed a reference with a normalized vector orthogonal to the ground
  59845. * at the ground coordinates (x, z) expressed in the World system.
  59846. * Doesn't uptade the reference Vector3 if (x, z) are outside the ground surface.
  59847. * Returns the GroundMesh.
  59848. */
  59849. GroundMesh.prototype.getNormalAtCoordinatesToRef = function (x, z, ref) {
  59850. var world = this.getWorldMatrix();
  59851. var tmpMat = BABYLON.Tmp.Matrix[5];
  59852. world.invertToRef(tmpMat);
  59853. var tmpVect = BABYLON.Tmp.Vector3[8];
  59854. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, 0.0, z, tmpMat, tmpVect); // transform x,z in the mesh local space
  59855. x = tmpVect.x;
  59856. z = tmpVect.z;
  59857. if (x < this._minX || x > this._maxX || z < this._minZ || z > this._maxZ) {
  59858. return this;
  59859. }
  59860. if (!this._heightQuads || this._heightQuads.length == 0) {
  59861. this._initHeightQuads();
  59862. this._computeHeightQuads();
  59863. }
  59864. var facet = this._getFacetAt(x, z);
  59865. BABYLON.Vector3.TransformNormalFromFloatsToRef(facet.x, facet.y, facet.z, world, ref);
  59866. return this;
  59867. };
  59868. /**
  59869. * Force the heights to be recomputed for getHeightAtCoordinates() or getNormalAtCoordinates()
  59870. * if the ground has been updated.
  59871. * This can be used in the render loop.
  59872. * Returns the GroundMesh.
  59873. */
  59874. GroundMesh.prototype.updateCoordinateHeights = function () {
  59875. if (!this._heightQuads || this._heightQuads.length == 0) {
  59876. this._initHeightQuads();
  59877. }
  59878. this._computeHeightQuads();
  59879. return this;
  59880. };
  59881. // Returns the element "facet" from the heightQuads array relative to (x, z) local coordinates
  59882. GroundMesh.prototype._getFacetAt = function (x, z) {
  59883. // retrieve col and row from x, z coordinates in the ground local system
  59884. var col = Math.floor((x + this._maxX) * this._subdivisionsX / this._width);
  59885. var row = Math.floor(-(z + this._maxZ) * this._subdivisionsY / this._height + this._subdivisionsY);
  59886. var quad = this._heightQuads[row * this._subdivisionsX + col];
  59887. var facet;
  59888. if (z < quad.slope.x * x + quad.slope.y) {
  59889. facet = quad.facet1;
  59890. }
  59891. else {
  59892. facet = quad.facet2;
  59893. }
  59894. return facet;
  59895. };
  59896. // Creates and populates the heightMap array with "facet" elements :
  59897. // a quad is two triangular facets separated by a slope, so a "facet" element is 1 slope + 2 facets
  59898. // slope : Vector2(c, h) = 2D diagonal line equation setting appart two triangular facets in a quad : z = cx + h
  59899. // facet1 : Vector4(a, b, c, d) = first facet 3D plane equation : ax + by + cz + d = 0
  59900. // facet2 : Vector4(a, b, c, d) = second facet 3D plane equation : ax + by + cz + d = 0
  59901. // Returns the GroundMesh.
  59902. GroundMesh.prototype._initHeightQuads = function () {
  59903. var subdivisionsX = this._subdivisionsX;
  59904. var subdivisionsY = this._subdivisionsY;
  59905. this._heightQuads = new Array();
  59906. for (var row = 0; row < subdivisionsY; row++) {
  59907. for (var col = 0; col < subdivisionsX; col++) {
  59908. 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) };
  59909. this._heightQuads[row * subdivisionsX + col] = quad;
  59910. }
  59911. }
  59912. return this;
  59913. };
  59914. // Compute each quad element values and update the the heightMap array :
  59915. // slope : Vector2(c, h) = 2D diagonal line equation setting appart two triangular facets in a quad : z = cx + h
  59916. // facet1 : Vector4(a, b, c, d) = first facet 3D plane equation : ax + by + cz + d = 0
  59917. // facet2 : Vector4(a, b, c, d) = second facet 3D plane equation : ax + by + cz + d = 0
  59918. // Returns the GroundMesh.
  59919. GroundMesh.prototype._computeHeightQuads = function () {
  59920. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  59921. if (!positions) {
  59922. return this;
  59923. }
  59924. var v1 = BABYLON.Tmp.Vector3[3];
  59925. var v2 = BABYLON.Tmp.Vector3[2];
  59926. var v3 = BABYLON.Tmp.Vector3[1];
  59927. var v4 = BABYLON.Tmp.Vector3[0];
  59928. var v1v2 = BABYLON.Tmp.Vector3[4];
  59929. var v1v3 = BABYLON.Tmp.Vector3[5];
  59930. var v1v4 = BABYLON.Tmp.Vector3[6];
  59931. var norm1 = BABYLON.Tmp.Vector3[7];
  59932. var norm2 = BABYLON.Tmp.Vector3[8];
  59933. var i = 0;
  59934. var j = 0;
  59935. var k = 0;
  59936. var cd = 0; // 2D slope coefficient : z = cd * x + h
  59937. var h = 0;
  59938. var d1 = 0; // facet plane equation : ax + by + cz + d = 0
  59939. var d2 = 0;
  59940. var subdivisionsX = this._subdivisionsX;
  59941. var subdivisionsY = this._subdivisionsY;
  59942. for (var row = 0; row < subdivisionsY; row++) {
  59943. for (var col = 0; col < subdivisionsX; col++) {
  59944. i = col * 3;
  59945. j = row * (subdivisionsX + 1) * 3;
  59946. k = (row + 1) * (subdivisionsX + 1) * 3;
  59947. v1.x = positions[j + i];
  59948. v1.y = positions[j + i + 1];
  59949. v1.z = positions[j + i + 2];
  59950. v2.x = positions[j + i + 3];
  59951. v2.y = positions[j + i + 4];
  59952. v2.z = positions[j + i + 5];
  59953. v3.x = positions[k + i];
  59954. v3.y = positions[k + i + 1];
  59955. v3.z = positions[k + i + 2];
  59956. v4.x = positions[k + i + 3];
  59957. v4.y = positions[k + i + 4];
  59958. v4.z = positions[k + i + 5];
  59959. // 2D slope V1V4
  59960. cd = (v4.z - v1.z) / (v4.x - v1.x);
  59961. h = v1.z - cd * v1.x; // v1 belongs to the slope
  59962. // facet equations :
  59963. // we compute each facet normal vector
  59964. // the equation of the facet plane is : norm.x * x + norm.y * y + norm.z * z + d = 0
  59965. // we compute the value d by applying the equation to v1 which belongs to the plane
  59966. // then we store the facet equation in a Vector4
  59967. v2.subtractToRef(v1, v1v2);
  59968. v3.subtractToRef(v1, v1v3);
  59969. v4.subtractToRef(v1, v1v4);
  59970. BABYLON.Vector3.CrossToRef(v1v4, v1v3, norm1); // caution : CrossToRef uses the Tmp class
  59971. BABYLON.Vector3.CrossToRef(v1v2, v1v4, norm2);
  59972. norm1.normalize();
  59973. norm2.normalize();
  59974. d1 = -(norm1.x * v1.x + norm1.y * v1.y + norm1.z * v1.z);
  59975. d2 = -(norm2.x * v2.x + norm2.y * v2.y + norm2.z * v2.z);
  59976. var quad = this._heightQuads[row * subdivisionsX + col];
  59977. quad.slope.copyFromFloats(cd, h);
  59978. quad.facet1.copyFromFloats(norm1.x, norm1.y, norm1.z, d1);
  59979. quad.facet2.copyFromFloats(norm2.x, norm2.y, norm2.z, d2);
  59980. }
  59981. }
  59982. return this;
  59983. };
  59984. GroundMesh.prototype.serialize = function (serializationObject) {
  59985. _super.prototype.serialize.call(this, serializationObject);
  59986. serializationObject.subdivisionsX = this._subdivisionsX;
  59987. serializationObject.subdivisionsY = this._subdivisionsY;
  59988. serializationObject.minX = this._minX;
  59989. serializationObject.maxX = this._maxX;
  59990. serializationObject.minZ = this._minZ;
  59991. serializationObject.maxZ = this._maxZ;
  59992. serializationObject.width = this._width;
  59993. serializationObject.height = this._height;
  59994. };
  59995. GroundMesh.Parse = function (parsedMesh, scene) {
  59996. var result = new GroundMesh(parsedMesh.name, scene);
  59997. result._subdivisionsX = parsedMesh.subdivisionsX || 1;
  59998. result._subdivisionsY = parsedMesh.subdivisionsY || 1;
  59999. result._minX = parsedMesh.minX;
  60000. result._maxX = parsedMesh.maxX;
  60001. result._minZ = parsedMesh.minZ;
  60002. result._maxZ = parsedMesh.maxZ;
  60003. result._width = parsedMesh.width;
  60004. result._height = parsedMesh.height;
  60005. return result;
  60006. };
  60007. return GroundMesh;
  60008. }(BABYLON.Mesh));
  60009. BABYLON.GroundMesh = GroundMesh;
  60010. })(BABYLON || (BABYLON = {}));
  60011. //# sourceMappingURL=babylon.groundMesh.js.map
  60012. var BABYLON;
  60013. (function (BABYLON) {
  60014. /**
  60015. * Creates an instance based on a source mesh.
  60016. */
  60017. var InstancedMesh = /** @class */ (function (_super) {
  60018. __extends(InstancedMesh, _super);
  60019. function InstancedMesh(name, source) {
  60020. var _this = _super.call(this, name, source.getScene()) || this;
  60021. source.instances.push(_this);
  60022. _this._sourceMesh = source;
  60023. _this.position.copyFrom(source.position);
  60024. _this.rotation.copyFrom(source.rotation);
  60025. _this.scaling.copyFrom(source.scaling);
  60026. if (source.rotationQuaternion) {
  60027. _this.rotationQuaternion = source.rotationQuaternion.clone();
  60028. }
  60029. _this.infiniteDistance = source.infiniteDistance;
  60030. _this.setPivotMatrix(source.getPivotMatrix());
  60031. _this.refreshBoundingInfo();
  60032. _this._syncSubMeshes();
  60033. return _this;
  60034. }
  60035. /**
  60036. * Returns the string "InstancedMesh".
  60037. */
  60038. InstancedMesh.prototype.getClassName = function () {
  60039. return "InstancedMesh";
  60040. };
  60041. Object.defineProperty(InstancedMesh.prototype, "receiveShadows", {
  60042. // Methods
  60043. get: function () {
  60044. return this._sourceMesh.receiveShadows;
  60045. },
  60046. enumerable: true,
  60047. configurable: true
  60048. });
  60049. Object.defineProperty(InstancedMesh.prototype, "material", {
  60050. get: function () {
  60051. return this._sourceMesh.material;
  60052. },
  60053. enumerable: true,
  60054. configurable: true
  60055. });
  60056. Object.defineProperty(InstancedMesh.prototype, "visibility", {
  60057. get: function () {
  60058. return this._sourceMesh.visibility;
  60059. },
  60060. enumerable: true,
  60061. configurable: true
  60062. });
  60063. Object.defineProperty(InstancedMesh.prototype, "skeleton", {
  60064. get: function () {
  60065. return this._sourceMesh.skeleton;
  60066. },
  60067. enumerable: true,
  60068. configurable: true
  60069. });
  60070. Object.defineProperty(InstancedMesh.prototype, "renderingGroupId", {
  60071. get: function () {
  60072. return this._sourceMesh.renderingGroupId;
  60073. },
  60074. set: function (value) {
  60075. if (!this._sourceMesh || value === this._sourceMesh.renderingGroupId) {
  60076. return;
  60077. }
  60078. //no-op with warning
  60079. BABYLON.Tools.Warn("Note - setting renderingGroupId of an instanced mesh has no effect on the scene");
  60080. },
  60081. enumerable: true,
  60082. configurable: true
  60083. });
  60084. /**
  60085. * Returns the total number of vertices (integer).
  60086. */
  60087. InstancedMesh.prototype.getTotalVertices = function () {
  60088. return this._sourceMesh.getTotalVertices();
  60089. };
  60090. Object.defineProperty(InstancedMesh.prototype, "sourceMesh", {
  60091. get: function () {
  60092. return this._sourceMesh;
  60093. },
  60094. enumerable: true,
  60095. configurable: true
  60096. });
  60097. /**
  60098. * Is this node ready to be used/rendered
  60099. * @param completeCheck defines if a complete check (including materials and lights) has to be done (false by default)
  60100. * @return {boolean} is it ready
  60101. */
  60102. InstancedMesh.prototype.isReady = function (completeCheck) {
  60103. if (completeCheck === void 0) { completeCheck = false; }
  60104. return this._sourceMesh.isReady(completeCheck, true);
  60105. };
  60106. /**
  60107. * Returns a float array or a Float32Array of the requested kind of data : positons, normals, uvs, etc.
  60108. */
  60109. InstancedMesh.prototype.getVerticesData = function (kind, copyWhenShared) {
  60110. return this._sourceMesh.getVerticesData(kind, copyWhenShared);
  60111. };
  60112. /**
  60113. * Sets the vertex data of the mesh geometry for the requested `kind`.
  60114. * If the mesh has no geometry, a new Geometry object is set to the mesh and then passed this vertex data.
  60115. * The `data` are either a numeric array either a Float32Array.
  60116. * The parameter `updatable` is passed as is to the underlying Geometry object constructor (if initianilly none) or updater.
  60117. * 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).
  60118. * Note that a new underlying VertexBuffer object is created each call.
  60119. * If the `kind` is the `PositionKind`, the mesh BoundingInfo is renewed, so the bounding box and sphere, and the mesh World Matrix is recomputed.
  60120. *
  60121. * Possible `kind` values :
  60122. * - BABYLON.VertexBuffer.PositionKind
  60123. * - BABYLON.VertexBuffer.UVKind
  60124. * - BABYLON.VertexBuffer.UV2Kind
  60125. * - BABYLON.VertexBuffer.UV3Kind
  60126. * - BABYLON.VertexBuffer.UV4Kind
  60127. * - BABYLON.VertexBuffer.UV5Kind
  60128. * - BABYLON.VertexBuffer.UV6Kind
  60129. * - BABYLON.VertexBuffer.ColorKind
  60130. * - BABYLON.VertexBuffer.MatricesIndicesKind
  60131. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  60132. * - BABYLON.VertexBuffer.MatricesWeightsKind
  60133. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  60134. *
  60135. * Returns the Mesh.
  60136. */
  60137. InstancedMesh.prototype.setVerticesData = function (kind, data, updatable, stride) {
  60138. if (this.sourceMesh) {
  60139. this.sourceMesh.setVerticesData(kind, data, updatable, stride);
  60140. }
  60141. return this.sourceMesh;
  60142. };
  60143. /**
  60144. * Updates the existing vertex data of the mesh geometry for the requested `kind`.
  60145. * If the mesh has no geometry, it is simply returned as it is.
  60146. * The `data` are either a numeric array either a Float32Array.
  60147. * No new underlying VertexBuffer object is created.
  60148. * 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.
  60149. * If the parameter `makeItUnique` is true, a new global geometry is created from this positions and is set to the mesh.
  60150. *
  60151. * Possible `kind` values :
  60152. * - BABYLON.VertexBuffer.PositionKind
  60153. * - BABYLON.VertexBuffer.UVKind
  60154. * - BABYLON.VertexBuffer.UV2Kind
  60155. * - BABYLON.VertexBuffer.UV3Kind
  60156. * - BABYLON.VertexBuffer.UV4Kind
  60157. * - BABYLON.VertexBuffer.UV5Kind
  60158. * - BABYLON.VertexBuffer.UV6Kind
  60159. * - BABYLON.VertexBuffer.ColorKind
  60160. * - BABYLON.VertexBuffer.MatricesIndicesKind
  60161. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  60162. * - BABYLON.VertexBuffer.MatricesWeightsKind
  60163. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  60164. *
  60165. * Returns the Mesh.
  60166. */
  60167. InstancedMesh.prototype.updateVerticesData = function (kind, data, updateExtends, makeItUnique) {
  60168. if (this.sourceMesh) {
  60169. this.sourceMesh.updateVerticesData(kind, data, updateExtends, makeItUnique);
  60170. }
  60171. return this.sourceMesh;
  60172. };
  60173. /**
  60174. * Sets the mesh indices.
  60175. * Expects an array populated with integers or a typed array (Int32Array, Uint32Array, Uint16Array).
  60176. * If the mesh has no geometry, a new Geometry object is created and set to the mesh.
  60177. * This method creates a new index buffer each call.
  60178. * Returns the Mesh.
  60179. */
  60180. InstancedMesh.prototype.setIndices = function (indices, totalVertices) {
  60181. if (totalVertices === void 0) { totalVertices = null; }
  60182. if (this.sourceMesh) {
  60183. this.sourceMesh.setIndices(indices, totalVertices);
  60184. }
  60185. return this.sourceMesh;
  60186. };
  60187. /**
  60188. * Boolean : True if the mesh owns the requested kind of data.
  60189. */
  60190. InstancedMesh.prototype.isVerticesDataPresent = function (kind) {
  60191. return this._sourceMesh.isVerticesDataPresent(kind);
  60192. };
  60193. /**
  60194. * Returns an array of indices (IndicesArray).
  60195. */
  60196. InstancedMesh.prototype.getIndices = function () {
  60197. return this._sourceMesh.getIndices();
  60198. };
  60199. Object.defineProperty(InstancedMesh.prototype, "_positions", {
  60200. get: function () {
  60201. return this._sourceMesh._positions;
  60202. },
  60203. enumerable: true,
  60204. configurable: true
  60205. });
  60206. /**
  60207. * Sets a new updated BoundingInfo to the mesh.
  60208. * Returns the mesh.
  60209. */
  60210. InstancedMesh.prototype.refreshBoundingInfo = function () {
  60211. var meshBB = this._sourceMesh.getBoundingInfo();
  60212. this._boundingInfo = new BABYLON.BoundingInfo(meshBB.minimum.clone(), meshBB.maximum.clone());
  60213. this._updateBoundingInfo();
  60214. return this;
  60215. };
  60216. InstancedMesh.prototype._preActivate = function () {
  60217. if (this._currentLOD) {
  60218. this._currentLOD._preActivate();
  60219. }
  60220. return this;
  60221. };
  60222. InstancedMesh.prototype._activate = function (renderId) {
  60223. if (this._currentLOD) {
  60224. this._currentLOD._registerInstanceForRenderId(this, renderId);
  60225. }
  60226. return this;
  60227. };
  60228. /**
  60229. * Returns the current associated LOD AbstractMesh.
  60230. */
  60231. InstancedMesh.prototype.getLOD = function (camera) {
  60232. if (!camera) {
  60233. return this;
  60234. }
  60235. var boundingInfo = this.getBoundingInfo();
  60236. this._currentLOD = this.sourceMesh.getLOD(camera, boundingInfo.boundingSphere);
  60237. if (this._currentLOD === this.sourceMesh) {
  60238. return this;
  60239. }
  60240. return this._currentLOD;
  60241. };
  60242. InstancedMesh.prototype._syncSubMeshes = function () {
  60243. this.releaseSubMeshes();
  60244. if (this._sourceMesh.subMeshes) {
  60245. for (var index = 0; index < this._sourceMesh.subMeshes.length; index++) {
  60246. this._sourceMesh.subMeshes[index].clone(this, this._sourceMesh);
  60247. }
  60248. }
  60249. return this;
  60250. };
  60251. InstancedMesh.prototype._generatePointsArray = function () {
  60252. return this._sourceMesh._generatePointsArray();
  60253. };
  60254. /**
  60255. * Creates a new InstancedMesh from the current mesh.
  60256. * - name (string) : the cloned mesh name
  60257. * - newParent (optional Node) : the optional Node to parent the clone to.
  60258. * - doNotCloneChildren (optional boolean, default `false`) : if `true` the model children aren't cloned.
  60259. *
  60260. * Returns the clone.
  60261. */
  60262. InstancedMesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  60263. var result = this._sourceMesh.createInstance(name);
  60264. // Deep copy
  60265. BABYLON.Tools.DeepCopy(this, result, ["name", "subMeshes", "uniqueId"], []);
  60266. // Bounding info
  60267. this.refreshBoundingInfo();
  60268. // Parent
  60269. if (newParent) {
  60270. result.parent = newParent;
  60271. }
  60272. if (!doNotCloneChildren) {
  60273. // Children
  60274. for (var index = 0; index < this.getScene().meshes.length; index++) {
  60275. var mesh = this.getScene().meshes[index];
  60276. if (mesh.parent === this) {
  60277. mesh.clone(mesh.name, result);
  60278. }
  60279. }
  60280. }
  60281. result.computeWorldMatrix(true);
  60282. return result;
  60283. };
  60284. /**
  60285. * Disposes the InstancedMesh.
  60286. * Returns nothing.
  60287. */
  60288. InstancedMesh.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  60289. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  60290. // Remove from mesh
  60291. var index = this._sourceMesh.instances.indexOf(this);
  60292. this._sourceMesh.instances.splice(index, 1);
  60293. _super.prototype.dispose.call(this, doNotRecurse, disposeMaterialAndTextures);
  60294. };
  60295. return InstancedMesh;
  60296. }(BABYLON.AbstractMesh));
  60297. BABYLON.InstancedMesh = InstancedMesh;
  60298. })(BABYLON || (BABYLON = {}));
  60299. //# sourceMappingURL=babylon.instancedMesh.js.map
  60300. var BABYLON;
  60301. (function (BABYLON) {
  60302. var LinesMesh = /** @class */ (function (_super) {
  60303. __extends(LinesMesh, _super);
  60304. function LinesMesh(name, scene, parent, source, doNotCloneChildren, useVertexColor, useVertexAlpha) {
  60305. if (scene === void 0) { scene = null; }
  60306. if (parent === void 0) { parent = null; }
  60307. var _this = _super.call(this, name, scene, parent, source, doNotCloneChildren) || this;
  60308. _this.useVertexColor = useVertexColor;
  60309. _this.useVertexAlpha = useVertexAlpha;
  60310. _this.color = new BABYLON.Color3(1, 1, 1);
  60311. _this.alpha = 1;
  60312. if (source) {
  60313. _this.color = source.color.clone();
  60314. _this.alpha = source.alpha;
  60315. _this.useVertexColor = source.useVertexColor;
  60316. _this.useVertexAlpha = source.useVertexAlpha;
  60317. }
  60318. _this._intersectionThreshold = 0.1;
  60319. var defines = [];
  60320. var options = {
  60321. attributes: [BABYLON.VertexBuffer.PositionKind],
  60322. uniforms: ["world", "viewProjection"],
  60323. needAlphaBlending: true,
  60324. defines: defines
  60325. };
  60326. if (useVertexAlpha === false) {
  60327. options.needAlphaBlending = false;
  60328. }
  60329. if (!useVertexColor) {
  60330. options.uniforms.push("color");
  60331. }
  60332. else {
  60333. options.defines.push("#define VERTEXCOLOR");
  60334. options.attributes.push(BABYLON.VertexBuffer.ColorKind);
  60335. }
  60336. _this._colorShader = new BABYLON.ShaderMaterial("colorShader", _this.getScene(), "color", options);
  60337. return _this;
  60338. }
  60339. Object.defineProperty(LinesMesh.prototype, "intersectionThreshold", {
  60340. /**
  60341. * The intersection Threshold is the margin applied when intersection a segment of the LinesMesh with a Ray.
  60342. * This margin is expressed in world space coordinates, so its value may vary.
  60343. * Default value is 0.1
  60344. * @returns the intersection Threshold value.
  60345. */
  60346. get: function () {
  60347. return this._intersectionThreshold;
  60348. },
  60349. /**
  60350. * The intersection Threshold is the margin applied when intersection a segment of the LinesMesh with a Ray.
  60351. * This margin is expressed in world space coordinates, so its value may vary.
  60352. * @param value the new threshold to apply
  60353. */
  60354. set: function (value) {
  60355. if (this._intersectionThreshold === value) {
  60356. return;
  60357. }
  60358. this._intersectionThreshold = value;
  60359. if (this.geometry) {
  60360. this.geometry.boundingBias = new BABYLON.Vector2(0, value);
  60361. }
  60362. },
  60363. enumerable: true,
  60364. configurable: true
  60365. });
  60366. /**
  60367. * Returns the string "LineMesh"
  60368. */
  60369. LinesMesh.prototype.getClassName = function () {
  60370. return "LinesMesh";
  60371. };
  60372. Object.defineProperty(LinesMesh.prototype, "material", {
  60373. get: function () {
  60374. return this._colorShader;
  60375. },
  60376. set: function (value) {
  60377. // Do nothing
  60378. },
  60379. enumerable: true,
  60380. configurable: true
  60381. });
  60382. Object.defineProperty(LinesMesh.prototype, "checkCollisions", {
  60383. get: function () {
  60384. return false;
  60385. },
  60386. enumerable: true,
  60387. configurable: true
  60388. });
  60389. LinesMesh.prototype.createInstance = function (name) {
  60390. throw new Error("LinesMeshes do not support createInstance.");
  60391. };
  60392. LinesMesh.prototype._bind = function (subMesh, effect, fillMode) {
  60393. if (!this._geometry) {
  60394. return this;
  60395. }
  60396. // VBOs
  60397. this._geometry._bind(this._colorShader.getEffect());
  60398. // Color
  60399. if (!this.useVertexColor) {
  60400. this._colorShader.setColor4("color", this.color.toColor4(this.alpha));
  60401. }
  60402. return this;
  60403. };
  60404. LinesMesh.prototype._draw = function (subMesh, fillMode, instancesCount) {
  60405. if (!this._geometry || !this._geometry.getVertexBuffers() || (!this._unIndexed && !this._geometry.getIndexBuffer())) {
  60406. return this;
  60407. }
  60408. var engine = this.getScene().getEngine();
  60409. // Draw order
  60410. engine.drawElementsType(BABYLON.Material.LineListDrawMode, subMesh.indexStart, subMesh.indexCount);
  60411. return this;
  60412. };
  60413. LinesMesh.prototype.dispose = function (doNotRecurse) {
  60414. this._colorShader.dispose();
  60415. _super.prototype.dispose.call(this, doNotRecurse);
  60416. };
  60417. /**
  60418. * Returns a new LineMesh object cloned from the current one.
  60419. */
  60420. LinesMesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  60421. return new LinesMesh(name, this.getScene(), newParent, this, doNotCloneChildren);
  60422. };
  60423. return LinesMesh;
  60424. }(BABYLON.Mesh));
  60425. BABYLON.LinesMesh = LinesMesh;
  60426. })(BABYLON || (BABYLON = {}));
  60427. //# sourceMappingURL=babylon.linesMesh.js.map
  60428. var BABYLON;
  60429. (function (BABYLON) {
  60430. /**
  60431. * Class containing static functions to help procedurally build meshes
  60432. */
  60433. var MeshBuilder = /** @class */ (function () {
  60434. function MeshBuilder() {
  60435. }
  60436. MeshBuilder.updateSideOrientation = function (orientation) {
  60437. if (orientation == BABYLON.Mesh.DOUBLESIDE) {
  60438. return BABYLON.Mesh.DOUBLESIDE;
  60439. }
  60440. if (orientation === undefined || orientation === null) {
  60441. return BABYLON.Mesh.FRONTSIDE;
  60442. }
  60443. return orientation;
  60444. };
  60445. /**
  60446. * Creates a box mesh
  60447. * * The parameter `size` sets the size (float) of each box side (default 1)
  60448. * * You can set some different box dimensions by using the parameters `width`, `height` and `depth` (all by default have the same value than `size`)
  60449. * * 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)
  60450. * * Please read this tutorial : http://doc.babylonjs.com/tutorials/CreateBox_Per_Face_Textures_And_Colors
  60451. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  60452. * * 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
  60453. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  60454. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#box
  60455. * @param name defines the name of the mesh
  60456. * @param options defines the options used to create the mesh
  60457. * @param scene defines the hosting scene
  60458. * @returns the box mesh
  60459. */
  60460. MeshBuilder.CreateBox = function (name, options, scene) {
  60461. if (scene === void 0) { scene = null; }
  60462. var box = new BABYLON.Mesh(name, scene);
  60463. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  60464. box._originalBuilderSideOrientation = options.sideOrientation;
  60465. var vertexData = BABYLON.VertexData.CreateBox(options);
  60466. vertexData.applyToMesh(box, options.updatable);
  60467. return box;
  60468. };
  60469. /**
  60470. * Creates a sphere mesh
  60471. * * The parameter `diameter` sets the diameter size (float) of the sphere (default 1)
  60472. * * 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`)
  60473. * * The parameter `segments` sets the sphere number of horizontal stripes (positive integer, default 32)
  60474. * * 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
  60475. * * 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)
  60476. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  60477. * * 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
  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 sphere mesh
  60483. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#sphere
  60484. */
  60485. MeshBuilder.CreateSphere = function (name, options, scene) {
  60486. var sphere = new BABYLON.Mesh(name, scene);
  60487. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  60488. sphere._originalBuilderSideOrientation = options.sideOrientation;
  60489. var vertexData = BABYLON.VertexData.CreateSphere(options);
  60490. vertexData.applyToMesh(sphere, options.updatable);
  60491. return sphere;
  60492. };
  60493. /**
  60494. * Creates a plane polygonal mesh. By default, this is a disc
  60495. * * The parameter `radius` sets the radius size (float) of the polygon (default 0.5)
  60496. * * 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
  60497. * * 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
  60498. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  60499. * * 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
  60500. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  60501. * @param name defines the name of the mesh
  60502. * @param options defines the options used to create the mesh
  60503. * @param scene defines the hosting scene
  60504. * @returns the plane polygonal mesh
  60505. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#disc
  60506. */
  60507. MeshBuilder.CreateDisc = function (name, options, scene) {
  60508. if (scene === void 0) { scene = null; }
  60509. var disc = new BABYLON.Mesh(name, scene);
  60510. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  60511. disc._originalBuilderSideOrientation = options.sideOrientation;
  60512. var vertexData = BABYLON.VertexData.CreateDisc(options);
  60513. vertexData.applyToMesh(disc, options.updatable);
  60514. return disc;
  60515. };
  60516. /**
  60517. * Creates a sphere based upon an icosahedron with 20 triangular faces which can be subdivided
  60518. * * The parameter `radius` sets the radius size (float) of the icosphere (default 1)
  60519. * * 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`)
  60520. * * The parameter `subdivisions` sets the number of subdivisions (postive integer, default 4). The more subdivisions, the more faces on the icosphere whatever its size
  60521. * * 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
  60522. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  60523. * * 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
  60524. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  60525. * @param name defines the name of the mesh
  60526. * @param options defines the options used to create the mesh
  60527. * @param scene defines the hosting scene
  60528. * @returns the icosahedron mesh
  60529. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#icosphere
  60530. */
  60531. MeshBuilder.CreateIcoSphere = function (name, options, scene) {
  60532. var sphere = new BABYLON.Mesh(name, scene);
  60533. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  60534. sphere._originalBuilderSideOrientation = options.sideOrientation;
  60535. var vertexData = BABYLON.VertexData.CreateIcoSphere(options);
  60536. vertexData.applyToMesh(sphere, options.updatable);
  60537. return sphere;
  60538. };
  60539. ;
  60540. /**
  60541. * Creates a ribbon mesh. The ribbon is a parametric shape. It has no predefined shape. Its final shape will depend on the input parameters
  60542. * * The parameter `pathArray` is a required array of paths, what are each an array of successive Vector3. The pathArray parameter depicts the ribbon geometry
  60543. * * The parameter `closeArray` (boolean, default false) creates a seam between the first and the last paths of the path array
  60544. * * The parameter `closePath` (boolean, default false) creates a seam between the first and the last points of each path of the path array
  60545. * * 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
  60546. * * 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
  60547. * * 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
  60548. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  60549. * * 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
  60550. * * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture
  60551. * * 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
  60552. * * The parameters `colors` is an optional flat array of `Color4` to set/update each ribbon vertex with its own custom color values
  60553. * * 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
  60554. * * Moreover, you can use the parameter `color` with `instance` (to update the ribbon), only if you previously used it at creation time
  60555. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  60556. * @param name defines the name of the mesh
  60557. * @param options defines the options used to create the mesh
  60558. * @param scene defines the hosting scene
  60559. * @returns the ribbon mesh
  60560. * @see http://doc.babylonjs.com/tutorials/Ribbon_Tutorial
  60561. * @see http://doc.babylonjs.com/tutorials/Parametric_Shapes
  60562. */
  60563. MeshBuilder.CreateRibbon = function (name, options, scene) {
  60564. if (scene === void 0) { scene = null; }
  60565. var pathArray = options.pathArray;
  60566. var closeArray = options.closeArray;
  60567. var closePath = options.closePath;
  60568. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  60569. var instance = options.instance;
  60570. var updatable = options.updatable;
  60571. if (instance) { // existing ribbon instance update
  60572. // positionFunction : ribbon case
  60573. // only pathArray and sideOrientation parameters are taken into account for positions update
  60574. BABYLON.Vector3.FromFloatsToRef(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, BABYLON.Tmp.Vector3[0]); // minimum
  60575. BABYLON.Vector3.FromFloatsToRef(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE, BABYLON.Tmp.Vector3[1]);
  60576. var positionFunction = function (positions) {
  60577. var minlg = pathArray[0].length;
  60578. var i = 0;
  60579. var ns = (instance._originalBuilderSideOrientation === BABYLON.Mesh.DOUBLESIDE) ? 2 : 1;
  60580. for (var si = 1; si <= ns; si++) {
  60581. for (var p = 0; p < pathArray.length; p++) {
  60582. var path = pathArray[p];
  60583. var l = path.length;
  60584. minlg = (minlg < l) ? minlg : l;
  60585. var j = 0;
  60586. while (j < minlg) {
  60587. positions[i] = path[j].x;
  60588. positions[i + 1] = path[j].y;
  60589. positions[i + 2] = path[j].z;
  60590. if (path[j].x < BABYLON.Tmp.Vector3[0].x) {
  60591. BABYLON.Tmp.Vector3[0].x = path[j].x;
  60592. }
  60593. if (path[j].x > BABYLON.Tmp.Vector3[1].x) {
  60594. BABYLON.Tmp.Vector3[1].x = path[j].x;
  60595. }
  60596. if (path[j].y < BABYLON.Tmp.Vector3[0].y) {
  60597. BABYLON.Tmp.Vector3[0].y = path[j].y;
  60598. }
  60599. if (path[j].y > BABYLON.Tmp.Vector3[1].y) {
  60600. BABYLON.Tmp.Vector3[1].y = path[j].y;
  60601. }
  60602. if (path[j].z < BABYLON.Tmp.Vector3[0].z) {
  60603. BABYLON.Tmp.Vector3[0].z = path[j].z;
  60604. }
  60605. if (path[j].z > BABYLON.Tmp.Vector3[1].z) {
  60606. BABYLON.Tmp.Vector3[1].z = path[j].z;
  60607. }
  60608. j++;
  60609. i += 3;
  60610. }
  60611. if (instance._closePath) {
  60612. positions[i] = path[0].x;
  60613. positions[i + 1] = path[0].y;
  60614. positions[i + 2] = path[0].z;
  60615. i += 3;
  60616. }
  60617. }
  60618. }
  60619. };
  60620. var positions = instance.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  60621. positionFunction(positions);
  60622. instance._boundingInfo = new BABYLON.BoundingInfo(BABYLON.Tmp.Vector3[0], BABYLON.Tmp.Vector3[1]);
  60623. instance._boundingInfo.update(instance._worldMatrix);
  60624. instance.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions, false, false);
  60625. if (options.colors) {
  60626. var colors = instance.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  60627. for (var c = 0; c < options.colors.length; c++) {
  60628. colors[c * 4] = options.colors[c].r;
  60629. colors[c * 4 + 1] = options.colors[c].g;
  60630. colors[c * 4 + 2] = options.colors[c].b;
  60631. colors[c * 4 + 3] = options.colors[c].a;
  60632. }
  60633. instance.updateVerticesData(BABYLON.VertexBuffer.ColorKind, colors, false, false);
  60634. }
  60635. if (options.uvs) {
  60636. var uvs = instance.getVerticesData(BABYLON.VertexBuffer.UVKind);
  60637. for (var i = 0; i < options.uvs.length; i++) {
  60638. uvs[i * 2] = options.uvs[i].x;
  60639. uvs[i * 2 + 1] = options.uvs[i].y;
  60640. }
  60641. instance.updateVerticesData(BABYLON.VertexBuffer.UVKind, uvs, false, false);
  60642. }
  60643. if (!instance.areNormalsFrozen || instance.isFacetDataEnabled) {
  60644. var indices = instance.getIndices();
  60645. var normals = instance.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  60646. var params = instance.isFacetDataEnabled ? instance.getFacetDataParameters() : null;
  60647. BABYLON.VertexData.ComputeNormals(positions, indices, normals, params);
  60648. if (instance._closePath) {
  60649. var indexFirst = 0;
  60650. var indexLast = 0;
  60651. for (var p = 0; p < pathArray.length; p++) {
  60652. indexFirst = instance._idx[p] * 3;
  60653. if (p + 1 < pathArray.length) {
  60654. indexLast = (instance._idx[p + 1] - 1) * 3;
  60655. }
  60656. else {
  60657. indexLast = normals.length - 3;
  60658. }
  60659. normals[indexFirst] = (normals[indexFirst] + normals[indexLast]) * 0.5;
  60660. normals[indexFirst + 1] = (normals[indexFirst + 1] + normals[indexLast + 1]) * 0.5;
  60661. normals[indexFirst + 2] = (normals[indexFirst + 2] + normals[indexLast + 2]) * 0.5;
  60662. normals[indexLast] = normals[indexFirst];
  60663. normals[indexLast + 1] = normals[indexFirst + 1];
  60664. normals[indexLast + 2] = normals[indexFirst + 2];
  60665. }
  60666. }
  60667. if (!(instance.areNormalsFrozen)) {
  60668. instance.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normals, false, false);
  60669. }
  60670. }
  60671. return instance;
  60672. }
  60673. else { // new ribbon creation
  60674. var ribbon = new BABYLON.Mesh(name, scene);
  60675. ribbon._originalBuilderSideOrientation = sideOrientation;
  60676. var vertexData = BABYLON.VertexData.CreateRibbon(options);
  60677. if (closePath) {
  60678. ribbon._idx = vertexData._idx;
  60679. }
  60680. ribbon._closePath = closePath;
  60681. ribbon._closeArray = closeArray;
  60682. vertexData.applyToMesh(ribbon, updatable);
  60683. return ribbon;
  60684. }
  60685. };
  60686. /**
  60687. * Creates a cylinder or a cone mesh
  60688. * * The parameter `height` sets the height size (float) of the cylinder/cone (float, default 2).
  60689. * * The parameter `diameter` sets the diameter of the top and bottom cap at once (float, default 1).
  60690. * * 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.
  60691. * * The parameter `tessellation` sets the number of cylinder sides (positive integer, default 24). Set it to 3 to get a prism for instance.
  60692. * * The parameter `subdivisions` sets the number of rings along the cylinder height (positive integer, default 1).
  60693. * * The parameter `hasRings` (boolean, default false) makes the subdivisions independent from each other, so they become different faces.
  60694. * * The parameter `enclose` (boolean, default false) adds two extra faces per subdivision to a sliced cylinder to close it around its height axis.
  60695. * * The parameter `arc` (float, default 1) is the ratio (max 1) to apply to the circumference to slice the cylinder.
  60696. * * 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).
  60697. * * 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
  60698. * * Now, if the cylinder has 5 independent subdivisions (hasRings = true), n equals : top face + 5 stripe surfaces + bottom face = 2 + 5 = 7
  60699. * * 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
  60700. * * 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.
  60701. * * If `enclose` is false, a ring surface is one element.
  60702. * * If `enclose` is true, a ring surface is 3 successive elements in the array : the tubular surface, then the two closing faces.
  60703. * * 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
  60704. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  60705. * * 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
  60706. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  60707. * @param name defines the name of the mesh
  60708. * @param options defines the options used to create the mesh
  60709. * @param scene defines the hosting scene
  60710. * @returns the cylinder mesh
  60711. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#cylinder-or-cone
  60712. */
  60713. MeshBuilder.CreateCylinder = function (name, options, scene) {
  60714. var cylinder = new BABYLON.Mesh(name, scene);
  60715. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  60716. cylinder._originalBuilderSideOrientation = options.sideOrientation;
  60717. var vertexData = BABYLON.VertexData.CreateCylinder(options);
  60718. vertexData.applyToMesh(cylinder, options.updatable);
  60719. return cylinder;
  60720. };
  60721. /**
  60722. * Creates a torus mesh
  60723. * * The parameter `diameter` sets the diameter size (float) of the torus (default 1)
  60724. * * The parameter `thickness` sets the diameter size of the tube of the torus (float, default 0.5)
  60725. * * The parameter `tessellation` sets the number of torus sides (postive integer, default 16)
  60726. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  60727. * * 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
  60728. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  60729. * @param name defines the name of the mesh
  60730. * @param options defines the options used to create the mesh
  60731. * @param scene defines the hosting scene
  60732. * @returns the torus mesh
  60733. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#torus
  60734. */
  60735. MeshBuilder.CreateTorus = function (name, options, scene) {
  60736. var torus = new BABYLON.Mesh(name, scene);
  60737. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  60738. torus._originalBuilderSideOrientation = options.sideOrientation;
  60739. var vertexData = BABYLON.VertexData.CreateTorus(options);
  60740. vertexData.applyToMesh(torus, options.updatable);
  60741. return torus;
  60742. };
  60743. /**
  60744. * Creates a torus knot mesh
  60745. * * The parameter `radius` sets the global radius size (float) of the torus knot (default 2)
  60746. * * The parameter `radialSegments` sets the number of sides on each tube segments (positive integer, default 32)
  60747. * * The parameter `tubularSegments` sets the number of tubes to decompose the knot into (positive integer, default 32)
  60748. * * The parameters `p` and `q` are the number of windings on each axis (positive integers, default 2 and 3)
  60749. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  60750. * * If you create a double-sided mesh, you can choose what parts of the texture image to crop and stick respectively on the front and the back sides with the parameters `frontUVs` and `backUVs` (Vector4). Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  60751. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  60752. * @param name defines the name of the mesh
  60753. * @param options defines the options used to create the mesh
  60754. * @param scene defines the hosting scene
  60755. * @returns the torus knot mesh
  60756. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#torus-knot
  60757. */
  60758. MeshBuilder.CreateTorusKnot = function (name, options, scene) {
  60759. var torusKnot = new BABYLON.Mesh(name, scene);
  60760. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  60761. torusKnot._originalBuilderSideOrientation = options.sideOrientation;
  60762. var vertexData = BABYLON.VertexData.CreateTorusKnot(options);
  60763. vertexData.applyToMesh(torusKnot, options.updatable);
  60764. return torusKnot;
  60765. };
  60766. /**
  60767. * Creates a line system mesh. A line system is a pool of many lines gathered in a single mesh
  60768. * * 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
  60769. * * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineSystem to this static function
  60770. * * The parameter `lines` is an array of lines, each line being an array of successive Vector3
  60771. * * The optional parameter `instance` is an instance of an existing LineSystem object to be updated with the passed `lines` parameter
  60772. * * The optional parameter `colors` is an array of line colors, each line colors being an array of successive Color4, one per line point
  60773. * * The optional parameter `useVertexAlpha` is to be set to `false` (default `true`) when you don't need the alpha blending (faster)
  60774. * * 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
  60775. * * When updating an instance, remember that only line point positions can change, not the number of points, neither the number of lines
  60776. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  60777. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#linesystem
  60778. * @param name defines the name of the new line system
  60779. * @param options defines the options used to create the line system
  60780. * @param scene defines the hosting scene
  60781. * @returns a new line system mesh
  60782. */
  60783. MeshBuilder.CreateLineSystem = function (name, options, scene) {
  60784. var instance = options.instance;
  60785. var lines = options.lines;
  60786. var colors = options.colors;
  60787. if (instance) { // lines update
  60788. var positions = instance.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  60789. var vertexColor;
  60790. var lineColors;
  60791. if (colors) {
  60792. vertexColor = instance.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  60793. }
  60794. var i = 0;
  60795. var c = 0;
  60796. for (var l = 0; l < lines.length; l++) {
  60797. var points = lines[l];
  60798. for (var p = 0; p < points.length; p++) {
  60799. positions[i] = points[p].x;
  60800. positions[i + 1] = points[p].y;
  60801. positions[i + 2] = points[p].z;
  60802. if (colors && vertexColor) {
  60803. lineColors = colors[l];
  60804. vertexColor[c] = lineColors[p].r;
  60805. vertexColor[c + 1] = lineColors[p].g;
  60806. vertexColor[c + 2] = lineColors[p].b;
  60807. vertexColor[c + 3] = lineColors[p].a;
  60808. c += 4;
  60809. }
  60810. i += 3;
  60811. }
  60812. }
  60813. instance.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions, false, false);
  60814. if (colors && vertexColor) {
  60815. instance.updateVerticesData(BABYLON.VertexBuffer.ColorKind, vertexColor, false, false);
  60816. }
  60817. return instance;
  60818. }
  60819. // line system creation
  60820. var useVertexColor = (colors) ? true : false;
  60821. var lineSystem = new BABYLON.LinesMesh(name, scene, null, undefined, undefined, useVertexColor, options.useVertexAlpha);
  60822. var vertexData = BABYLON.VertexData.CreateLineSystem(options);
  60823. vertexData.applyToMesh(lineSystem, options.updatable);
  60824. return lineSystem;
  60825. };
  60826. /**
  60827. * Creates a line mesh
  60828. * 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
  60829. * * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function
  60830. * * The parameter `points` is an array successive Vector3
  60831. * * 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
  60832. * * The optional parameter `colors` is an array of successive Color4, one per line point
  60833. * * The optional parameter `useVertexAlpha` is to be set to `false` (default `true`) when you don't need alpha blending (faster)
  60834. * * When updating an instance, remember that only point positions can change, not the number of points
  60835. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  60836. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#lines
  60837. * @param name defines the name of the new line system
  60838. * @param options defines the options used to create the line system
  60839. * @param scene defines the hosting scene
  60840. * @returns a new line mesh
  60841. */
  60842. MeshBuilder.CreateLines = function (name, options, scene) {
  60843. if (scene === void 0) { scene = null; }
  60844. var colors = (options.colors) ? [options.colors] : null;
  60845. var lines = MeshBuilder.CreateLineSystem(name, { lines: [options.points], updatable: options.updatable, instance: options.instance, colors: colors, useVertexAlpha: options.useVertexAlpha }, scene);
  60846. return lines;
  60847. };
  60848. /**
  60849. * Creates a dashed line mesh
  60850. * * 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
  60851. * * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function
  60852. * * The parameter `points` is an array successive Vector3
  60853. * * The parameter `dashNb` is the intended total number of dashes (positive integer, default 200)
  60854. * * The parameter `dashSize` is the size of the dashes relatively the dash number (positive float, default 3)
  60855. * * The parameter `gapSize` is the size of the gap between two successive dashes relatively the dash number (positive float, default 1)
  60856. * * 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
  60857. * * When updating an instance, remember that only point positions can change, not the number of points
  60858. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  60859. * @param name defines the name of the mesh
  60860. * @param options defines the options used to create the mesh
  60861. * @param scene defines the hosting scene
  60862. * @returns the dashed line mesh
  60863. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#dashed-lines
  60864. */
  60865. MeshBuilder.CreateDashedLines = function (name, options, scene) {
  60866. if (scene === void 0) { scene = null; }
  60867. var points = options.points;
  60868. var instance = options.instance;
  60869. var gapSize = options.gapSize || 1;
  60870. var dashSize = options.dashSize || 3;
  60871. if (instance) { // dashed lines update
  60872. var positionFunction = function (positions) {
  60873. var curvect = BABYLON.Vector3.Zero();
  60874. var nbSeg = positions.length / 6;
  60875. var lg = 0;
  60876. var nb = 0;
  60877. var shft = 0;
  60878. var dashshft = 0;
  60879. var curshft = 0;
  60880. var p = 0;
  60881. var i = 0;
  60882. var j = 0;
  60883. for (i = 0; i < points.length - 1; i++) {
  60884. points[i + 1].subtractToRef(points[i], curvect);
  60885. lg += curvect.length();
  60886. }
  60887. shft = lg / nbSeg;
  60888. dashshft = instance.dashSize * shft / (instance.dashSize + instance.gapSize);
  60889. for (i = 0; i < points.length - 1; i++) {
  60890. points[i + 1].subtractToRef(points[i], curvect);
  60891. nb = Math.floor(curvect.length() / shft);
  60892. curvect.normalize();
  60893. j = 0;
  60894. while (j < nb && p < positions.length) {
  60895. curshft = shft * j;
  60896. positions[p] = points[i].x + curshft * curvect.x;
  60897. positions[p + 1] = points[i].y + curshft * curvect.y;
  60898. positions[p + 2] = points[i].z + curshft * curvect.z;
  60899. positions[p + 3] = points[i].x + (curshft + dashshft) * curvect.x;
  60900. positions[p + 4] = points[i].y + (curshft + dashshft) * curvect.y;
  60901. positions[p + 5] = points[i].z + (curshft + dashshft) * curvect.z;
  60902. p += 6;
  60903. j++;
  60904. }
  60905. }
  60906. while (p < positions.length) {
  60907. positions[p] = points[i].x;
  60908. positions[p + 1] = points[i].y;
  60909. positions[p + 2] = points[i].z;
  60910. p += 3;
  60911. }
  60912. };
  60913. instance.updateMeshPositions(positionFunction, false);
  60914. return instance;
  60915. }
  60916. // dashed lines creation
  60917. var dashedLines = new BABYLON.LinesMesh(name, scene);
  60918. var vertexData = BABYLON.VertexData.CreateDashedLines(options);
  60919. vertexData.applyToMesh(dashedLines, options.updatable);
  60920. dashedLines.dashSize = dashSize;
  60921. dashedLines.gapSize = gapSize;
  60922. return dashedLines;
  60923. };
  60924. /**
  60925. * 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.
  60926. * * 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.
  60927. * * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along.
  60928. * * 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.
  60929. * * The parameter `scale` (float, default 1) is the value to scale the shape.
  60930. * * 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
  60931. * * 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
  60932. * * Remember you can only change the shape or path point positions, not their number when updating an extruded shape.
  60933. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  60934. * * If you create a double-sided mesh, you can choose what parts of the texture image to crop and stick respectively on the front and the back sides with the parameters `frontUVs` and `backUVs` (Vector4). Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  60935. * * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture.
  60936. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  60937. * @param name defines the name of the mesh
  60938. * @param options defines the options used to create the mesh
  60939. * @param scene defines the hosting scene
  60940. * @returns the extruded shape mesh
  60941. * @see http://doc.babylonjs.com/tutorials/Parametric_Shapes
  60942. * @see http://doc.babylonjs.com/tutorials/Parametric_Shapes#extrusion
  60943. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#extruded-shapes
  60944. */
  60945. MeshBuilder.ExtrudeShape = function (name, options, scene) {
  60946. if (scene === void 0) { scene = null; }
  60947. var path = options.path;
  60948. var shape = options.shape;
  60949. var scale = options.scale || 1;
  60950. var rotation = options.rotation || 0;
  60951. var cap = (options.cap === 0) ? 0 : options.cap || BABYLON.Mesh.NO_CAP;
  60952. var updatable = options.updatable;
  60953. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  60954. var instance = options.instance || null;
  60955. var invertUV = options.invertUV || false;
  60956. 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);
  60957. };
  60958. /**
  60959. * Creates an custom extruded shape mesh.
  60960. * The custom extrusion is a parametric shape. It has no predefined shape. Its final shape will depend on the input parameters.
  60961. * * 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.
  60962. * * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along.
  60963. * * 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
  60964. * * It must returns a float value that will be the rotation in radians applied to the shape on each path point.
  60965. * * 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
  60966. * * It must returns a float value that will be the scale value applied to the shape on each path point
  60967. * * The parameter `ribbonClosePath` (boolean, default false) forces the extrusion underlying ribbon to close all the paths in its `pathArray`
  60968. * * The parameter `ribbonCloseArray` (boolean, default false) forces the extrusion underlying ribbon to close its `pathArray`
  60969. * * 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
  60970. * * 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
  60971. * * Remember you can only change the shape or path point positions, not their number when updating an extruded shape
  60972. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  60973. * * 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
  60974. * * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture
  60975. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  60976. * @param name defines the name of the mesh
  60977. * @param options defines the options used to create the mesh
  60978. * @param scene defines the hosting scene
  60979. * @returns the custom extruded shape mesh
  60980. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#custom-extruded-shapes
  60981. * @see http://doc.babylonjs.com/tutorials/Parametric_Shapes
  60982. * @see http://doc.babylonjs.com/tutorials/Parametric_Shapes#extrusion
  60983. */
  60984. MeshBuilder.ExtrudeShapeCustom = function (name, options, scene) {
  60985. var path = options.path;
  60986. var shape = options.shape;
  60987. var scaleFunction = options.scaleFunction || (function () { return 1; });
  60988. var rotationFunction = options.rotationFunction || (function () { return 0; });
  60989. var ribbonCloseArray = options.ribbonCloseArray || false;
  60990. var ribbonClosePath = options.ribbonClosePath || false;
  60991. var cap = (options.cap === 0) ? 0 : options.cap || BABYLON.Mesh.NO_CAP;
  60992. var updatable = options.updatable;
  60993. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  60994. var instance = options.instance;
  60995. var invertUV = options.invertUV || false;
  60996. 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);
  60997. };
  60998. /**
  60999. * Creates lathe mesh.
  61000. * The lathe is a shape with a symetry axis : a 2D model shape is rotated around this axis to design the lathe
  61001. * * 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
  61002. * * The parameter `radius` (positive float, default 1) is the radius value of the lathe
  61003. * * The parameter `tessellation` (positive integer, default 64) is the side number of the lathe
  61004. * * 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
  61005. * * The parameter `closed` (boolean, default true) opens/closes the lathe circumference. This should be set to false when used with the parameter "arc"
  61006. * * 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
  61007. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  61008. * * 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
  61009. * * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture
  61010. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  61011. * @param name defines the name of the mesh
  61012. * @param options defines the options used to create the mesh
  61013. * @param scene defines the hosting scene
  61014. * @returns the lathe mesh
  61015. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#lathe
  61016. */
  61017. MeshBuilder.CreateLathe = function (name, options, scene) {
  61018. var arc = options.arc ? ((options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc) : 1.0;
  61019. var closed = (options.closed === undefined) ? true : options.closed;
  61020. var shape = options.shape;
  61021. var radius = options.radius || 1;
  61022. var tessellation = options.tessellation || 64;
  61023. var updatable = options.updatable;
  61024. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  61025. var cap = options.cap || BABYLON.Mesh.NO_CAP;
  61026. var pi2 = Math.PI * 2;
  61027. var paths = new Array();
  61028. var invertUV = options.invertUV || false;
  61029. var i = 0;
  61030. var p = 0;
  61031. var step = pi2 / tessellation * arc;
  61032. var rotated;
  61033. var path = new Array();
  61034. ;
  61035. for (i = 0; i <= tessellation; i++) {
  61036. var path = [];
  61037. if (cap == BABYLON.Mesh.CAP_START || cap == BABYLON.Mesh.CAP_ALL) {
  61038. path.push(new BABYLON.Vector3(0, shape[0].y, 0));
  61039. path.push(new BABYLON.Vector3(Math.cos(i * step) * shape[0].x * radius, shape[0].y, Math.sin(i * step) * shape[0].x * radius));
  61040. }
  61041. for (p = 0; p < shape.length; p++) {
  61042. rotated = new BABYLON.Vector3(Math.cos(i * step) * shape[p].x * radius, shape[p].y, Math.sin(i * step) * shape[p].x * radius);
  61043. path.push(rotated);
  61044. }
  61045. if (cap == BABYLON.Mesh.CAP_END || cap == BABYLON.Mesh.CAP_ALL) {
  61046. 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));
  61047. path.push(new BABYLON.Vector3(0, shape[shape.length - 1].y, 0));
  61048. }
  61049. paths.push(path);
  61050. }
  61051. // lathe ribbon
  61052. var lathe = MeshBuilder.CreateRibbon(name, { pathArray: paths, closeArray: closed, sideOrientation: sideOrientation, updatable: updatable, invertUV: invertUV, frontUVs: options.frontUVs, backUVs: options.backUVs }, scene);
  61053. return lathe;
  61054. };
  61055. /**
  61056. * Creates a plane mesh
  61057. * * The parameter `size` sets the size (float) of both sides of the plane at once (default 1)
  61058. * * You can set some different plane dimensions by using the parameters `width` and `height` (both by default have the same value than `size`)
  61059. * * The parameter `sourcePlane` is a Plane instance. It builds a mesh plane from a Math plane
  61060. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  61061. * * 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
  61062. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  61063. * @param name defines the name of the mesh
  61064. * @param options defines the options used to create the mesh
  61065. * @param scene defines the hosting scene
  61066. * @returns the plane mesh
  61067. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#plane
  61068. */
  61069. MeshBuilder.CreatePlane = function (name, options, scene) {
  61070. var plane = new BABYLON.Mesh(name, scene);
  61071. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  61072. plane._originalBuilderSideOrientation = options.sideOrientation;
  61073. var vertexData = BABYLON.VertexData.CreatePlane(options);
  61074. vertexData.applyToMesh(plane, options.updatable);
  61075. if (options.sourcePlane) {
  61076. plane.translate(options.sourcePlane.normal, options.sourcePlane.d);
  61077. var product = Math.acos(BABYLON.Vector3.Dot(options.sourcePlane.normal, BABYLON.Axis.Z));
  61078. var vectorProduct = BABYLON.Vector3.Cross(BABYLON.Axis.Z, options.sourcePlane.normal);
  61079. plane.rotate(vectorProduct, product);
  61080. }
  61081. return plane;
  61082. };
  61083. /**
  61084. * Creates a ground mesh
  61085. * * The parameters `width` and `height` (floats, default 1) set the width and height sizes of the ground
  61086. * * The parameter `subdivisions` (positive integer) sets the number of subdivisions per side
  61087. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  61088. * @param name defines the name of the mesh
  61089. * @param options defines the options used to create the mesh
  61090. * @param scene defines the hosting scene
  61091. * @returns the ground mesh
  61092. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#plane
  61093. */
  61094. MeshBuilder.CreateGround = function (name, options, scene) {
  61095. var ground = new BABYLON.GroundMesh(name, scene);
  61096. ground._setReady(false);
  61097. ground._subdivisionsX = options.subdivisionsX || options.subdivisions || 1;
  61098. ground._subdivisionsY = options.subdivisionsY || options.subdivisions || 1;
  61099. ground._width = options.width || 1;
  61100. ground._height = options.height || 1;
  61101. ground._maxX = ground._width / 2;
  61102. ground._maxZ = ground._height / 2;
  61103. ground._minX = -ground._maxX;
  61104. ground._minZ = -ground._maxZ;
  61105. var vertexData = BABYLON.VertexData.CreateGround(options);
  61106. vertexData.applyToMesh(ground, options.updatable);
  61107. ground._setReady(true);
  61108. return ground;
  61109. };
  61110. /**
  61111. * Creates a tiled ground mesh
  61112. * * The parameters `xmin` and `xmax` (floats, default -1 and 1) set the ground minimum and maximum X coordinates
  61113. * * The parameters `zmin` and `zmax` (floats, default -1 and 1) set the ground minimum and maximum Z coordinates
  61114. * * 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
  61115. * * 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
  61116. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  61117. * @param name defines the name of the mesh
  61118. * @param options defines the options used to create the mesh
  61119. * @param scene defines the hosting scene
  61120. * @returns the tiled ground mesh
  61121. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#tiled-ground
  61122. */
  61123. MeshBuilder.CreateTiledGround = function (name, options, scene) {
  61124. var tiledGround = new BABYLON.Mesh(name, scene);
  61125. var vertexData = BABYLON.VertexData.CreateTiledGround(options);
  61126. vertexData.applyToMesh(tiledGround, options.updatable);
  61127. return tiledGround;
  61128. };
  61129. /**
  61130. * Creates a ground mesh from a height map
  61131. * * The parameter `url` sets the URL of the height map image resource.
  61132. * * The parameters `width` and `height` (positive floats, default 10) set the ground width and height sizes.
  61133. * * The parameter `subdivisions` (positive integer, default 1) sets the number of subdivision per side.
  61134. * * The parameter `minHeight` (float, default 0) is the minimum altitude on the ground.
  61135. * * The parameter `maxHeight` (float, default 1) is the maximum altitude on the ground.
  61136. * * 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.
  61137. * * 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).
  61138. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  61139. * @param name defines the name of the mesh
  61140. * @param url defines the url to the height map
  61141. * @param options defines the options used to create the mesh
  61142. * @param scene defines the hosting scene
  61143. * @returns the ground mesh
  61144. * @see http://doc.babylonjs.com/tutorials/14._Height_Map
  61145. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#ground-from-a-height-map
  61146. */
  61147. MeshBuilder.CreateGroundFromHeightMap = function (name, url, options, scene) {
  61148. var width = options.width || 10.0;
  61149. var height = options.height || 10.0;
  61150. var subdivisions = options.subdivisions || 1 | 0;
  61151. var minHeight = options.minHeight || 0.0;
  61152. var maxHeight = options.maxHeight || 1.0;
  61153. var filter = options.colorFilter || new BABYLON.Color3(0.3, 0.59, 0.11);
  61154. var updatable = options.updatable;
  61155. var onReady = options.onReady;
  61156. var ground = new BABYLON.GroundMesh(name, scene);
  61157. ground._subdivisionsX = subdivisions;
  61158. ground._subdivisionsY = subdivisions;
  61159. ground._width = width;
  61160. ground._height = height;
  61161. ground._maxX = ground._width / 2.0;
  61162. ground._maxZ = ground._height / 2.0;
  61163. ground._minX = -ground._maxX;
  61164. ground._minZ = -ground._maxZ;
  61165. ground._setReady(false);
  61166. var onload = function (img) {
  61167. // Getting height map data
  61168. var canvas = document.createElement("canvas");
  61169. var context = canvas.getContext("2d");
  61170. if (!context) {
  61171. throw new Error("Unable to get 2d context for CreateGroundFromHeightMap");
  61172. }
  61173. if (scene.isDisposed) {
  61174. return;
  61175. }
  61176. var bufferWidth = img.width;
  61177. var bufferHeight = img.height;
  61178. canvas.width = bufferWidth;
  61179. canvas.height = bufferHeight;
  61180. context.drawImage(img, 0, 0);
  61181. // Create VertexData from map data
  61182. // Cast is due to wrong definition in lib.d.ts from ts 1.3 - https://github.com/Microsoft/TypeScript/issues/949
  61183. var buffer = context.getImageData(0, 0, bufferWidth, bufferHeight).data;
  61184. var vertexData = BABYLON.VertexData.CreateGroundFromHeightMap({
  61185. width: width, height: height,
  61186. subdivisions: subdivisions,
  61187. minHeight: minHeight, maxHeight: maxHeight, colorFilter: filter,
  61188. buffer: buffer, bufferWidth: bufferWidth, bufferHeight: bufferHeight
  61189. });
  61190. vertexData.applyToMesh(ground, updatable);
  61191. //execute ready callback, if set
  61192. if (onReady) {
  61193. onReady(ground);
  61194. }
  61195. ground._setReady(true);
  61196. };
  61197. BABYLON.Tools.LoadImage(url, onload, function () { }, scene.database);
  61198. return ground;
  61199. };
  61200. /**
  61201. * Creates a polygon mesh
  61202. * The polygon's shape will depend on the input parameters and is constructed parallel to a ground mesh
  61203. * * 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
  61204. * * You can set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  61205. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  61206. * * 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)
  61207. * * Remember you can only change the shape positions, not their number when updating a polygon
  61208. * @param name defines the name of the mesh
  61209. * @param options defines the options used to create the mesh
  61210. * @param scene defines the hosting scene
  61211. * @returns the polygon mesh
  61212. */
  61213. MeshBuilder.CreatePolygon = function (name, options, scene) {
  61214. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  61215. var shape = options.shape;
  61216. var holes = options.holes || [];
  61217. var depth = options.depth || 0;
  61218. var contours = [];
  61219. var hole = [];
  61220. for (var i = 0; i < shape.length; i++) {
  61221. contours[i] = new BABYLON.Vector2(shape[i].x, shape[i].z);
  61222. }
  61223. var epsilon = 0.00000001;
  61224. if (contours[0].equalsWithEpsilon(contours[contours.length - 1], epsilon)) {
  61225. contours.pop();
  61226. }
  61227. var polygonTriangulation = new BABYLON.PolygonMeshBuilder(name, contours, scene);
  61228. for (var hNb = 0; hNb < holes.length; hNb++) {
  61229. hole = [];
  61230. for (var hPoint = 0; hPoint < holes[hNb].length; hPoint++) {
  61231. hole.push(new BABYLON.Vector2(holes[hNb][hPoint].x, holes[hNb][hPoint].z));
  61232. }
  61233. polygonTriangulation.addHole(hole);
  61234. }
  61235. var polygon = polygonTriangulation.build(options.updatable, depth);
  61236. polygon._originalBuilderSideOrientation = options.sideOrientation;
  61237. var vertexData = BABYLON.VertexData.CreatePolygon(polygon, options.sideOrientation, options.faceUV, options.faceColors, options.frontUVs, options.backUVs);
  61238. vertexData.applyToMesh(polygon, options.updatable);
  61239. return polygon;
  61240. };
  61241. ;
  61242. /**
  61243. * Creates an extruded polygon mesh, with depth in the Y direction.
  61244. * * 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)
  61245. * @see http://doc.babylonjs.com/tutorials/CreateBox_Per_Face_Textures_And_Colors
  61246. * @param name defines the name of the mesh
  61247. * @param options defines the options used to create the mesh
  61248. * @param scene defines the hosting scene
  61249. * @returns the polygon mesh
  61250. */
  61251. MeshBuilder.ExtrudePolygon = function (name, options, scene) {
  61252. return MeshBuilder.CreatePolygon(name, options, scene);
  61253. };
  61254. ;
  61255. /**
  61256. * Creates a tube mesh.
  61257. * The tube is a parametric shape. It has no predefined shape. Its final shape will depend on the input parameters
  61258. * * The parameter `path` is a required array of successive Vector3. It is the curve used as the axis of the tube
  61259. * * The parameter `radius` (positive float, default 1) sets the tube radius size
  61260. * * The parameter `tessellation` (positive float, default 64) is the number of sides on the tubular surface
  61261. * * The parameter `radiusFunction` (javascript function, default null) is a vanilla javascript function. If it is not null, it overwrittes the parameter `radius`
  61262. * * 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)
  61263. * * The parameter `arc` (positive float, maximum 1, default 1) is the ratio to apply to the tube circumference : 2 x PI x arc
  61264. * * 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
  61265. * * 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
  61266. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  61267. * * 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
  61268. * * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture
  61269. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  61270. * @param name defines the name of the mesh
  61271. * @param options defines the options used to create the mesh
  61272. * @param scene defines the hosting scene
  61273. * @returns the tube mesh
  61274. * @see http://doc.babylonjs.com/tutorials/Parametric_Shapes
  61275. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#tube
  61276. */
  61277. MeshBuilder.CreateTube = function (name, options, scene) {
  61278. var path = options.path;
  61279. var instance = options.instance;
  61280. var radius = 1.0;
  61281. if (instance) {
  61282. radius = instance.radius;
  61283. }
  61284. if (options.radius !== undefined) {
  61285. radius = options.radius;
  61286. }
  61287. ;
  61288. var tessellation = options.tessellation || 64 | 0;
  61289. var radiusFunction = options.radiusFunction || null;
  61290. var cap = options.cap || BABYLON.Mesh.NO_CAP;
  61291. var invertUV = options.invertUV || false;
  61292. var updatable = options.updatable;
  61293. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  61294. options.arc = options.arc && (options.arc <= 0.0 || options.arc > 1.0) ? 1.0 : options.arc || 1.0;
  61295. // tube geometry
  61296. var tubePathArray = function (path, path3D, circlePaths, radius, tessellation, radiusFunction, cap, arc) {
  61297. var tangents = path3D.getTangents();
  61298. var normals = path3D.getNormals();
  61299. var distances = path3D.getDistances();
  61300. var pi2 = Math.PI * 2;
  61301. var step = pi2 / tessellation * arc;
  61302. var returnRadius = function () { return radius; };
  61303. var radiusFunctionFinal = radiusFunction || returnRadius;
  61304. var circlePath;
  61305. var rad;
  61306. var normal;
  61307. var rotated;
  61308. var rotationMatrix = BABYLON.Tmp.Matrix[0];
  61309. var index = (cap === BABYLON.Mesh._NO_CAP || cap === BABYLON.Mesh.CAP_END) ? 0 : 2;
  61310. for (var i = 0; i < path.length; i++) {
  61311. rad = radiusFunctionFinal(i, distances[i]); // current radius
  61312. circlePath = Array(); // current circle array
  61313. normal = normals[i]; // current normal
  61314. for (var t = 0; t < tessellation; t++) {
  61315. BABYLON.Matrix.RotationAxisToRef(tangents[i], step * t, rotationMatrix);
  61316. rotated = circlePath[t] ? circlePath[t] : BABYLON.Vector3.Zero();
  61317. BABYLON.Vector3.TransformCoordinatesToRef(normal, rotationMatrix, rotated);
  61318. rotated.scaleInPlace(rad).addInPlace(path[i]);
  61319. circlePath[t] = rotated;
  61320. }
  61321. circlePaths[index] = circlePath;
  61322. index++;
  61323. }
  61324. // cap
  61325. var capPath = function (nbPoints, pathIndex) {
  61326. var pointCap = Array();
  61327. for (var i = 0; i < nbPoints; i++) {
  61328. pointCap.push(path[pathIndex]);
  61329. }
  61330. return pointCap;
  61331. };
  61332. switch (cap) {
  61333. case BABYLON.Mesh.NO_CAP:
  61334. break;
  61335. case BABYLON.Mesh.CAP_START:
  61336. circlePaths[0] = capPath(tessellation, 0);
  61337. circlePaths[1] = circlePaths[2].slice(0);
  61338. break;
  61339. case BABYLON.Mesh.CAP_END:
  61340. circlePaths[index] = circlePaths[index - 1].slice(0);
  61341. circlePaths[index + 1] = capPath(tessellation, path.length - 1);
  61342. break;
  61343. case BABYLON.Mesh.CAP_ALL:
  61344. circlePaths[0] = capPath(tessellation, 0);
  61345. circlePaths[1] = circlePaths[2].slice(0);
  61346. circlePaths[index] = circlePaths[index - 1].slice(0);
  61347. circlePaths[index + 1] = capPath(tessellation, path.length - 1);
  61348. break;
  61349. default:
  61350. break;
  61351. }
  61352. return circlePaths;
  61353. };
  61354. var path3D;
  61355. var pathArray;
  61356. if (instance) { // tube update
  61357. var arc = options.arc || instance.arc;
  61358. path3D = (instance.path3D).update(path);
  61359. pathArray = tubePathArray(path, path3D, instance.pathArray, radius, instance.tessellation, radiusFunction, instance.cap, arc);
  61360. instance = MeshBuilder.CreateRibbon("", { pathArray: pathArray, instance: instance });
  61361. instance.path3D = path3D;
  61362. instance.pathArray = pathArray;
  61363. instance.arc = arc;
  61364. instance.radius = radius;
  61365. return instance;
  61366. }
  61367. // tube creation
  61368. path3D = new BABYLON.Path3D(path);
  61369. var newPathArray = new Array();
  61370. cap = (cap < 0 || cap > 3) ? 0 : cap;
  61371. pathArray = tubePathArray(path, path3D, newPathArray, radius, tessellation, radiusFunction, cap, options.arc);
  61372. var tube = MeshBuilder.CreateRibbon(name, { pathArray: pathArray, closePath: true, closeArray: false, updatable: updatable, sideOrientation: sideOrientation, invertUV: invertUV, frontUVs: options.frontUVs, backUVs: options.backUVs }, scene);
  61373. tube.pathArray = pathArray;
  61374. tube.path3D = path3D;
  61375. tube.tessellation = tessellation;
  61376. tube.cap = cap;
  61377. tube.arc = options.arc;
  61378. tube.radius = radius;
  61379. return tube;
  61380. };
  61381. /**
  61382. * Creates a polyhedron mesh
  61383. * * 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
  61384. * * The parameter `size` (positive float, default 1) sets the polygon size
  61385. * * You can overwrite the `size` on each dimension bu using the parameters `sizeX`, `sizeY` or `sizeZ` (positive floats, default to `size` value)
  61386. * * 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`
  61387. * * 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
  61388. * * 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)`)
  61389. * * 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
  61390. * * 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
  61391. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  61392. * * 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
  61393. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  61394. * @param name defines the name of the mesh
  61395. * @param options defines the options used to create the mesh
  61396. * @param scene defines the hosting scene
  61397. * @returns the polyhedron mesh
  61398. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#polyhedron
  61399. */
  61400. MeshBuilder.CreatePolyhedron = function (name, options, scene) {
  61401. var polyhedron = new BABYLON.Mesh(name, scene);
  61402. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  61403. polyhedron._originalBuilderSideOrientation = options.sideOrientation;
  61404. var vertexData = BABYLON.VertexData.CreatePolyhedron(options);
  61405. vertexData.applyToMesh(polyhedron, options.updatable);
  61406. return polyhedron;
  61407. };
  61408. /**
  61409. * Creates a decal mesh.
  61410. * 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
  61411. * * The parameter `position` (Vector3, default `(0, 0, 0)`) sets the position of the decal in World coordinates
  61412. * * The parameter `normal` (Vector3, default `Vector3.Up`) sets the normal of the mesh where the decal is applied onto in World coordinates
  61413. * * The parameter `size` (Vector3, default `(1, 1, 1)`) sets the decal scaling
  61414. * * The parameter `angle` (float in radian, default 0) sets the angle to rotate the decal
  61415. * @param name defines the name of the mesh
  61416. * @param sourceMesh defines the mesh where the decal must be applied
  61417. * @param options defines the options used to create the mesh
  61418. * @param scene defines the hosting scene
  61419. * @returns the decal mesh
  61420. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#decals
  61421. */
  61422. MeshBuilder.CreateDecal = function (name, sourceMesh, options) {
  61423. var indices = sourceMesh.getIndices();
  61424. var positions = sourceMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  61425. var normals = sourceMesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  61426. var position = options.position || BABYLON.Vector3.Zero();
  61427. var normal = options.normal || BABYLON.Vector3.Up();
  61428. var size = options.size || BABYLON.Vector3.One();
  61429. var angle = options.angle || 0;
  61430. // Getting correct rotation
  61431. if (!normal) {
  61432. var target = new BABYLON.Vector3(0, 0, 1);
  61433. var camera = sourceMesh.getScene().activeCamera;
  61434. var cameraWorldTarget = BABYLON.Vector3.TransformCoordinates(target, camera.getWorldMatrix());
  61435. normal = camera.globalPosition.subtract(cameraWorldTarget);
  61436. }
  61437. var yaw = -Math.atan2(normal.z, normal.x) - Math.PI / 2;
  61438. var len = Math.sqrt(normal.x * normal.x + normal.z * normal.z);
  61439. var pitch = Math.atan2(normal.y, len);
  61440. // Matrix
  61441. var decalWorldMatrix = BABYLON.Matrix.RotationYawPitchRoll(yaw, pitch, angle).multiply(BABYLON.Matrix.Translation(position.x, position.y, position.z));
  61442. var inverseDecalWorldMatrix = BABYLON.Matrix.Invert(decalWorldMatrix);
  61443. var meshWorldMatrix = sourceMesh.getWorldMatrix();
  61444. var transformMatrix = meshWorldMatrix.multiply(inverseDecalWorldMatrix);
  61445. var vertexData = new BABYLON.VertexData();
  61446. vertexData.indices = [];
  61447. vertexData.positions = [];
  61448. vertexData.normals = [];
  61449. vertexData.uvs = [];
  61450. var currentVertexDataIndex = 0;
  61451. var extractDecalVector3 = function (indexId) {
  61452. var result = new BABYLON.PositionNormalVertex();
  61453. if (!indices || !positions || !normals) {
  61454. return result;
  61455. }
  61456. var vertexId = indices[indexId];
  61457. result.position = new BABYLON.Vector3(positions[vertexId * 3], positions[vertexId * 3 + 1], positions[vertexId * 3 + 2]);
  61458. // Send vector to decal local world
  61459. result.position = BABYLON.Vector3.TransformCoordinates(result.position, transformMatrix);
  61460. // Get normal
  61461. result.normal = new BABYLON.Vector3(normals[vertexId * 3], normals[vertexId * 3 + 1], normals[vertexId * 3 + 2]);
  61462. result.normal = BABYLON.Vector3.TransformNormal(result.normal, transformMatrix);
  61463. return result;
  61464. }; // Inspired by https://github.com/mrdoob/three.js/blob/eee231960882f6f3b6113405f524956145148146/examples/js/geometries/DecalGeometry.js
  61465. var clip = function (vertices, axis) {
  61466. if (vertices.length === 0) {
  61467. return vertices;
  61468. }
  61469. var clipSize = 0.5 * Math.abs(BABYLON.Vector3.Dot(size, axis));
  61470. var clipVertices = function (v0, v1) {
  61471. var clipFactor = BABYLON.Vector3.GetClipFactor(v0.position, v1.position, axis, clipSize);
  61472. return new BABYLON.PositionNormalVertex(BABYLON.Vector3.Lerp(v0.position, v1.position, clipFactor), BABYLON.Vector3.Lerp(v0.normal, v1.normal, clipFactor));
  61473. };
  61474. var result = new Array();
  61475. for (var index = 0; index < vertices.length; index += 3) {
  61476. var v1Out;
  61477. var v2Out;
  61478. var v3Out;
  61479. var total = 0;
  61480. var nV1 = null;
  61481. var nV2 = null;
  61482. var nV3 = null;
  61483. var nV4 = null;
  61484. var d1 = BABYLON.Vector3.Dot(vertices[index].position, axis) - clipSize;
  61485. var d2 = BABYLON.Vector3.Dot(vertices[index + 1].position, axis) - clipSize;
  61486. var d3 = BABYLON.Vector3.Dot(vertices[index + 2].position, axis) - clipSize;
  61487. v1Out = d1 > 0;
  61488. v2Out = d2 > 0;
  61489. v3Out = d3 > 0;
  61490. total = (v1Out ? 1 : 0) + (v2Out ? 1 : 0) + (v3Out ? 1 : 0);
  61491. switch (total) {
  61492. case 0:
  61493. result.push(vertices[index]);
  61494. result.push(vertices[index + 1]);
  61495. result.push(vertices[index + 2]);
  61496. break;
  61497. case 1:
  61498. if (v1Out) {
  61499. nV1 = vertices[index + 1];
  61500. nV2 = vertices[index + 2];
  61501. nV3 = clipVertices(vertices[index], nV1);
  61502. nV4 = clipVertices(vertices[index], nV2);
  61503. }
  61504. if (v2Out) {
  61505. nV1 = vertices[index];
  61506. nV2 = vertices[index + 2];
  61507. nV3 = clipVertices(vertices[index + 1], nV1);
  61508. nV4 = clipVertices(vertices[index + 1], nV2);
  61509. result.push(nV3);
  61510. result.push(nV2.clone());
  61511. result.push(nV1.clone());
  61512. result.push(nV2.clone());
  61513. result.push(nV3.clone());
  61514. result.push(nV4);
  61515. break;
  61516. }
  61517. if (v3Out) {
  61518. nV1 = vertices[index];
  61519. nV2 = vertices[index + 1];
  61520. nV3 = clipVertices(vertices[index + 2], nV1);
  61521. nV4 = clipVertices(vertices[index + 2], nV2);
  61522. }
  61523. if (nV1 && nV2 && nV3 && nV4) {
  61524. result.push(nV1.clone());
  61525. result.push(nV2.clone());
  61526. result.push(nV3);
  61527. result.push(nV4);
  61528. result.push(nV3.clone());
  61529. result.push(nV2.clone());
  61530. }
  61531. break;
  61532. case 2:
  61533. if (!v1Out) {
  61534. nV1 = vertices[index].clone();
  61535. nV2 = clipVertices(nV1, vertices[index + 1]);
  61536. nV3 = clipVertices(nV1, vertices[index + 2]);
  61537. result.push(nV1);
  61538. result.push(nV2);
  61539. result.push(nV3);
  61540. }
  61541. if (!v2Out) {
  61542. nV1 = vertices[index + 1].clone();
  61543. nV2 = clipVertices(nV1, vertices[index + 2]);
  61544. nV3 = clipVertices(nV1, vertices[index]);
  61545. result.push(nV1);
  61546. result.push(nV2);
  61547. result.push(nV3);
  61548. }
  61549. if (!v3Out) {
  61550. nV1 = vertices[index + 2].clone();
  61551. nV2 = clipVertices(nV1, vertices[index]);
  61552. nV3 = clipVertices(nV1, vertices[index + 1]);
  61553. result.push(nV1);
  61554. result.push(nV2);
  61555. result.push(nV3);
  61556. }
  61557. break;
  61558. case 3:
  61559. break;
  61560. }
  61561. }
  61562. return result;
  61563. };
  61564. for (var index = 0; index < indices.length; index += 3) {
  61565. var faceVertices = new Array();
  61566. faceVertices.push(extractDecalVector3(index));
  61567. faceVertices.push(extractDecalVector3(index + 1));
  61568. faceVertices.push(extractDecalVector3(index + 2));
  61569. // Clip
  61570. faceVertices = clip(faceVertices, new BABYLON.Vector3(1, 0, 0));
  61571. faceVertices = clip(faceVertices, new BABYLON.Vector3(-1, 0, 0));
  61572. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, 1, 0));
  61573. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, -1, 0));
  61574. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, 0, 1));
  61575. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, 0, -1));
  61576. if (faceVertices.length === 0) {
  61577. continue;
  61578. }
  61579. // Add UVs and get back to world
  61580. for (var vIndex = 0; vIndex < faceVertices.length; vIndex++) {
  61581. var vertex = faceVertices[vIndex];
  61582. //TODO check for Int32Array | Uint32Array | Uint16Array
  61583. vertexData.indices.push(currentVertexDataIndex);
  61584. vertex.position.toArray(vertexData.positions, currentVertexDataIndex * 3);
  61585. vertex.normal.toArray(vertexData.normals, currentVertexDataIndex * 3);
  61586. vertexData.uvs.push(0.5 + vertex.position.x / size.x);
  61587. vertexData.uvs.push(0.5 + vertex.position.y / size.y);
  61588. currentVertexDataIndex++;
  61589. }
  61590. }
  61591. // Return mesh
  61592. var decal = new BABYLON.Mesh(name, sourceMesh.getScene());
  61593. vertexData.applyToMesh(decal);
  61594. decal.position = position.clone();
  61595. decal.rotation = new BABYLON.Vector3(pitch, yaw, angle);
  61596. return decal;
  61597. };
  61598. // Privates
  61599. MeshBuilder._ExtrudeShapeGeneric = function (name, shape, curve, scale, rotation, scaleFunction, rotateFunction, rbCA, rbCP, cap, custom, scene, updtbl, side, instance, invertUV, frontUVs, backUVs) {
  61600. // extrusion geometry
  61601. var extrusionPathArray = function (shape, curve, path3D, shapePaths, scale, rotation, scaleFunction, rotateFunction, cap, custom) {
  61602. var tangents = path3D.getTangents();
  61603. var normals = path3D.getNormals();
  61604. var binormals = path3D.getBinormals();
  61605. var distances = path3D.getDistances();
  61606. var angle = 0;
  61607. var returnScale = function () { return scale !== null ? scale : 1; };
  61608. var returnRotation = function () { return rotation !== null ? rotation : 0; };
  61609. var rotate = custom && rotateFunction ? rotateFunction : returnRotation;
  61610. var scl = custom && scaleFunction ? scaleFunction : returnScale;
  61611. var index = (cap === BABYLON.Mesh.NO_CAP || cap === BABYLON.Mesh.CAP_END) ? 0 : 2;
  61612. var rotationMatrix = BABYLON.Tmp.Matrix[0];
  61613. for (var i = 0; i < curve.length; i++) {
  61614. var shapePath = new Array();
  61615. var angleStep = rotate(i, distances[i]);
  61616. var scaleRatio = scl(i, distances[i]);
  61617. for (var p = 0; p < shape.length; p++) {
  61618. BABYLON.Matrix.RotationAxisToRef(tangents[i], angle, rotationMatrix);
  61619. var planed = ((tangents[i].scale(shape[p].z)).add(normals[i].scale(shape[p].x)).add(binormals[i].scale(shape[p].y)));
  61620. var rotated = shapePath[p] ? shapePath[p] : BABYLON.Vector3.Zero();
  61621. BABYLON.Vector3.TransformCoordinatesToRef(planed, rotationMatrix, rotated);
  61622. rotated.scaleInPlace(scaleRatio).addInPlace(curve[i]);
  61623. shapePath[p] = rotated;
  61624. }
  61625. shapePaths[index] = shapePath;
  61626. angle += angleStep;
  61627. index++;
  61628. }
  61629. // cap
  61630. var capPath = function (shapePath) {
  61631. var pointCap = Array();
  61632. var barycenter = BABYLON.Vector3.Zero();
  61633. var i;
  61634. for (i = 0; i < shapePath.length; i++) {
  61635. barycenter.addInPlace(shapePath[i]);
  61636. }
  61637. barycenter.scaleInPlace(1.0 / shapePath.length);
  61638. for (i = 0; i < shapePath.length; i++) {
  61639. pointCap.push(barycenter);
  61640. }
  61641. return pointCap;
  61642. };
  61643. switch (cap) {
  61644. case BABYLON.Mesh.NO_CAP:
  61645. break;
  61646. case BABYLON.Mesh.CAP_START:
  61647. shapePaths[0] = capPath(shapePaths[2]);
  61648. shapePaths[1] = shapePaths[2];
  61649. break;
  61650. case BABYLON.Mesh.CAP_END:
  61651. shapePaths[index] = shapePaths[index - 1];
  61652. shapePaths[index + 1] = capPath(shapePaths[index - 1]);
  61653. break;
  61654. case BABYLON.Mesh.CAP_ALL:
  61655. shapePaths[0] = capPath(shapePaths[2]);
  61656. shapePaths[1] = shapePaths[2];
  61657. shapePaths[index] = shapePaths[index - 1];
  61658. shapePaths[index + 1] = capPath(shapePaths[index - 1]);
  61659. break;
  61660. default:
  61661. break;
  61662. }
  61663. return shapePaths;
  61664. };
  61665. var path3D;
  61666. var pathArray;
  61667. if (instance) { // instance update
  61668. path3D = (instance.path3D).update(curve);
  61669. pathArray = extrusionPathArray(shape, curve, instance.path3D, instance.pathArray, scale, rotation, scaleFunction, rotateFunction, instance.cap, custom);
  61670. instance = BABYLON.Mesh.CreateRibbon("", pathArray, false, false, 0, scene || undefined, false, 0, instance);
  61671. return instance;
  61672. }
  61673. // extruded shape creation
  61674. path3D = new BABYLON.Path3D(curve);
  61675. var newShapePaths = new Array();
  61676. cap = (cap < 0 || cap > 3) ? 0 : cap;
  61677. pathArray = extrusionPathArray(shape, curve, path3D, newShapePaths, scale, rotation, scaleFunction, rotateFunction, cap, custom);
  61678. var extrudedGeneric = MeshBuilder.CreateRibbon(name, { pathArray: pathArray, closeArray: rbCA, closePath: rbCP, updatable: updtbl, sideOrientation: side, invertUV: invertUV, frontUVs: frontUVs || undefined, backUVs: backUVs || undefined }, scene);
  61679. extrudedGeneric.pathArray = pathArray;
  61680. extrudedGeneric.path3D = path3D;
  61681. extrudedGeneric.cap = cap;
  61682. return extrudedGeneric;
  61683. };
  61684. return MeshBuilder;
  61685. }());
  61686. BABYLON.MeshBuilder = MeshBuilder;
  61687. })(BABYLON || (BABYLON = {}));
  61688. //# sourceMappingURL=babylon.meshBuilder.js.map
  61689. var BABYLON;
  61690. (function (BABYLON) {
  61691. /**
  61692. * Draco compression (https://google.github.io/draco/)
  61693. */
  61694. var DracoCompression = /** @class */ (function () {
  61695. /**
  61696. * Constructor
  61697. */
  61698. function DracoCompression() {
  61699. }
  61700. Object.defineProperty(DracoCompression, "DecoderAvailable", {
  61701. /**
  61702. * Returns true if the decoder is available.
  61703. */
  61704. get: function () {
  61705. if (typeof DracoDecoderModule !== "undefined") {
  61706. return true;
  61707. }
  61708. var decoder = DracoCompression.Configuration.decoder;
  61709. if (decoder) {
  61710. if (decoder.wasmUrl && decoder.wasmBinaryUrl && typeof WebAssembly === "object") {
  61711. return true;
  61712. }
  61713. if (decoder.fallbackUrl) {
  61714. return true;
  61715. }
  61716. }
  61717. return false;
  61718. },
  61719. enumerable: true,
  61720. configurable: true
  61721. });
  61722. /**
  61723. * Stop all async operations and release resources.
  61724. */
  61725. DracoCompression.prototype.dispose = function () {
  61726. };
  61727. /**
  61728. * Decode Draco compressed mesh data to vertex data.
  61729. * @param data The array buffer view for the Draco compression data
  61730. * @param attributes A map of attributes from vertex buffer kinds to Draco unique ids
  61731. * @returns A promise that resolves with the decoded vertex data
  61732. */
  61733. DracoCompression.prototype.decodeMeshAsync = function (data, attributes) {
  61734. return DracoCompression._GetDecoderModule().then(function (wrappedModule) {
  61735. var module = wrappedModule.module;
  61736. var vertexData = new BABYLON.VertexData();
  61737. var buffer = new module.DecoderBuffer();
  61738. buffer.Init(data, data.byteLength);
  61739. var decoder = new module.Decoder();
  61740. var geometry;
  61741. var status;
  61742. try {
  61743. var type = decoder.GetEncodedGeometryType(buffer);
  61744. switch (type) {
  61745. case module.TRIANGULAR_MESH:
  61746. geometry = new module.Mesh();
  61747. status = decoder.DecodeBufferToMesh(buffer, geometry);
  61748. break;
  61749. case module.POINT_CLOUD:
  61750. geometry = new module.PointCloud();
  61751. status = decoder.DecodeBufferToPointCloud(buffer, geometry);
  61752. break;
  61753. default:
  61754. throw new Error("Invalid geometry type " + type);
  61755. }
  61756. if (!status.ok() || !geometry.ptr) {
  61757. throw new Error(status.error_msg());
  61758. }
  61759. var numPoints = geometry.num_points();
  61760. if (type === module.TRIANGULAR_MESH) {
  61761. var numFaces = geometry.num_faces();
  61762. var faceIndices = new module.DracoInt32Array();
  61763. try {
  61764. var indices = new Uint32Array(numFaces * 3);
  61765. for (var i = 0; i < numFaces; i++) {
  61766. decoder.GetFaceFromMesh(geometry, i, faceIndices);
  61767. var offset = i * 3;
  61768. indices[offset + 0] = faceIndices.GetValue(0);
  61769. indices[offset + 1] = faceIndices.GetValue(1);
  61770. indices[offset + 2] = faceIndices.GetValue(2);
  61771. }
  61772. vertexData.indices = indices;
  61773. }
  61774. finally {
  61775. module.destroy(faceIndices);
  61776. }
  61777. }
  61778. for (var kind in attributes) {
  61779. var uniqueId = attributes[kind];
  61780. var attribute = decoder.GetAttributeByUniqueId(geometry, uniqueId);
  61781. var dracoData = new module.DracoFloat32Array();
  61782. try {
  61783. decoder.GetAttributeFloatForAllPoints(geometry, attribute, dracoData);
  61784. var babylonData = new Float32Array(numPoints * attribute.num_components());
  61785. for (var i = 0; i < babylonData.length; i++) {
  61786. babylonData[i] = dracoData.GetValue(i);
  61787. }
  61788. vertexData.set(babylonData, kind);
  61789. }
  61790. finally {
  61791. module.destroy(dracoData);
  61792. }
  61793. }
  61794. }
  61795. finally {
  61796. if (geometry) {
  61797. module.destroy(geometry);
  61798. }
  61799. module.destroy(decoder);
  61800. module.destroy(buffer);
  61801. }
  61802. return vertexData;
  61803. });
  61804. };
  61805. DracoCompression._GetDecoderModule = function () {
  61806. if (!DracoCompression._DecoderModulePromise) {
  61807. var promise = null;
  61808. var config_1 = {};
  61809. if (typeof DracoDecoderModule !== "undefined") {
  61810. promise = Promise.resolve();
  61811. }
  61812. else {
  61813. var decoder = DracoCompression.Configuration.decoder;
  61814. if (decoder) {
  61815. if (decoder.wasmUrl && decoder.wasmBinaryUrl && typeof WebAssembly === "object") {
  61816. promise = Promise.all([
  61817. DracoCompression._LoadScriptAsync(decoder.wasmUrl),
  61818. DracoCompression._LoadFileAsync(decoder.wasmBinaryUrl).then(function (data) {
  61819. config_1.wasmBinary = data;
  61820. })
  61821. ]);
  61822. }
  61823. else if (decoder.fallbackUrl) {
  61824. promise = DracoCompression._LoadScriptAsync(decoder.fallbackUrl);
  61825. }
  61826. }
  61827. }
  61828. if (!promise) {
  61829. throw new Error("Draco decoder module is not available");
  61830. }
  61831. DracoCompression._DecoderModulePromise = promise.then(function () {
  61832. return new Promise(function (resolve) {
  61833. config_1.onModuleLoaded = function (decoderModule) {
  61834. // decoderModule is Promise-like. Wrap before resolving to avoid loop.
  61835. resolve({ module: decoderModule });
  61836. };
  61837. DracoDecoderModule(config_1);
  61838. });
  61839. });
  61840. }
  61841. return DracoCompression._DecoderModulePromise;
  61842. };
  61843. DracoCompression._LoadScriptAsync = function (url) {
  61844. return new Promise(function (resolve, reject) {
  61845. BABYLON.Tools.LoadScript(url, function () {
  61846. resolve();
  61847. }, function (message) {
  61848. reject(new Error(message));
  61849. });
  61850. });
  61851. };
  61852. DracoCompression._LoadFileAsync = function (url) {
  61853. return new Promise(function (resolve, reject) {
  61854. BABYLON.Tools.LoadFile(url, function (data) {
  61855. resolve(data);
  61856. }, undefined, undefined, true, function (request, exception) {
  61857. reject(exception);
  61858. });
  61859. });
  61860. };
  61861. /**
  61862. * The configuration.
  61863. */
  61864. DracoCompression.Configuration = {
  61865. decoder: {
  61866. wasmUrl: "https://preview.babylonjs.com/draco_wasm_wrapper_gltf.js",
  61867. wasmBinaryUrl: "https://preview.babylonjs.com/draco_decoder_gltf.wasm",
  61868. fallbackUrl: "https://preview.babylonjs.com/draco_decoder_gltf.js"
  61869. }
  61870. };
  61871. return DracoCompression;
  61872. }());
  61873. BABYLON.DracoCompression = DracoCompression;
  61874. })(BABYLON || (BABYLON = {}));
  61875. //# sourceMappingURL=babylon.dracoCompression.js.map
  61876. var BABYLON;
  61877. (function (BABYLON) {
  61878. var AudioEngine = /** @class */ (function () {
  61879. function AudioEngine() {
  61880. this._audioContext = null;
  61881. this._audioContextInitialized = false;
  61882. this.canUseWebAudio = false;
  61883. this.WarnedWebAudioUnsupported = false;
  61884. this.unlocked = false;
  61885. this.isMP3supported = false;
  61886. this.isOGGsupported = false;
  61887. if (typeof window.AudioContext !== 'undefined' || typeof window.webkitAudioContext !== 'undefined') {
  61888. window.AudioContext = window.AudioContext || window.webkitAudioContext;
  61889. this.canUseWebAudio = true;
  61890. }
  61891. var audioElem = document.createElement('audio');
  61892. try {
  61893. if (audioElem && !!audioElem.canPlayType && audioElem.canPlayType('audio/mpeg; codecs="mp3"').replace(/^no$/, '')) {
  61894. this.isMP3supported = true;
  61895. }
  61896. }
  61897. catch (e) {
  61898. // protect error during capability check.
  61899. }
  61900. try {
  61901. if (audioElem && !!audioElem.canPlayType && audioElem.canPlayType('audio/ogg; codecs="vorbis"').replace(/^no$/, '')) {
  61902. this.isOGGsupported = true;
  61903. }
  61904. }
  61905. catch (e) {
  61906. // protect error during capability check.
  61907. }
  61908. if (/iPad|iPhone|iPod/.test(navigator.platform)) {
  61909. this._unlockiOSaudio();
  61910. }
  61911. else {
  61912. this.unlocked = true;
  61913. }
  61914. }
  61915. Object.defineProperty(AudioEngine.prototype, "audioContext", {
  61916. get: function () {
  61917. if (!this._audioContextInitialized) {
  61918. this._initializeAudioContext();
  61919. }
  61920. return this._audioContext;
  61921. },
  61922. enumerable: true,
  61923. configurable: true
  61924. });
  61925. AudioEngine.prototype._unlockiOSaudio = function () {
  61926. var _this = this;
  61927. var unlockaudio = function () {
  61928. if (!_this.audioContext) {
  61929. return;
  61930. }
  61931. var buffer = _this.audioContext.createBuffer(1, 1, 22050);
  61932. var source = _this.audioContext.createBufferSource();
  61933. source.buffer = buffer;
  61934. source.connect(_this.audioContext.destination);
  61935. source.start(0);
  61936. setTimeout(function () {
  61937. if ((source.playbackState === source.PLAYING_STATE || source.playbackState === source.FINISHED_STATE)) {
  61938. _this.unlocked = true;
  61939. window.removeEventListener('touchend', unlockaudio, false);
  61940. if (_this.onAudioUnlocked) {
  61941. _this.onAudioUnlocked();
  61942. }
  61943. }
  61944. }, 0);
  61945. };
  61946. window.addEventListener('touchend', unlockaudio, false);
  61947. };
  61948. AudioEngine.prototype._initializeAudioContext = function () {
  61949. try {
  61950. if (this.canUseWebAudio) {
  61951. this._audioContext = new AudioContext();
  61952. // create a global volume gain node
  61953. this.masterGain = this._audioContext.createGain();
  61954. this.masterGain.gain.value = 1;
  61955. this.masterGain.connect(this._audioContext.destination);
  61956. this._audioContextInitialized = true;
  61957. }
  61958. }
  61959. catch (e) {
  61960. this.canUseWebAudio = false;
  61961. BABYLON.Tools.Error("Web Audio: " + e.message);
  61962. }
  61963. };
  61964. AudioEngine.prototype.dispose = function () {
  61965. if (this.canUseWebAudio && this._audioContextInitialized) {
  61966. if (this._connectedAnalyser && this._audioContext) {
  61967. this._connectedAnalyser.stopDebugCanvas();
  61968. this._connectedAnalyser.dispose();
  61969. this.masterGain.disconnect();
  61970. this.masterGain.connect(this._audioContext.destination);
  61971. this._connectedAnalyser = null;
  61972. }
  61973. this.masterGain.gain.value = 1;
  61974. }
  61975. this.WarnedWebAudioUnsupported = false;
  61976. };
  61977. AudioEngine.prototype.getGlobalVolume = function () {
  61978. if (this.canUseWebAudio && this._audioContextInitialized) {
  61979. return this.masterGain.gain.value;
  61980. }
  61981. else {
  61982. return -1;
  61983. }
  61984. };
  61985. AudioEngine.prototype.setGlobalVolume = function (newVolume) {
  61986. if (this.canUseWebAudio && this._audioContextInitialized) {
  61987. this.masterGain.gain.value = newVolume;
  61988. }
  61989. };
  61990. AudioEngine.prototype.connectToAnalyser = function (analyser) {
  61991. if (this._connectedAnalyser) {
  61992. this._connectedAnalyser.stopDebugCanvas();
  61993. }
  61994. if (this.canUseWebAudio && this._audioContextInitialized && this._audioContext) {
  61995. this._connectedAnalyser = analyser;
  61996. this.masterGain.disconnect();
  61997. this._connectedAnalyser.connectAudioNodes(this.masterGain, this._audioContext.destination);
  61998. }
  61999. };
  62000. return AudioEngine;
  62001. }());
  62002. BABYLON.AudioEngine = AudioEngine;
  62003. })(BABYLON || (BABYLON = {}));
  62004. //# sourceMappingURL=babylon.audioEngine.js.map
  62005. var BABYLON;
  62006. (function (BABYLON) {
  62007. var Sound = /** @class */ (function () {
  62008. /**
  62009. * Create a sound and attach it to a scene
  62010. * @param name Name of your sound
  62011. * @param urlOrArrayBuffer Url to the sound to load async or ArrayBuffer
  62012. * @param readyToPlayCallback Provide a callback function if you'd like to load your code once the sound is ready to be played
  62013. * @param options Objects to provide with the current available options: autoplay, loop, volume, spatialSound, maxDistance, rolloffFactor, refDistance, distanceModel, panningModel, streaming
  62014. */
  62015. function Sound(name, urlOrArrayBuffer, scene, readyToPlayCallback, options) {
  62016. if (readyToPlayCallback === void 0) { readyToPlayCallback = null; }
  62017. var _this = this;
  62018. this.autoplay = false;
  62019. this.loop = false;
  62020. this.useCustomAttenuation = false;
  62021. this.spatialSound = false;
  62022. this.refDistance = 1;
  62023. this.rolloffFactor = 1;
  62024. this.maxDistance = 100;
  62025. this.distanceModel = "linear";
  62026. this._panningModel = "equalpower";
  62027. this._playbackRate = 1;
  62028. this._streaming = false;
  62029. this._startTime = 0;
  62030. this._startOffset = 0;
  62031. this._position = BABYLON.Vector3.Zero();
  62032. this._localDirection = new BABYLON.Vector3(1, 0, 0);
  62033. this._volume = 1;
  62034. this._isReadyToPlay = false;
  62035. this.isPlaying = false;
  62036. this.isPaused = false;
  62037. this._isDirectional = false;
  62038. // Used if you'd like to create a directional sound.
  62039. // If not set, the sound will be omnidirectional
  62040. this._coneInnerAngle = 360;
  62041. this._coneOuterAngle = 360;
  62042. this._coneOuterGain = 0;
  62043. this._isOutputConnected = false;
  62044. this._urlType = "Unknown";
  62045. this.name = name;
  62046. this._scene = scene;
  62047. this._readyToPlayCallback = readyToPlayCallback;
  62048. // Default custom attenuation function is a linear attenuation
  62049. this._customAttenuationFunction = function (currentVolume, currentDistance, maxDistance, refDistance, rolloffFactor) {
  62050. if (currentDistance < maxDistance) {
  62051. return currentVolume * (1 - currentDistance / maxDistance);
  62052. }
  62053. else {
  62054. return 0;
  62055. }
  62056. };
  62057. if (options) {
  62058. this.autoplay = options.autoplay || false;
  62059. this.loop = options.loop || false;
  62060. // if volume === 0, we need another way to check this option
  62061. if (options.volume !== undefined) {
  62062. this._volume = options.volume;
  62063. }
  62064. this.spatialSound = options.spatialSound || false;
  62065. this.maxDistance = options.maxDistance || 100;
  62066. this.useCustomAttenuation = options.useCustomAttenuation || false;
  62067. this.rolloffFactor = options.rolloffFactor || 1;
  62068. this.refDistance = options.refDistance || 1;
  62069. this.distanceModel = options.distanceModel || "linear";
  62070. this._playbackRate = options.playbackRate || 1;
  62071. this._streaming = options.streaming || false;
  62072. }
  62073. if (BABYLON.Engine.audioEngine.canUseWebAudio && BABYLON.Engine.audioEngine.audioContext) {
  62074. this._soundGain = BABYLON.Engine.audioEngine.audioContext.createGain();
  62075. this._soundGain.gain.value = this._volume;
  62076. this._inputAudioNode = this._soundGain;
  62077. this._ouputAudioNode = this._soundGain;
  62078. if (this.spatialSound) {
  62079. this._createSpatialParameters();
  62080. }
  62081. this._scene.mainSoundTrack.AddSound(this);
  62082. var validParameter = true;
  62083. // if no parameter is passed, you need to call setAudioBuffer yourself to prepare the sound
  62084. if (urlOrArrayBuffer) {
  62085. try {
  62086. if (typeof (urlOrArrayBuffer) === "string")
  62087. this._urlType = "String";
  62088. if (Array.isArray(urlOrArrayBuffer))
  62089. this._urlType = "Array";
  62090. if (urlOrArrayBuffer instanceof ArrayBuffer)
  62091. this._urlType = "ArrayBuffer";
  62092. var urls = [];
  62093. var codecSupportedFound = false;
  62094. switch (this._urlType) {
  62095. case "ArrayBuffer":
  62096. if (urlOrArrayBuffer.byteLength > 0) {
  62097. codecSupportedFound = true;
  62098. this._soundLoaded(urlOrArrayBuffer);
  62099. }
  62100. break;
  62101. case "String":
  62102. urls.push(urlOrArrayBuffer);
  62103. case "Array":
  62104. if (urls.length === 0)
  62105. urls = urlOrArrayBuffer;
  62106. // If we found a supported format, we load it immediately and stop the loop
  62107. for (var i = 0; i < urls.length; i++) {
  62108. var url = urls[i];
  62109. if (url.indexOf(".mp3", url.length - 4) !== -1 && BABYLON.Engine.audioEngine.isMP3supported) {
  62110. codecSupportedFound = true;
  62111. }
  62112. if (url.indexOf(".ogg", url.length - 4) !== -1 && BABYLON.Engine.audioEngine.isOGGsupported) {
  62113. codecSupportedFound = true;
  62114. }
  62115. if (url.indexOf(".wav", url.length - 4) !== -1) {
  62116. codecSupportedFound = true;
  62117. }
  62118. if (url.indexOf("blob:") !== -1) {
  62119. codecSupportedFound = true;
  62120. }
  62121. if (codecSupportedFound) {
  62122. // Loading sound using XHR2
  62123. if (!this._streaming) {
  62124. this._scene._loadFile(url, function (data) {
  62125. _this._soundLoaded(data);
  62126. }, undefined, true, true, function (exception) {
  62127. if (exception) {
  62128. BABYLON.Tools.Error("XHR " + exception.status + " error on: " + url + ".");
  62129. }
  62130. BABYLON.Tools.Error("Sound creation aborted.");
  62131. _this._scene.mainSoundTrack.RemoveSound(_this);
  62132. });
  62133. }
  62134. // Streaming sound using HTML5 Audio tag
  62135. else {
  62136. this._htmlAudioElement = new Audio(url);
  62137. this._htmlAudioElement.controls = false;
  62138. this._htmlAudioElement.loop = this.loop;
  62139. BABYLON.Tools.SetCorsBehavior(url, this._htmlAudioElement);
  62140. this._htmlAudioElement.preload = "auto";
  62141. this._htmlAudioElement.addEventListener("canplaythrough", function () {
  62142. _this._isReadyToPlay = true;
  62143. if (_this.autoplay) {
  62144. _this.play();
  62145. }
  62146. if (_this._readyToPlayCallback) {
  62147. _this._readyToPlayCallback();
  62148. }
  62149. });
  62150. document.body.appendChild(this._htmlAudioElement);
  62151. }
  62152. break;
  62153. }
  62154. }
  62155. break;
  62156. default:
  62157. validParameter = false;
  62158. break;
  62159. }
  62160. if (!validParameter) {
  62161. BABYLON.Tools.Error("Parameter must be a URL to the sound, an Array of URLs (.mp3 & .ogg) or an ArrayBuffer of the sound.");
  62162. }
  62163. else {
  62164. if (!codecSupportedFound) {
  62165. this._isReadyToPlay = true;
  62166. // Simulating a ready to play event to avoid breaking code path
  62167. if (this._readyToPlayCallback) {
  62168. window.setTimeout(function () {
  62169. if (_this._readyToPlayCallback) {
  62170. _this._readyToPlayCallback();
  62171. }
  62172. }, 1000);
  62173. }
  62174. }
  62175. }
  62176. }
  62177. catch (ex) {
  62178. BABYLON.Tools.Error("Unexpected error. Sound creation aborted.");
  62179. this._scene.mainSoundTrack.RemoveSound(this);
  62180. }
  62181. }
  62182. }
  62183. else {
  62184. // Adding an empty sound to avoid breaking audio calls for non Web Audio browsers
  62185. this._scene.mainSoundTrack.AddSound(this);
  62186. if (!BABYLON.Engine.audioEngine.WarnedWebAudioUnsupported) {
  62187. BABYLON.Tools.Error("Web Audio is not supported by your browser.");
  62188. BABYLON.Engine.audioEngine.WarnedWebAudioUnsupported = true;
  62189. }
  62190. // Simulating a ready to play event to avoid breaking code for non web audio browsers
  62191. if (this._readyToPlayCallback) {
  62192. window.setTimeout(function () {
  62193. if (_this._readyToPlayCallback) {
  62194. _this._readyToPlayCallback();
  62195. }
  62196. }, 1000);
  62197. }
  62198. }
  62199. }
  62200. Sound.prototype.dispose = function () {
  62201. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  62202. if (this.isPlaying) {
  62203. this.stop();
  62204. }
  62205. this._isReadyToPlay = false;
  62206. if (this.soundTrackId === -1) {
  62207. this._scene.mainSoundTrack.RemoveSound(this);
  62208. }
  62209. else {
  62210. this._scene.soundTracks[this.soundTrackId].RemoveSound(this);
  62211. }
  62212. if (this._soundGain) {
  62213. this._soundGain.disconnect();
  62214. this._soundGain = null;
  62215. }
  62216. if (this._soundPanner) {
  62217. this._soundPanner.disconnect();
  62218. this._soundPanner = null;
  62219. }
  62220. if (this._soundSource) {
  62221. this._soundSource.disconnect();
  62222. this._soundSource = null;
  62223. }
  62224. this._audioBuffer = null;
  62225. if (this._htmlAudioElement) {
  62226. this._htmlAudioElement.pause();
  62227. this._htmlAudioElement.src = "";
  62228. document.body.removeChild(this._htmlAudioElement);
  62229. }
  62230. if (this._connectedMesh && this._registerFunc) {
  62231. this._connectedMesh.unregisterAfterWorldMatrixUpdate(this._registerFunc);
  62232. this._connectedMesh = null;
  62233. }
  62234. }
  62235. };
  62236. Sound.prototype.isReady = function () {
  62237. return this._isReadyToPlay;
  62238. };
  62239. Sound.prototype._soundLoaded = function (audioData) {
  62240. var _this = this;
  62241. if (!BABYLON.Engine.audioEngine.audioContext) {
  62242. return;
  62243. }
  62244. BABYLON.Engine.audioEngine.audioContext.decodeAudioData(audioData, function (buffer) {
  62245. _this._audioBuffer = buffer;
  62246. _this._isReadyToPlay = true;
  62247. if (_this.autoplay) {
  62248. _this.play();
  62249. }
  62250. if (_this._readyToPlayCallback) {
  62251. _this._readyToPlayCallback();
  62252. }
  62253. }, function (err) { BABYLON.Tools.Error("Error while decoding audio data for: " + _this.name + " / Error: " + err); });
  62254. };
  62255. Sound.prototype.setAudioBuffer = function (audioBuffer) {
  62256. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  62257. this._audioBuffer = audioBuffer;
  62258. this._isReadyToPlay = true;
  62259. }
  62260. };
  62261. Sound.prototype.updateOptions = function (options) {
  62262. if (options) {
  62263. this.loop = options.loop || this.loop;
  62264. this.maxDistance = options.maxDistance || this.maxDistance;
  62265. this.useCustomAttenuation = options.useCustomAttenuation || this.useCustomAttenuation;
  62266. this.rolloffFactor = options.rolloffFactor || this.rolloffFactor;
  62267. this.refDistance = options.refDistance || this.refDistance;
  62268. this.distanceModel = options.distanceModel || this.distanceModel;
  62269. this._playbackRate = options.playbackRate || this._playbackRate;
  62270. this._updateSpatialParameters();
  62271. if (this.isPlaying) {
  62272. if (this._streaming) {
  62273. this._htmlAudioElement.playbackRate = this._playbackRate;
  62274. }
  62275. else {
  62276. if (this._soundSource) {
  62277. this._soundSource.playbackRate.value = this._playbackRate;
  62278. }
  62279. }
  62280. }
  62281. }
  62282. };
  62283. Sound.prototype._createSpatialParameters = function () {
  62284. if (BABYLON.Engine.audioEngine.canUseWebAudio && BABYLON.Engine.audioEngine.audioContext) {
  62285. if (this._scene.headphone) {
  62286. this._panningModel = "HRTF";
  62287. }
  62288. this._soundPanner = BABYLON.Engine.audioEngine.audioContext.createPanner();
  62289. this._updateSpatialParameters();
  62290. this._soundPanner.connect(this._ouputAudioNode);
  62291. this._inputAudioNode = this._soundPanner;
  62292. }
  62293. };
  62294. Sound.prototype._updateSpatialParameters = function () {
  62295. if (this.spatialSound && this._soundPanner) {
  62296. if (this.useCustomAttenuation) {
  62297. // Tricks to disable in a way embedded Web Audio attenuation
  62298. this._soundPanner.distanceModel = "linear";
  62299. this._soundPanner.maxDistance = Number.MAX_VALUE;
  62300. this._soundPanner.refDistance = 1;
  62301. this._soundPanner.rolloffFactor = 1;
  62302. this._soundPanner.panningModel = this._panningModel;
  62303. }
  62304. else {
  62305. this._soundPanner.distanceModel = this.distanceModel;
  62306. this._soundPanner.maxDistance = this.maxDistance;
  62307. this._soundPanner.refDistance = this.refDistance;
  62308. this._soundPanner.rolloffFactor = this.rolloffFactor;
  62309. this._soundPanner.panningModel = this._panningModel;
  62310. }
  62311. }
  62312. };
  62313. Sound.prototype.switchPanningModelToHRTF = function () {
  62314. this._panningModel = "HRTF";
  62315. this._switchPanningModel();
  62316. };
  62317. Sound.prototype.switchPanningModelToEqualPower = function () {
  62318. this._panningModel = "equalpower";
  62319. this._switchPanningModel();
  62320. };
  62321. Sound.prototype._switchPanningModel = function () {
  62322. if (BABYLON.Engine.audioEngine.canUseWebAudio && this.spatialSound && this._soundPanner) {
  62323. this._soundPanner.panningModel = this._panningModel;
  62324. }
  62325. };
  62326. Sound.prototype.connectToSoundTrackAudioNode = function (soundTrackAudioNode) {
  62327. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  62328. if (this._isOutputConnected) {
  62329. this._ouputAudioNode.disconnect();
  62330. }
  62331. this._ouputAudioNode.connect(soundTrackAudioNode);
  62332. this._isOutputConnected = true;
  62333. }
  62334. };
  62335. /**
  62336. * Transform this sound into a directional source
  62337. * @param coneInnerAngle Size of the inner cone in degree
  62338. * @param coneOuterAngle Size of the outer cone in degree
  62339. * @param coneOuterGain Volume of the sound outside the outer cone (between 0.0 and 1.0)
  62340. */
  62341. Sound.prototype.setDirectionalCone = function (coneInnerAngle, coneOuterAngle, coneOuterGain) {
  62342. if (coneOuterAngle < coneInnerAngle) {
  62343. BABYLON.Tools.Error("setDirectionalCone(): outer angle of the cone must be superior or equal to the inner angle.");
  62344. return;
  62345. }
  62346. this._coneInnerAngle = coneInnerAngle;
  62347. this._coneOuterAngle = coneOuterAngle;
  62348. this._coneOuterGain = coneOuterGain;
  62349. this._isDirectional = true;
  62350. if (this.isPlaying && this.loop) {
  62351. this.stop();
  62352. this.play();
  62353. }
  62354. };
  62355. Sound.prototype.setPosition = function (newPosition) {
  62356. this._position = newPosition;
  62357. if (BABYLON.Engine.audioEngine.canUseWebAudio && this.spatialSound && this._soundPanner) {
  62358. this._soundPanner.setPosition(this._position.x, this._position.y, this._position.z);
  62359. }
  62360. };
  62361. Sound.prototype.setLocalDirectionToMesh = function (newLocalDirection) {
  62362. this._localDirection = newLocalDirection;
  62363. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._connectedMesh && this.isPlaying) {
  62364. this._updateDirection();
  62365. }
  62366. };
  62367. Sound.prototype._updateDirection = function () {
  62368. if (!this._connectedMesh || !this._soundPanner) {
  62369. return;
  62370. }
  62371. var mat = this._connectedMesh.getWorldMatrix();
  62372. var direction = BABYLON.Vector3.TransformNormal(this._localDirection, mat);
  62373. direction.normalize();
  62374. this._soundPanner.setOrientation(direction.x, direction.y, direction.z);
  62375. };
  62376. Sound.prototype.updateDistanceFromListener = function () {
  62377. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._connectedMesh && this.useCustomAttenuation && this._soundGain && this._scene.activeCamera) {
  62378. var distance = this._connectedMesh.getDistanceToCamera(this._scene.activeCamera);
  62379. this._soundGain.gain.value = this._customAttenuationFunction(this._volume, distance, this.maxDistance, this.refDistance, this.rolloffFactor);
  62380. }
  62381. };
  62382. Sound.prototype.setAttenuationFunction = function (callback) {
  62383. this._customAttenuationFunction = callback;
  62384. };
  62385. /**
  62386. * Play the sound
  62387. * @param time (optional) Start the sound after X seconds. Start immediately (0) by default.
  62388. * @param offset (optional) Start the sound setting it at a specific time
  62389. */
  62390. Sound.prototype.play = function (time, offset) {
  62391. var _this = this;
  62392. if (this._isReadyToPlay && this._scene.audioEnabled && BABYLON.Engine.audioEngine.audioContext) {
  62393. try {
  62394. if (this._startOffset < 0) {
  62395. time = -this._startOffset;
  62396. this._startOffset = 0;
  62397. }
  62398. var startTime = time ? BABYLON.Engine.audioEngine.audioContext.currentTime + time : BABYLON.Engine.audioEngine.audioContext.currentTime;
  62399. if (!this._soundSource || !this._streamingSource) {
  62400. if (this.spatialSound && this._soundPanner) {
  62401. this._soundPanner.setPosition(this._position.x, this._position.y, this._position.z);
  62402. if (this._isDirectional) {
  62403. this._soundPanner.coneInnerAngle = this._coneInnerAngle;
  62404. this._soundPanner.coneOuterAngle = this._coneOuterAngle;
  62405. this._soundPanner.coneOuterGain = this._coneOuterGain;
  62406. if (this._connectedMesh) {
  62407. this._updateDirection();
  62408. }
  62409. else {
  62410. this._soundPanner.setOrientation(this._localDirection.x, this._localDirection.y, this._localDirection.z);
  62411. }
  62412. }
  62413. }
  62414. }
  62415. if (this._streaming) {
  62416. if (!this._streamingSource) {
  62417. this._streamingSource = BABYLON.Engine.audioEngine.audioContext.createMediaElementSource(this._htmlAudioElement);
  62418. this._htmlAudioElement.onended = function () { _this._onended(); };
  62419. this._htmlAudioElement.playbackRate = this._playbackRate;
  62420. }
  62421. this._streamingSource.disconnect();
  62422. this._streamingSource.connect(this._inputAudioNode);
  62423. this._htmlAudioElement.play();
  62424. }
  62425. else {
  62426. this._soundSource = BABYLON.Engine.audioEngine.audioContext.createBufferSource();
  62427. this._soundSource.buffer = this._audioBuffer;
  62428. this._soundSource.connect(this._inputAudioNode);
  62429. this._soundSource.loop = this.loop;
  62430. this._soundSource.playbackRate.value = this._playbackRate;
  62431. this._soundSource.onended = function () { _this._onended(); };
  62432. if (this._soundSource.buffer) {
  62433. this._soundSource.start(startTime, this.isPaused ? this._startOffset % this._soundSource.buffer.duration : offset ? offset : 0);
  62434. }
  62435. }
  62436. this._startTime = startTime;
  62437. this.isPlaying = true;
  62438. this.isPaused = false;
  62439. }
  62440. catch (ex) {
  62441. BABYLON.Tools.Error("Error while trying to play audio: " + this.name + ", " + ex.message);
  62442. }
  62443. }
  62444. };
  62445. Sound.prototype._onended = function () {
  62446. this.isPlaying = false;
  62447. if (this.onended) {
  62448. this.onended();
  62449. }
  62450. };
  62451. /**
  62452. * Stop the sound
  62453. * @param time (optional) Stop the sound after X seconds. Stop immediately (0) by default.
  62454. */
  62455. Sound.prototype.stop = function (time) {
  62456. if (this.isPlaying) {
  62457. if (this._streaming) {
  62458. this._htmlAudioElement.pause();
  62459. // Test needed for Firefox or it will generate an Invalid State Error
  62460. if (this._htmlAudioElement.currentTime > 0) {
  62461. this._htmlAudioElement.currentTime = 0;
  62462. }
  62463. }
  62464. else if (BABYLON.Engine.audioEngine.audioContext && this._soundSource) {
  62465. var stopTime = time ? BABYLON.Engine.audioEngine.audioContext.currentTime + time : BABYLON.Engine.audioEngine.audioContext.currentTime;
  62466. this._soundSource.stop(stopTime);
  62467. this._soundSource.onended = function () { };
  62468. if (!this.isPaused) {
  62469. this._startOffset = 0;
  62470. }
  62471. }
  62472. this.isPlaying = false;
  62473. }
  62474. };
  62475. Sound.prototype.pause = function () {
  62476. if (this.isPlaying) {
  62477. this.isPaused = true;
  62478. if (this._streaming) {
  62479. this._htmlAudioElement.pause();
  62480. }
  62481. else if (BABYLON.Engine.audioEngine.audioContext) {
  62482. this.stop(0);
  62483. this._startOffset += BABYLON.Engine.audioEngine.audioContext.currentTime - this._startTime;
  62484. }
  62485. }
  62486. };
  62487. Sound.prototype.setVolume = function (newVolume, time) {
  62488. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._soundGain) {
  62489. if (time && BABYLON.Engine.audioEngine.audioContext) {
  62490. this._soundGain.gain.cancelScheduledValues(BABYLON.Engine.audioEngine.audioContext.currentTime);
  62491. this._soundGain.gain.setValueAtTime(this._soundGain.gain.value, BABYLON.Engine.audioEngine.audioContext.currentTime);
  62492. this._soundGain.gain.linearRampToValueAtTime(newVolume, BABYLON.Engine.audioEngine.audioContext.currentTime + time);
  62493. }
  62494. else {
  62495. this._soundGain.gain.value = newVolume;
  62496. }
  62497. }
  62498. this._volume = newVolume;
  62499. };
  62500. Sound.prototype.setPlaybackRate = function (newPlaybackRate) {
  62501. this._playbackRate = newPlaybackRate;
  62502. if (this.isPlaying) {
  62503. if (this._streaming) {
  62504. this._htmlAudioElement.playbackRate = this._playbackRate;
  62505. }
  62506. else if (this._soundSource) {
  62507. this._soundSource.playbackRate.value = this._playbackRate;
  62508. }
  62509. }
  62510. };
  62511. Sound.prototype.getVolume = function () {
  62512. return this._volume;
  62513. };
  62514. Sound.prototype.attachToMesh = function (meshToConnectTo) {
  62515. var _this = this;
  62516. if (this._connectedMesh && this._registerFunc) {
  62517. this._connectedMesh.unregisterAfterWorldMatrixUpdate(this._registerFunc);
  62518. this._registerFunc = null;
  62519. }
  62520. this._connectedMesh = meshToConnectTo;
  62521. if (!this.spatialSound) {
  62522. this.spatialSound = true;
  62523. this._createSpatialParameters();
  62524. if (this.isPlaying && this.loop) {
  62525. this.stop();
  62526. this.play();
  62527. }
  62528. }
  62529. this._onRegisterAfterWorldMatrixUpdate(this._connectedMesh);
  62530. this._registerFunc = function (connectedMesh) { return _this._onRegisterAfterWorldMatrixUpdate(connectedMesh); };
  62531. meshToConnectTo.registerAfterWorldMatrixUpdate(this._registerFunc);
  62532. };
  62533. Sound.prototype.detachFromMesh = function () {
  62534. if (this._connectedMesh && this._registerFunc) {
  62535. this._connectedMesh.unregisterAfterWorldMatrixUpdate(this._registerFunc);
  62536. this._registerFunc = null;
  62537. this._connectedMesh = null;
  62538. }
  62539. };
  62540. Sound.prototype._onRegisterAfterWorldMatrixUpdate = function (node) {
  62541. if (!node.getBoundingInfo) {
  62542. return;
  62543. }
  62544. var mesh = node;
  62545. var boundingInfo = mesh.getBoundingInfo();
  62546. this.setPosition(boundingInfo.boundingSphere.centerWorld);
  62547. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._isDirectional && this.isPlaying) {
  62548. this._updateDirection();
  62549. }
  62550. };
  62551. Sound.prototype.clone = function () {
  62552. var _this = this;
  62553. if (!this._streaming) {
  62554. var setBufferAndRun = function () {
  62555. if (_this._isReadyToPlay) {
  62556. clonedSound._audioBuffer = _this.getAudioBuffer();
  62557. clonedSound._isReadyToPlay = true;
  62558. if (clonedSound.autoplay) {
  62559. clonedSound.play();
  62560. }
  62561. }
  62562. else {
  62563. window.setTimeout(setBufferAndRun, 300);
  62564. }
  62565. };
  62566. var currentOptions = {
  62567. autoplay: this.autoplay, loop: this.loop,
  62568. volume: this._volume, spatialSound: this.spatialSound, maxDistance: this.maxDistance,
  62569. useCustomAttenuation: this.useCustomAttenuation, rolloffFactor: this.rolloffFactor,
  62570. refDistance: this.refDistance, distanceModel: this.distanceModel
  62571. };
  62572. var clonedSound = new Sound(this.name + "_cloned", new ArrayBuffer(0), this._scene, null, currentOptions);
  62573. if (this.useCustomAttenuation) {
  62574. clonedSound.setAttenuationFunction(this._customAttenuationFunction);
  62575. }
  62576. clonedSound.setPosition(this._position);
  62577. clonedSound.setPlaybackRate(this._playbackRate);
  62578. setBufferAndRun();
  62579. return clonedSound;
  62580. }
  62581. // Can't clone a streaming sound
  62582. else {
  62583. return null;
  62584. }
  62585. };
  62586. Sound.prototype.getAudioBuffer = function () {
  62587. return this._audioBuffer;
  62588. };
  62589. Sound.prototype.serialize = function () {
  62590. var serializationObject = {
  62591. name: this.name,
  62592. url: this.name,
  62593. autoplay: this.autoplay,
  62594. loop: this.loop,
  62595. volume: this._volume,
  62596. spatialSound: this.spatialSound,
  62597. maxDistance: this.maxDistance,
  62598. rolloffFactor: this.rolloffFactor,
  62599. refDistance: this.refDistance,
  62600. distanceModel: this.distanceModel,
  62601. playbackRate: this._playbackRate,
  62602. panningModel: this._panningModel,
  62603. soundTrackId: this.soundTrackId
  62604. };
  62605. if (this.spatialSound) {
  62606. if (this._connectedMesh)
  62607. serializationObject.connectedMeshId = this._connectedMesh.id;
  62608. serializationObject.position = this._position.asArray();
  62609. serializationObject.refDistance = this.refDistance;
  62610. serializationObject.distanceModel = this.distanceModel;
  62611. serializationObject.isDirectional = this._isDirectional;
  62612. serializationObject.localDirectionToMesh = this._localDirection.asArray();
  62613. serializationObject.coneInnerAngle = this._coneInnerAngle;
  62614. serializationObject.coneOuterAngle = this._coneOuterAngle;
  62615. serializationObject.coneOuterGain = this._coneOuterGain;
  62616. }
  62617. return serializationObject;
  62618. };
  62619. Sound.Parse = function (parsedSound, scene, rootUrl, sourceSound) {
  62620. var soundName = parsedSound.name;
  62621. var soundUrl;
  62622. if (parsedSound.url) {
  62623. soundUrl = rootUrl + parsedSound.url;
  62624. }
  62625. else {
  62626. soundUrl = rootUrl + soundName;
  62627. }
  62628. var options = {
  62629. autoplay: parsedSound.autoplay, loop: parsedSound.loop, volume: parsedSound.volume,
  62630. spatialSound: parsedSound.spatialSound, maxDistance: parsedSound.maxDistance,
  62631. rolloffFactor: parsedSound.rolloffFactor,
  62632. refDistance: parsedSound.refDistance,
  62633. distanceModel: parsedSound.distanceModel,
  62634. playbackRate: parsedSound.playbackRate
  62635. };
  62636. var newSound;
  62637. if (!sourceSound) {
  62638. newSound = new Sound(soundName, soundUrl, scene, function () { scene._removePendingData(newSound); }, options);
  62639. scene._addPendingData(newSound);
  62640. }
  62641. else {
  62642. var setBufferAndRun = function () {
  62643. if (sourceSound._isReadyToPlay) {
  62644. newSound._audioBuffer = sourceSound.getAudioBuffer();
  62645. newSound._isReadyToPlay = true;
  62646. if (newSound.autoplay) {
  62647. newSound.play();
  62648. }
  62649. }
  62650. else {
  62651. window.setTimeout(setBufferAndRun, 300);
  62652. }
  62653. };
  62654. newSound = new Sound(soundName, new ArrayBuffer(0), scene, null, options);
  62655. setBufferAndRun();
  62656. }
  62657. if (parsedSound.position) {
  62658. var soundPosition = BABYLON.Vector3.FromArray(parsedSound.position);
  62659. newSound.setPosition(soundPosition);
  62660. }
  62661. if (parsedSound.isDirectional) {
  62662. newSound.setDirectionalCone(parsedSound.coneInnerAngle || 360, parsedSound.coneOuterAngle || 360, parsedSound.coneOuterGain || 0);
  62663. if (parsedSound.localDirectionToMesh) {
  62664. var localDirectionToMesh = BABYLON.Vector3.FromArray(parsedSound.localDirectionToMesh);
  62665. newSound.setLocalDirectionToMesh(localDirectionToMesh);
  62666. }
  62667. }
  62668. if (parsedSound.connectedMeshId) {
  62669. var connectedMesh = scene.getMeshByID(parsedSound.connectedMeshId);
  62670. if (connectedMesh) {
  62671. newSound.attachToMesh(connectedMesh);
  62672. }
  62673. }
  62674. return newSound;
  62675. };
  62676. return Sound;
  62677. }());
  62678. BABYLON.Sound = Sound;
  62679. })(BABYLON || (BABYLON = {}));
  62680. //# sourceMappingURL=babylon.sound.js.map
  62681. var BABYLON;
  62682. (function (BABYLON) {
  62683. var SoundTrack = /** @class */ (function () {
  62684. function SoundTrack(scene, options) {
  62685. this.id = -1;
  62686. this._isMainTrack = false;
  62687. this._isInitialized = false;
  62688. this._scene = scene;
  62689. this.soundCollection = new Array();
  62690. this._options = options;
  62691. if (!this._isMainTrack) {
  62692. this._scene.soundTracks.push(this);
  62693. this.id = this._scene.soundTracks.length - 1;
  62694. }
  62695. }
  62696. SoundTrack.prototype._initializeSoundTrackAudioGraph = function () {
  62697. if (BABYLON.Engine.audioEngine.canUseWebAudio && BABYLON.Engine.audioEngine.audioContext) {
  62698. this._outputAudioNode = BABYLON.Engine.audioEngine.audioContext.createGain();
  62699. this._outputAudioNode.connect(BABYLON.Engine.audioEngine.masterGain);
  62700. if (this._options) {
  62701. if (this._options.volume) {
  62702. this._outputAudioNode.gain.value = this._options.volume;
  62703. }
  62704. if (this._options.mainTrack) {
  62705. this._isMainTrack = this._options.mainTrack;
  62706. }
  62707. }
  62708. this._isInitialized = true;
  62709. }
  62710. };
  62711. SoundTrack.prototype.dispose = function () {
  62712. if (BABYLON.Engine.audioEngine && BABYLON.Engine.audioEngine.canUseWebAudio) {
  62713. if (this._connectedAnalyser) {
  62714. this._connectedAnalyser.stopDebugCanvas();
  62715. }
  62716. while (this.soundCollection.length) {
  62717. this.soundCollection[0].dispose();
  62718. }
  62719. if (this._outputAudioNode) {
  62720. this._outputAudioNode.disconnect();
  62721. }
  62722. this._outputAudioNode = null;
  62723. }
  62724. };
  62725. SoundTrack.prototype.AddSound = function (sound) {
  62726. if (!this._isInitialized) {
  62727. this._initializeSoundTrackAudioGraph();
  62728. }
  62729. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._outputAudioNode) {
  62730. sound.connectToSoundTrackAudioNode(this._outputAudioNode);
  62731. }
  62732. if (sound.soundTrackId) {
  62733. if (sound.soundTrackId === -1) {
  62734. this._scene.mainSoundTrack.RemoveSound(sound);
  62735. }
  62736. else {
  62737. this._scene.soundTracks[sound.soundTrackId].RemoveSound(sound);
  62738. }
  62739. }
  62740. this.soundCollection.push(sound);
  62741. sound.soundTrackId = this.id;
  62742. };
  62743. SoundTrack.prototype.RemoveSound = function (sound) {
  62744. var index = this.soundCollection.indexOf(sound);
  62745. if (index !== -1) {
  62746. this.soundCollection.splice(index, 1);
  62747. }
  62748. };
  62749. SoundTrack.prototype.setVolume = function (newVolume) {
  62750. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._outputAudioNode) {
  62751. this._outputAudioNode.gain.value = newVolume;
  62752. }
  62753. };
  62754. SoundTrack.prototype.switchPanningModelToHRTF = function () {
  62755. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  62756. for (var i = 0; i < this.soundCollection.length; i++) {
  62757. this.soundCollection[i].switchPanningModelToHRTF();
  62758. }
  62759. }
  62760. };
  62761. SoundTrack.prototype.switchPanningModelToEqualPower = function () {
  62762. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  62763. for (var i = 0; i < this.soundCollection.length; i++) {
  62764. this.soundCollection[i].switchPanningModelToEqualPower();
  62765. }
  62766. }
  62767. };
  62768. SoundTrack.prototype.connectToAnalyser = function (analyser) {
  62769. if (this._connectedAnalyser) {
  62770. this._connectedAnalyser.stopDebugCanvas();
  62771. }
  62772. this._connectedAnalyser = analyser;
  62773. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._outputAudioNode) {
  62774. this._outputAudioNode.disconnect();
  62775. this._connectedAnalyser.connectAudioNodes(this._outputAudioNode, BABYLON.Engine.audioEngine.masterGain);
  62776. }
  62777. };
  62778. return SoundTrack;
  62779. }());
  62780. BABYLON.SoundTrack = SoundTrack;
  62781. })(BABYLON || (BABYLON = {}));
  62782. //# sourceMappingURL=babylon.soundtrack.js.map
  62783. var BABYLON;
  62784. (function (BABYLON) {
  62785. /**
  62786. * Class used to work with sound analyzer using fast fourier transform (FFT)
  62787. * @see http://doc.babylonjs.com/how_to/playing_sounds_and_music
  62788. */
  62789. var Analyser = /** @class */ (function () {
  62790. /**
  62791. * Creates a new analyser
  62792. * @param scene defines hosting scene
  62793. */
  62794. function Analyser(scene) {
  62795. /**
  62796. * Gets or sets the smoothing
  62797. * @ignorenaming
  62798. */
  62799. this.SMOOTHING = 0.75;
  62800. /**
  62801. * Gets or sets the FFT table size
  62802. * @ignorenaming
  62803. */
  62804. this.FFT_SIZE = 512;
  62805. /**
  62806. * Gets or sets the bar graph amplitude
  62807. * @ignorenaming
  62808. */
  62809. this.BARGRAPHAMPLITUDE = 256;
  62810. /**
  62811. * Gets or sets the position of the debug canvas
  62812. * @ignorenaming
  62813. */
  62814. this.DEBUGCANVASPOS = { x: 20, y: 20 };
  62815. /**
  62816. * Gets or sets the debug canvas size
  62817. * @ignorenaming
  62818. */
  62819. this.DEBUGCANVASSIZE = { width: 320, height: 200 };
  62820. this._scene = scene;
  62821. this._audioEngine = BABYLON.Engine.audioEngine;
  62822. if (this._audioEngine.canUseWebAudio && this._audioEngine.audioContext) {
  62823. this._webAudioAnalyser = this._audioEngine.audioContext.createAnalyser();
  62824. this._webAudioAnalyser.minDecibels = -140;
  62825. this._webAudioAnalyser.maxDecibels = 0;
  62826. this._byteFreqs = new Uint8Array(this._webAudioAnalyser.frequencyBinCount);
  62827. this._byteTime = new Uint8Array(this._webAudioAnalyser.frequencyBinCount);
  62828. this._floatFreqs = new Float32Array(this._webAudioAnalyser.frequencyBinCount);
  62829. }
  62830. }
  62831. /**
  62832. * Get the number of data values you will have to play with for the visualization
  62833. * @see https://developer.mozilla.org/en-US/docs/Web/API/AnalyserNode/frequencyBinCount
  62834. * @returns a number
  62835. */
  62836. Analyser.prototype.getFrequencyBinCount = function () {
  62837. if (this._audioEngine.canUseWebAudio) {
  62838. return this._webAudioAnalyser.frequencyBinCount;
  62839. }
  62840. else {
  62841. return 0;
  62842. }
  62843. };
  62844. /**
  62845. * Gets the current frequency data as a byte array
  62846. * @see https://developer.mozilla.org/en-US/docs/Web/API/AnalyserNode/getByteFrequencyData
  62847. * @returns a Uint8Array
  62848. */
  62849. Analyser.prototype.getByteFrequencyData = function () {
  62850. if (this._audioEngine.canUseWebAudio) {
  62851. this._webAudioAnalyser.smoothingTimeConstant = this.SMOOTHING;
  62852. this._webAudioAnalyser.fftSize = this.FFT_SIZE;
  62853. this._webAudioAnalyser.getByteFrequencyData(this._byteFreqs);
  62854. }
  62855. return this._byteFreqs;
  62856. };
  62857. /**
  62858. * Gets the current waveform as a byte array
  62859. * @see https://developer.mozilla.org/en-US/docs/Web/API/AnalyserNode/getByteTimeDomainData
  62860. * @returns a Uint8Array
  62861. */
  62862. Analyser.prototype.getByteTimeDomainData = function () {
  62863. if (this._audioEngine.canUseWebAudio) {
  62864. this._webAudioAnalyser.smoothingTimeConstant = this.SMOOTHING;
  62865. this._webAudioAnalyser.fftSize = this.FFT_SIZE;
  62866. this._webAudioAnalyser.getByteTimeDomainData(this._byteTime);
  62867. }
  62868. return this._byteTime;
  62869. };
  62870. /**
  62871. * Gets the current frequency data as a float array
  62872. * @see https://developer.mozilla.org/en-US/docs/Web/API/AnalyserNode/getByteFrequencyData
  62873. * @returns a Float32Array
  62874. */
  62875. Analyser.prototype.getFloatFrequencyData = function () {
  62876. if (this._audioEngine.canUseWebAudio) {
  62877. this._webAudioAnalyser.smoothingTimeConstant = this.SMOOTHING;
  62878. this._webAudioAnalyser.fftSize = this.FFT_SIZE;
  62879. this._webAudioAnalyser.getFloatFrequencyData(this._floatFreqs);
  62880. }
  62881. return this._floatFreqs;
  62882. };
  62883. /**
  62884. * Renders the debug canvas
  62885. */
  62886. Analyser.prototype.drawDebugCanvas = function () {
  62887. var _this = this;
  62888. if (this._audioEngine.canUseWebAudio) {
  62889. if (!this._debugCanvas) {
  62890. this._debugCanvas = document.createElement("canvas");
  62891. this._debugCanvas.width = this.DEBUGCANVASSIZE.width;
  62892. this._debugCanvas.height = this.DEBUGCANVASSIZE.height;
  62893. this._debugCanvas.style.position = "absolute";
  62894. this._debugCanvas.style.top = this.DEBUGCANVASPOS.y + "px";
  62895. this._debugCanvas.style.left = this.DEBUGCANVASPOS.x + "px";
  62896. this._debugCanvasContext = this._debugCanvas.getContext("2d");
  62897. document.body.appendChild(this._debugCanvas);
  62898. this._registerFunc = function () {
  62899. _this.drawDebugCanvas();
  62900. };
  62901. this._scene.registerBeforeRender(this._registerFunc);
  62902. }
  62903. if (this._registerFunc && this._debugCanvasContext) {
  62904. var workingArray = this.getByteFrequencyData();
  62905. this._debugCanvasContext.fillStyle = 'rgb(0, 0, 0)';
  62906. this._debugCanvasContext.fillRect(0, 0, this.DEBUGCANVASSIZE.width, this.DEBUGCANVASSIZE.height);
  62907. // Draw the frequency domain chart.
  62908. for (var i = 0; i < this.getFrequencyBinCount(); i++) {
  62909. var value = workingArray[i];
  62910. var percent = value / this.BARGRAPHAMPLITUDE;
  62911. var height = this.DEBUGCANVASSIZE.height * percent;
  62912. var offset = this.DEBUGCANVASSIZE.height - height - 1;
  62913. var barWidth = this.DEBUGCANVASSIZE.width / this.getFrequencyBinCount();
  62914. var hue = i / this.getFrequencyBinCount() * 360;
  62915. this._debugCanvasContext.fillStyle = 'hsl(' + hue + ', 100%, 50%)';
  62916. this._debugCanvasContext.fillRect(i * barWidth, offset, barWidth, height);
  62917. }
  62918. }
  62919. }
  62920. };
  62921. /**
  62922. * Stops rendering the debug canvas and removes it
  62923. */
  62924. Analyser.prototype.stopDebugCanvas = function () {
  62925. if (this._debugCanvas) {
  62926. if (this._registerFunc) {
  62927. this._scene.unregisterBeforeRender(this._registerFunc);
  62928. this._registerFunc = null;
  62929. }
  62930. document.body.removeChild(this._debugCanvas);
  62931. this._debugCanvas = null;
  62932. this._debugCanvasContext = null;
  62933. }
  62934. };
  62935. /**
  62936. * Connects two audio nodes
  62937. * @param inputAudioNode defines first node to connect
  62938. * @param outputAudioNode defines second node to connect
  62939. */
  62940. Analyser.prototype.connectAudioNodes = function (inputAudioNode, outputAudioNode) {
  62941. if (this._audioEngine.canUseWebAudio) {
  62942. inputAudioNode.connect(this._webAudioAnalyser);
  62943. this._webAudioAnalyser.connect(outputAudioNode);
  62944. }
  62945. };
  62946. /**
  62947. * Releases all associated resources
  62948. */
  62949. Analyser.prototype.dispose = function () {
  62950. if (this._audioEngine.canUseWebAudio) {
  62951. this._webAudioAnalyser.disconnect();
  62952. }
  62953. };
  62954. return Analyser;
  62955. }());
  62956. BABYLON.Analyser = Analyser;
  62957. })(BABYLON || (BABYLON = {}));
  62958. //# sourceMappingURL=babylon.analyser.js.map
  62959. var BABYLON;
  62960. (function (BABYLON) {
  62961. var CubeTexture = /** @class */ (function (_super) {
  62962. __extends(CubeTexture, _super);
  62963. function CubeTexture(rootUrl, scene, extensions, noMipmap, files, onLoad, onError, format, prefiltered, forcedExtension) {
  62964. if (extensions === void 0) { extensions = null; }
  62965. if (noMipmap === void 0) { noMipmap = false; }
  62966. if (files === void 0) { files = null; }
  62967. if (onLoad === void 0) { onLoad = null; }
  62968. if (onError === void 0) { onError = null; }
  62969. if (format === void 0) { format = BABYLON.Engine.TEXTUREFORMAT_RGBA; }
  62970. if (prefiltered === void 0) { prefiltered = false; }
  62971. if (forcedExtension === void 0) { forcedExtension = null; }
  62972. var _this = _super.call(this, scene) || this;
  62973. _this.coordinatesMode = BABYLON.Texture.CUBIC_MODE;
  62974. /**
  62975. * Gets or sets the center of the bounding box associated with the cube texture
  62976. * It must define where the camera used to render the texture was set
  62977. */
  62978. _this.boundingBoxPosition = BABYLON.Vector3.Zero();
  62979. _this._rotationY = 0;
  62980. _this.name = rootUrl;
  62981. _this.url = rootUrl;
  62982. _this._noMipmap = noMipmap;
  62983. _this.hasAlpha = false;
  62984. _this._format = format;
  62985. _this._prefiltered = prefiltered;
  62986. _this.isCube = true;
  62987. _this._textureMatrix = BABYLON.Matrix.Identity();
  62988. if (prefiltered) {
  62989. _this.gammaSpace = false;
  62990. }
  62991. if (!rootUrl && !files) {
  62992. return _this;
  62993. }
  62994. _this._texture = _this._getFromCache(rootUrl, noMipmap);
  62995. var lastDot = rootUrl.lastIndexOf(".");
  62996. var extension = forcedExtension ? forcedExtension : (lastDot > -1 ? rootUrl.substring(lastDot).toLowerCase() : "");
  62997. var isDDS = (extension === ".dds");
  62998. if (!files) {
  62999. if (!isDDS && !extensions) {
  63000. extensions = ["_px.jpg", "_py.jpg", "_pz.jpg", "_nx.jpg", "_ny.jpg", "_nz.jpg"];
  63001. }
  63002. files = [];
  63003. if (extensions) {
  63004. for (var index = 0; index < extensions.length; index++) {
  63005. files.push(rootUrl + extensions[index]);
  63006. }
  63007. }
  63008. }
  63009. _this._files = files;
  63010. if (!_this._texture) {
  63011. if (!scene.useDelayedTextureLoading) {
  63012. if (prefiltered) {
  63013. _this._texture = scene.getEngine().createPrefilteredCubeTexture(rootUrl, scene, _this.lodGenerationScale, _this.lodGenerationOffset, onLoad, onError, format, forcedExtension);
  63014. }
  63015. else {
  63016. _this._texture = scene.getEngine().createCubeTexture(rootUrl, scene, files, noMipmap, onLoad, onError, _this._format, forcedExtension);
  63017. }
  63018. }
  63019. else {
  63020. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  63021. }
  63022. }
  63023. else if (onLoad) {
  63024. if (_this._texture.isReady) {
  63025. BABYLON.Tools.SetImmediate(function () { return onLoad(); });
  63026. }
  63027. else {
  63028. _this._texture.onLoadedObservable.add(onLoad);
  63029. }
  63030. }
  63031. return _this;
  63032. }
  63033. Object.defineProperty(CubeTexture.prototype, "boundingBoxSize", {
  63034. get: function () {
  63035. return this._boundingBoxSize;
  63036. },
  63037. /**
  63038. * Gets or sets the size of the bounding box associated with the cube texture
  63039. * When defined, the cubemap will switch to local mode
  63040. * @see https://community.arm.com/graphics/b/blog/posts/reflections-based-on-local-cubemaps-in-unity
  63041. * @example https://www.babylonjs-playground.com/#RNASML
  63042. */
  63043. set: function (value) {
  63044. if (this._boundingBoxSize && this._boundingBoxSize.equals(value)) {
  63045. return;
  63046. }
  63047. this._boundingBoxSize = value;
  63048. var scene = this.getScene();
  63049. if (scene) {
  63050. scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  63051. }
  63052. },
  63053. enumerable: true,
  63054. configurable: true
  63055. });
  63056. Object.defineProperty(CubeTexture.prototype, "rotationY", {
  63057. /**
  63058. * Gets texture matrix rotation angle around Y axis radians.
  63059. */
  63060. get: function () {
  63061. return this._rotationY;
  63062. },
  63063. /**
  63064. * Sets texture matrix rotation angle around Y axis in radians.
  63065. */
  63066. set: function (value) {
  63067. this._rotationY = value;
  63068. this.setReflectionTextureMatrix(BABYLON.Matrix.RotationY(this._rotationY));
  63069. },
  63070. enumerable: true,
  63071. configurable: true
  63072. });
  63073. CubeTexture.CreateFromImages = function (files, scene, noMipmap) {
  63074. var rootUrlKey = "";
  63075. files.forEach(function (url) { return rootUrlKey += url; });
  63076. return new CubeTexture(rootUrlKey, scene, null, noMipmap, files);
  63077. };
  63078. CubeTexture.CreateFromPrefilteredData = function (url, scene, forcedExtension) {
  63079. if (forcedExtension === void 0) { forcedExtension = null; }
  63080. return new CubeTexture(url, scene, null, false, null, null, null, undefined, true, forcedExtension);
  63081. };
  63082. // Methods
  63083. CubeTexture.prototype.delayLoad = function () {
  63084. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  63085. return;
  63086. }
  63087. var scene = this.getScene();
  63088. if (!scene) {
  63089. return;
  63090. }
  63091. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  63092. this._texture = this._getFromCache(this.url, this._noMipmap);
  63093. if (!this._texture) {
  63094. if (this._prefiltered) {
  63095. this._texture = scene.getEngine().createPrefilteredCubeTexture(this.url, scene, this.lodGenerationScale, this.lodGenerationOffset, undefined, undefined, this._format);
  63096. }
  63097. else {
  63098. this._texture = scene.getEngine().createCubeTexture(this.url, scene, this._files, this._noMipmap, undefined, undefined, this._format);
  63099. }
  63100. }
  63101. };
  63102. CubeTexture.prototype.getReflectionTextureMatrix = function () {
  63103. return this._textureMatrix;
  63104. };
  63105. CubeTexture.prototype.setReflectionTextureMatrix = function (value) {
  63106. this._textureMatrix = value;
  63107. };
  63108. CubeTexture.Parse = function (parsedTexture, scene, rootUrl) {
  63109. var texture = BABYLON.SerializationHelper.Parse(function () {
  63110. var prefiltered = false;
  63111. if (parsedTexture.prefiltered) {
  63112. prefiltered = parsedTexture.prefiltered;
  63113. }
  63114. return new CubeTexture(rootUrl + parsedTexture.name, scene, parsedTexture.extensions, false, null, null, null, undefined, prefiltered);
  63115. }, parsedTexture, scene);
  63116. // Local Cubemaps
  63117. if (parsedTexture.boundingBoxPosition) {
  63118. texture.boundingBoxPosition = BABYLON.Vector3.FromArray(parsedTexture.boundingBoxPosition);
  63119. }
  63120. if (parsedTexture.boundingBoxSize) {
  63121. texture.boundingBoxSize = BABYLON.Vector3.FromArray(parsedTexture.boundingBoxSize);
  63122. }
  63123. // Animations
  63124. if (parsedTexture.animations) {
  63125. for (var animationIndex = 0; animationIndex < parsedTexture.animations.length; animationIndex++) {
  63126. var parsedAnimation = parsedTexture.animations[animationIndex];
  63127. texture.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  63128. }
  63129. }
  63130. return texture;
  63131. };
  63132. CubeTexture.prototype.clone = function () {
  63133. var _this = this;
  63134. return BABYLON.SerializationHelper.Clone(function () {
  63135. var scene = _this.getScene();
  63136. if (!scene) {
  63137. return _this;
  63138. }
  63139. return new CubeTexture(_this.url, scene, _this._extensions, _this._noMipmap, _this._files);
  63140. }, this);
  63141. };
  63142. __decorate([
  63143. BABYLON.serialize("rotationY")
  63144. ], CubeTexture.prototype, "_rotationY", void 0);
  63145. return CubeTexture;
  63146. }(BABYLON.BaseTexture));
  63147. BABYLON.CubeTexture = CubeTexture;
  63148. })(BABYLON || (BABYLON = {}));
  63149. //# sourceMappingURL=babylon.cubeTexture.js.map
  63150. var BABYLON;
  63151. (function (BABYLON) {
  63152. var RenderTargetTexture = /** @class */ (function (_super) {
  63153. __extends(RenderTargetTexture, _super);
  63154. /**
  63155. * Instantiate a render target texture. This is mainly to render of screen the scene to for instance apply post processse
  63156. * or used a shadow, depth texture...
  63157. * @param name The friendly name of the texture
  63158. * @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)
  63159. * @param scene The scene the RTT belongs to. The latest created scene will be used if not precised.
  63160. * @param generateMipMaps True if mip maps need to be generated after render.
  63161. * @param doNotChangeAspectRatio True to not change the aspect ratio of the scene in the RTT
  63162. * @param type The type of the buffer in the RTT (int, half float, float...)
  63163. * @param isCube True if a cube texture needs to be created
  63164. * @param samplingMode The sampling mode to be usedwith the render target (Linear, Nearest...)
  63165. * @param generateDepthBuffer True to generate a depth buffer
  63166. * @param generateStencilBuffer True to generate a stencil buffer
  63167. * @param isMulti True if multiple textures need to be created (Draw Buffers)
  63168. */
  63169. function RenderTargetTexture(name, size, scene, generateMipMaps, doNotChangeAspectRatio, type, isCube, samplingMode, generateDepthBuffer, generateStencilBuffer, isMulti) {
  63170. if (doNotChangeAspectRatio === void 0) { doNotChangeAspectRatio = true; }
  63171. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  63172. if (isCube === void 0) { isCube = false; }
  63173. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  63174. if (generateDepthBuffer === void 0) { generateDepthBuffer = true; }
  63175. if (generateStencilBuffer === void 0) { generateStencilBuffer = false; }
  63176. if (isMulti === void 0) { isMulti = false; }
  63177. var _this = _super.call(this, null, scene, !generateMipMaps) || this;
  63178. _this.isCube = isCube;
  63179. /**
  63180. * Use this list to define the list of mesh you want to render.
  63181. */
  63182. _this.renderList = new Array();
  63183. _this.renderParticles = true;
  63184. _this.renderSprites = false;
  63185. _this.coordinatesMode = BABYLON.Texture.PROJECTION_MODE;
  63186. _this.ignoreCameraViewport = false;
  63187. // Events
  63188. /**
  63189. * An event triggered when the texture is unbind.
  63190. */
  63191. _this.onBeforeBindObservable = new BABYLON.Observable();
  63192. /**
  63193. * An event triggered when the texture is unbind.
  63194. */
  63195. _this.onAfterUnbindObservable = new BABYLON.Observable();
  63196. /**
  63197. * An event triggered before rendering the texture
  63198. */
  63199. _this.onBeforeRenderObservable = new BABYLON.Observable();
  63200. /**
  63201. * An event triggered after rendering the texture
  63202. */
  63203. _this.onAfterRenderObservable = new BABYLON.Observable();
  63204. /**
  63205. * An event triggered after the texture clear
  63206. */
  63207. _this.onClearObservable = new BABYLON.Observable();
  63208. _this._currentRefreshId = -1;
  63209. _this._refreshRate = 1;
  63210. _this._samples = 1;
  63211. /**
  63212. * Gets or sets the center of the bounding box associated with the texture (when in cube mode)
  63213. * It must define where the camera used to render the texture is set
  63214. */
  63215. _this.boundingBoxPosition = BABYLON.Vector3.Zero();
  63216. scene = _this.getScene();
  63217. if (!scene) {
  63218. return _this;
  63219. }
  63220. _this._engine = scene.getEngine();
  63221. _this.name = name;
  63222. _this.isRenderTarget = true;
  63223. _this._initialSizeParameter = size;
  63224. _this._processSizeParameter(size);
  63225. _this._resizeObserver = _this.getScene().getEngine().onResizeObservable.add(function () {
  63226. });
  63227. _this._generateMipMaps = generateMipMaps ? true : false;
  63228. _this._doNotChangeAspectRatio = doNotChangeAspectRatio;
  63229. // Rendering groups
  63230. _this._renderingManager = new BABYLON.RenderingManager(scene);
  63231. if (isMulti) {
  63232. return _this;
  63233. }
  63234. _this._renderTargetOptions = {
  63235. generateMipMaps: generateMipMaps,
  63236. type: type,
  63237. samplingMode: samplingMode,
  63238. generateDepthBuffer: generateDepthBuffer,
  63239. generateStencilBuffer: generateStencilBuffer
  63240. };
  63241. if (samplingMode === BABYLON.Texture.NEAREST_SAMPLINGMODE) {
  63242. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  63243. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  63244. }
  63245. if (isCube) {
  63246. _this._texture = scene.getEngine().createRenderTargetCubeTexture(_this.getRenderSize(), _this._renderTargetOptions);
  63247. _this.coordinatesMode = BABYLON.Texture.INVCUBIC_MODE;
  63248. _this._textureMatrix = BABYLON.Matrix.Identity();
  63249. }
  63250. else {
  63251. _this._texture = scene.getEngine().createRenderTargetTexture(_this._size, _this._renderTargetOptions);
  63252. }
  63253. return _this;
  63254. }
  63255. Object.defineProperty(RenderTargetTexture, "REFRESHRATE_RENDER_ONCE", {
  63256. get: function () {
  63257. return RenderTargetTexture._REFRESHRATE_RENDER_ONCE;
  63258. },
  63259. enumerable: true,
  63260. configurable: true
  63261. });
  63262. Object.defineProperty(RenderTargetTexture, "REFRESHRATE_RENDER_ONEVERYFRAME", {
  63263. get: function () {
  63264. return RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYFRAME;
  63265. },
  63266. enumerable: true,
  63267. configurable: true
  63268. });
  63269. Object.defineProperty(RenderTargetTexture, "REFRESHRATE_RENDER_ONEVERYTWOFRAMES", {
  63270. get: function () {
  63271. return RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYTWOFRAMES;
  63272. },
  63273. enumerable: true,
  63274. configurable: true
  63275. });
  63276. Object.defineProperty(RenderTargetTexture.prototype, "onAfterUnbind", {
  63277. set: function (callback) {
  63278. if (this._onAfterUnbindObserver) {
  63279. this.onAfterUnbindObservable.remove(this._onAfterUnbindObserver);
  63280. }
  63281. this._onAfterUnbindObserver = this.onAfterUnbindObservable.add(callback);
  63282. },
  63283. enumerable: true,
  63284. configurable: true
  63285. });
  63286. Object.defineProperty(RenderTargetTexture.prototype, "onBeforeRender", {
  63287. set: function (callback) {
  63288. if (this._onBeforeRenderObserver) {
  63289. this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
  63290. }
  63291. this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
  63292. },
  63293. enumerable: true,
  63294. configurable: true
  63295. });
  63296. Object.defineProperty(RenderTargetTexture.prototype, "onAfterRender", {
  63297. set: function (callback) {
  63298. if (this._onAfterRenderObserver) {
  63299. this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  63300. }
  63301. this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
  63302. },
  63303. enumerable: true,
  63304. configurable: true
  63305. });
  63306. Object.defineProperty(RenderTargetTexture.prototype, "onClear", {
  63307. set: function (callback) {
  63308. if (this._onClearObserver) {
  63309. this.onClearObservable.remove(this._onClearObserver);
  63310. }
  63311. this._onClearObserver = this.onClearObservable.add(callback);
  63312. },
  63313. enumerable: true,
  63314. configurable: true
  63315. });
  63316. Object.defineProperty(RenderTargetTexture.prototype, "renderTargetOptions", {
  63317. get: function () {
  63318. return this._renderTargetOptions;
  63319. },
  63320. enumerable: true,
  63321. configurable: true
  63322. });
  63323. RenderTargetTexture.prototype._onRatioRescale = function () {
  63324. if (this._sizeRatio) {
  63325. this.resize(this._initialSizeParameter);
  63326. }
  63327. };
  63328. Object.defineProperty(RenderTargetTexture.prototype, "boundingBoxSize", {
  63329. get: function () {
  63330. return this._boundingBoxSize;
  63331. },
  63332. /**
  63333. * Gets or sets the size of the bounding box associated with the texture (when in cube mode)
  63334. * When defined, the cubemap will switch to local mode
  63335. * @see https://community.arm.com/graphics/b/blog/posts/reflections-based-on-local-cubemaps-in-unity
  63336. * @example https://www.babylonjs-playground.com/#RNASML
  63337. */
  63338. set: function (value) {
  63339. if (this._boundingBoxSize && this._boundingBoxSize.equals(value)) {
  63340. return;
  63341. }
  63342. this._boundingBoxSize = value;
  63343. var scene = this.getScene();
  63344. if (scene) {
  63345. scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  63346. }
  63347. },
  63348. enumerable: true,
  63349. configurable: true
  63350. });
  63351. /**
  63352. * Creates a depth stencil texture.
  63353. * This is only available in WebGL 2 or with the depth texture extension available.
  63354. * @param comparisonFunction Specifies the comparison function to set on the texture. If 0 or undefined, the texture is not in comparison mode
  63355. * @param bilinearFiltering Specifies whether or not bilinear filtering is enable on the texture
  63356. * @param generateStencil Specifies whether or not a stencil should be allocated in the texture
  63357. */
  63358. RenderTargetTexture.prototype.createDepthStencilTexture = function (comparisonFunction, bilinearFiltering, generateStencil) {
  63359. if (comparisonFunction === void 0) { comparisonFunction = 0; }
  63360. if (bilinearFiltering === void 0) { bilinearFiltering = true; }
  63361. if (generateStencil === void 0) { generateStencil = false; }
  63362. if (!this.getScene()) {
  63363. return;
  63364. }
  63365. var engine = this.getScene().getEngine();
  63366. this.depthStencilTexture = engine.createDepthStencilTexture(this._size, {
  63367. bilinearFiltering: bilinearFiltering,
  63368. comparisonFunction: comparisonFunction,
  63369. generateStencil: generateStencil,
  63370. isCube: this.isCube
  63371. });
  63372. engine.setFrameBufferDepthStencilTexture(this);
  63373. };
  63374. RenderTargetTexture.prototype._processSizeParameter = function (size) {
  63375. if (size.ratio) {
  63376. this._sizeRatio = size.ratio;
  63377. this._size = {
  63378. width: this._bestReflectionRenderTargetDimension(this._engine.getRenderWidth(), this._sizeRatio),
  63379. height: this._bestReflectionRenderTargetDimension(this._engine.getRenderHeight(), this._sizeRatio)
  63380. };
  63381. }
  63382. else {
  63383. this._size = size;
  63384. }
  63385. };
  63386. Object.defineProperty(RenderTargetTexture.prototype, "samples", {
  63387. get: function () {
  63388. return this._samples;
  63389. },
  63390. set: function (value) {
  63391. if (this._samples === value) {
  63392. return;
  63393. }
  63394. var scene = this.getScene();
  63395. if (!scene) {
  63396. return;
  63397. }
  63398. this._samples = scene.getEngine().updateRenderTargetTextureSampleCount(this._texture, value);
  63399. },
  63400. enumerable: true,
  63401. configurable: true
  63402. });
  63403. RenderTargetTexture.prototype.resetRefreshCounter = function () {
  63404. this._currentRefreshId = -1;
  63405. };
  63406. Object.defineProperty(RenderTargetTexture.prototype, "refreshRate", {
  63407. get: function () {
  63408. return this._refreshRate;
  63409. },
  63410. // Use 0 to render just once, 1 to render on every frame, 2 to render every two frames and so on...
  63411. set: function (value) {
  63412. this._refreshRate = value;
  63413. this.resetRefreshCounter();
  63414. },
  63415. enumerable: true,
  63416. configurable: true
  63417. });
  63418. RenderTargetTexture.prototype.addPostProcess = function (postProcess) {
  63419. if (!this._postProcessManager) {
  63420. var scene = this.getScene();
  63421. if (!scene) {
  63422. return;
  63423. }
  63424. this._postProcessManager = new BABYLON.PostProcessManager(scene);
  63425. this._postProcesses = new Array();
  63426. }
  63427. this._postProcesses.push(postProcess);
  63428. this._postProcesses[0].autoClear = false;
  63429. };
  63430. RenderTargetTexture.prototype.clearPostProcesses = function (dispose) {
  63431. if (!this._postProcesses) {
  63432. return;
  63433. }
  63434. if (dispose) {
  63435. for (var _i = 0, _a = this._postProcesses; _i < _a.length; _i++) {
  63436. var postProcess = _a[_i];
  63437. postProcess.dispose();
  63438. }
  63439. }
  63440. this._postProcesses = [];
  63441. };
  63442. RenderTargetTexture.prototype.removePostProcess = function (postProcess) {
  63443. if (!this._postProcesses) {
  63444. return;
  63445. }
  63446. var index = this._postProcesses.indexOf(postProcess);
  63447. if (index === -1) {
  63448. return;
  63449. }
  63450. this._postProcesses.splice(index, 1);
  63451. if (this._postProcesses.length > 0) {
  63452. this._postProcesses[0].autoClear = false;
  63453. }
  63454. };
  63455. RenderTargetTexture.prototype._shouldRender = function () {
  63456. if (this._currentRefreshId === -1) { // At least render once
  63457. this._currentRefreshId = 1;
  63458. return true;
  63459. }
  63460. if (this.refreshRate === this._currentRefreshId) {
  63461. this._currentRefreshId = 1;
  63462. return true;
  63463. }
  63464. this._currentRefreshId++;
  63465. return false;
  63466. };
  63467. RenderTargetTexture.prototype.getRenderSize = function () {
  63468. if (this._size.width) {
  63469. return this._size.width;
  63470. }
  63471. return this._size;
  63472. };
  63473. RenderTargetTexture.prototype.getRenderWidth = function () {
  63474. if (this._size.width) {
  63475. return this._size.width;
  63476. }
  63477. return this._size;
  63478. };
  63479. RenderTargetTexture.prototype.getRenderHeight = function () {
  63480. if (this._size.width) {
  63481. return this._size.height;
  63482. }
  63483. return this._size;
  63484. };
  63485. Object.defineProperty(RenderTargetTexture.prototype, "canRescale", {
  63486. get: function () {
  63487. return true;
  63488. },
  63489. enumerable: true,
  63490. configurable: true
  63491. });
  63492. RenderTargetTexture.prototype.scale = function (ratio) {
  63493. var newSize = this.getRenderSize() * ratio;
  63494. this.resize(newSize);
  63495. };
  63496. RenderTargetTexture.prototype.getReflectionTextureMatrix = function () {
  63497. if (this.isCube) {
  63498. return this._textureMatrix;
  63499. }
  63500. return _super.prototype.getReflectionTextureMatrix.call(this);
  63501. };
  63502. RenderTargetTexture.prototype.resize = function (size) {
  63503. this.releaseInternalTexture();
  63504. var scene = this.getScene();
  63505. if (!scene) {
  63506. return;
  63507. }
  63508. this._processSizeParameter(size);
  63509. if (this.isCube) {
  63510. this._texture = scene.getEngine().createRenderTargetCubeTexture(this.getRenderSize(), this._renderTargetOptions);
  63511. }
  63512. else {
  63513. this._texture = scene.getEngine().createRenderTargetTexture(this._size, this._renderTargetOptions);
  63514. }
  63515. };
  63516. RenderTargetTexture.prototype.render = function (useCameraPostProcess, dumpForDebug) {
  63517. if (useCameraPostProcess === void 0) { useCameraPostProcess = false; }
  63518. if (dumpForDebug === void 0) { dumpForDebug = false; }
  63519. var scene = this.getScene();
  63520. if (!scene) {
  63521. return;
  63522. }
  63523. var engine = scene.getEngine();
  63524. if (this.useCameraPostProcesses !== undefined) {
  63525. useCameraPostProcess = this.useCameraPostProcesses;
  63526. }
  63527. if (this._waitingRenderList) {
  63528. this.renderList = [];
  63529. for (var index = 0; index < this._waitingRenderList.length; index++) {
  63530. var id = this._waitingRenderList[index];
  63531. var mesh_1 = scene.getMeshByID(id);
  63532. if (mesh_1) {
  63533. this.renderList.push(mesh_1);
  63534. }
  63535. }
  63536. delete this._waitingRenderList;
  63537. }
  63538. // Is predicate defined?
  63539. if (this.renderListPredicate) {
  63540. if (this.renderList) {
  63541. this.renderList.splice(0); // Clear previous renderList
  63542. }
  63543. else {
  63544. this.renderList = [];
  63545. }
  63546. var scene = this.getScene();
  63547. if (!scene) {
  63548. return;
  63549. }
  63550. var sceneMeshes = scene.meshes;
  63551. for (var index = 0; index < sceneMeshes.length; index++) {
  63552. var mesh = sceneMeshes[index];
  63553. if (this.renderListPredicate(mesh)) {
  63554. this.renderList.push(mesh);
  63555. }
  63556. }
  63557. }
  63558. this.onBeforeBindObservable.notifyObservers(this);
  63559. // Set custom projection.
  63560. // Needs to be before binding to prevent changing the aspect ratio.
  63561. var camera;
  63562. if (this.activeCamera) {
  63563. camera = this.activeCamera;
  63564. engine.setViewport(this.activeCamera.viewport, this.getRenderWidth(), this.getRenderHeight());
  63565. if (this.activeCamera !== scene.activeCamera) {
  63566. scene.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix(true));
  63567. }
  63568. }
  63569. else {
  63570. camera = scene.activeCamera;
  63571. if (camera) {
  63572. engine.setViewport(camera.viewport, this.getRenderWidth(), this.getRenderHeight());
  63573. }
  63574. }
  63575. // Prepare renderingManager
  63576. this._renderingManager.reset();
  63577. var currentRenderList = this.renderList ? this.renderList : scene.getActiveMeshes().data;
  63578. var currentRenderListLength = this.renderList ? this.renderList.length : scene.getActiveMeshes().length;
  63579. var sceneRenderId = scene.getRenderId();
  63580. for (var meshIndex = 0; meshIndex < currentRenderListLength; meshIndex++) {
  63581. var mesh = currentRenderList[meshIndex];
  63582. if (mesh) {
  63583. if (!mesh.isReady(this.refreshRate === 0)) {
  63584. this.resetRefreshCounter();
  63585. continue;
  63586. }
  63587. mesh._preActivateForIntermediateRendering(sceneRenderId);
  63588. var isMasked = void 0;
  63589. if (!this.renderList && camera) {
  63590. isMasked = ((mesh.layerMask & camera.layerMask) === 0);
  63591. }
  63592. else {
  63593. isMasked = false;
  63594. }
  63595. if (mesh.isEnabled() && mesh.isVisible && mesh.subMeshes && !isMasked) {
  63596. mesh._activate(sceneRenderId);
  63597. for (var subIndex = 0; subIndex < mesh.subMeshes.length; subIndex++) {
  63598. var subMesh = mesh.subMeshes[subIndex];
  63599. scene._activeIndices.addCount(subMesh.indexCount, false);
  63600. this._renderingManager.dispatch(subMesh, mesh);
  63601. }
  63602. }
  63603. }
  63604. }
  63605. for (var particleIndex = 0; particleIndex < scene.particleSystems.length; particleIndex++) {
  63606. var particleSystem = scene.particleSystems[particleIndex];
  63607. var emitter = particleSystem.emitter;
  63608. if (!particleSystem.isStarted() || !emitter || !emitter.position || !emitter.isEnabled()) {
  63609. continue;
  63610. }
  63611. if (currentRenderList.indexOf(emitter) >= 0) {
  63612. this._renderingManager.dispatchParticles(particleSystem);
  63613. }
  63614. }
  63615. if (this.isCube) {
  63616. for (var face = 0; face < 6; face++) {
  63617. this.renderToTarget(face, currentRenderList, currentRenderListLength, useCameraPostProcess, dumpForDebug);
  63618. scene.incrementRenderId();
  63619. scene.resetCachedMaterial();
  63620. }
  63621. }
  63622. else {
  63623. this.renderToTarget(0, currentRenderList, currentRenderListLength, useCameraPostProcess, dumpForDebug);
  63624. }
  63625. this.onAfterUnbindObservable.notifyObservers(this);
  63626. if (scene.activeCamera) {
  63627. if (this.activeCamera && this.activeCamera !== scene.activeCamera) {
  63628. scene.setTransformMatrix(scene.activeCamera.getViewMatrix(), scene.activeCamera.getProjectionMatrix(true));
  63629. }
  63630. engine.setViewport(scene.activeCamera.viewport);
  63631. }
  63632. scene.resetCachedMaterial();
  63633. };
  63634. RenderTargetTexture.prototype._bestReflectionRenderTargetDimension = function (renderDimension, scale) {
  63635. var minimum = 128;
  63636. var x = renderDimension * scale;
  63637. var curved = BABYLON.Tools.NearestPOT(x + (minimum * minimum / (minimum + x)));
  63638. // Ensure we don't exceed the render dimension (while staying POT)
  63639. return Math.min(BABYLON.Tools.FloorPOT(renderDimension), curved);
  63640. };
  63641. RenderTargetTexture.prototype.unbindFrameBuffer = function (engine, faceIndex) {
  63642. var _this = this;
  63643. if (!this._texture) {
  63644. return;
  63645. }
  63646. engine.unBindFramebuffer(this._texture, this.isCube, function () {
  63647. _this.onAfterRenderObservable.notifyObservers(faceIndex);
  63648. });
  63649. };
  63650. RenderTargetTexture.prototype.renderToTarget = function (faceIndex, currentRenderList, currentRenderListLength, useCameraPostProcess, dumpForDebug) {
  63651. var scene = this.getScene();
  63652. if (!scene) {
  63653. return;
  63654. }
  63655. var engine = scene.getEngine();
  63656. if (!this._texture) {
  63657. return;
  63658. }
  63659. // Bind
  63660. if (this._postProcessManager) {
  63661. this._postProcessManager._prepareFrame(this._texture, this._postProcesses);
  63662. }
  63663. else if (!useCameraPostProcess || !scene.postProcessManager._prepareFrame(this._texture)) {
  63664. if (this._texture) {
  63665. engine.bindFramebuffer(this._texture, this.isCube ? faceIndex : undefined, undefined, undefined, this.ignoreCameraViewport, this.depthStencilTexture ? this.depthStencilTexture : undefined);
  63666. }
  63667. }
  63668. this.onBeforeRenderObservable.notifyObservers(faceIndex);
  63669. // Clear
  63670. if (this.onClearObservable.hasObservers()) {
  63671. this.onClearObservable.notifyObservers(engine);
  63672. }
  63673. else {
  63674. engine.clear(this.clearColor || scene.clearColor, true, true, true);
  63675. }
  63676. if (!this._doNotChangeAspectRatio) {
  63677. scene.updateTransformMatrix(true);
  63678. }
  63679. // Render
  63680. this._renderingManager.render(this.customRenderFunction, currentRenderList, this.renderParticles, this.renderSprites);
  63681. if (this._postProcessManager) {
  63682. this._postProcessManager._finalizeFrame(false, this._texture, faceIndex, this._postProcesses, this.ignoreCameraViewport);
  63683. }
  63684. else if (useCameraPostProcess) {
  63685. scene.postProcessManager._finalizeFrame(false, this._texture, faceIndex);
  63686. }
  63687. if (!this._doNotChangeAspectRatio) {
  63688. scene.updateTransformMatrix(true);
  63689. }
  63690. // Dump ?
  63691. if (dumpForDebug) {
  63692. BABYLON.Tools.DumpFramebuffer(this.getRenderWidth(), this.getRenderHeight(), engine);
  63693. }
  63694. // Unbind
  63695. if (!this.isCube || faceIndex === 5) {
  63696. if (this.isCube) {
  63697. if (faceIndex === 5) {
  63698. engine.generateMipMapsForCubemap(this._texture);
  63699. }
  63700. }
  63701. this.unbindFrameBuffer(engine, faceIndex);
  63702. }
  63703. else {
  63704. this.onAfterRenderObservable.notifyObservers(faceIndex);
  63705. }
  63706. };
  63707. /**
  63708. * Overrides the default sort function applied in the renderging group to prepare the meshes.
  63709. * This allowed control for front to back rendering or reversly depending of the special needs.
  63710. *
  63711. * @param renderingGroupId The rendering group id corresponding to its index
  63712. * @param opaqueSortCompareFn The opaque queue comparison function use to sort.
  63713. * @param alphaTestSortCompareFn The alpha test queue comparison function use to sort.
  63714. * @param transparentSortCompareFn The transparent queue comparison function use to sort.
  63715. */
  63716. RenderTargetTexture.prototype.setRenderingOrder = function (renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn) {
  63717. if (opaqueSortCompareFn === void 0) { opaqueSortCompareFn = null; }
  63718. if (alphaTestSortCompareFn === void 0) { alphaTestSortCompareFn = null; }
  63719. if (transparentSortCompareFn === void 0) { transparentSortCompareFn = null; }
  63720. this._renderingManager.setRenderingOrder(renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn);
  63721. };
  63722. /**
  63723. * Specifies whether or not the stencil and depth buffer are cleared between two rendering groups.
  63724. *
  63725. * @param renderingGroupId The rendering group id corresponding to its index
  63726. * @param autoClearDepthStencil Automatically clears depth and stencil between groups if true.
  63727. */
  63728. RenderTargetTexture.prototype.setRenderingAutoClearDepthStencil = function (renderingGroupId, autoClearDepthStencil) {
  63729. this._renderingManager.setRenderingAutoClearDepthStencil(renderingGroupId, autoClearDepthStencil);
  63730. };
  63731. RenderTargetTexture.prototype.clone = function () {
  63732. var textureSize = this.getSize();
  63733. 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);
  63734. // Base texture
  63735. newTexture.hasAlpha = this.hasAlpha;
  63736. newTexture.level = this.level;
  63737. // RenderTarget Texture
  63738. newTexture.coordinatesMode = this.coordinatesMode;
  63739. if (this.renderList) {
  63740. newTexture.renderList = this.renderList.slice(0);
  63741. }
  63742. return newTexture;
  63743. };
  63744. RenderTargetTexture.prototype.serialize = function () {
  63745. if (!this.name) {
  63746. return null;
  63747. }
  63748. var serializationObject = _super.prototype.serialize.call(this);
  63749. serializationObject.renderTargetSize = this.getRenderSize();
  63750. serializationObject.renderList = [];
  63751. if (this.renderList) {
  63752. for (var index = 0; index < this.renderList.length; index++) {
  63753. serializationObject.renderList.push(this.renderList[index].id);
  63754. }
  63755. }
  63756. return serializationObject;
  63757. };
  63758. // This will remove the attached framebuffer objects. The texture will not be able to be used as render target anymore
  63759. RenderTargetTexture.prototype.disposeFramebufferObjects = function () {
  63760. var objBuffer = this.getInternalTexture();
  63761. var scene = this.getScene();
  63762. if (objBuffer && scene) {
  63763. scene.getEngine()._releaseFramebufferObjects(objBuffer);
  63764. }
  63765. };
  63766. RenderTargetTexture.prototype.dispose = function () {
  63767. if (this._postProcessManager) {
  63768. this._postProcessManager.dispose();
  63769. this._postProcessManager = null;
  63770. }
  63771. this.clearPostProcesses(true);
  63772. if (this._resizeObserver) {
  63773. this.getScene().getEngine().onResizeObservable.remove(this._resizeObserver);
  63774. this._resizeObserver = null;
  63775. }
  63776. this.renderList = null;
  63777. // Remove from custom render targets
  63778. var scene = this.getScene();
  63779. if (!scene) {
  63780. return;
  63781. }
  63782. var index = scene.customRenderTargets.indexOf(this);
  63783. if (index >= 0) {
  63784. scene.customRenderTargets.splice(index, 1);
  63785. }
  63786. for (var _i = 0, _a = scene.cameras; _i < _a.length; _i++) {
  63787. var camera = _a[_i];
  63788. index = camera.customRenderTargets.indexOf(this);
  63789. if (index >= 0) {
  63790. camera.customRenderTargets.splice(index, 1);
  63791. }
  63792. }
  63793. _super.prototype.dispose.call(this);
  63794. };
  63795. RenderTargetTexture.prototype._rebuild = function () {
  63796. if (this.refreshRate === RenderTargetTexture.REFRESHRATE_RENDER_ONCE) {
  63797. this.refreshRate = RenderTargetTexture.REFRESHRATE_RENDER_ONCE;
  63798. }
  63799. if (this._postProcessManager) {
  63800. this._postProcessManager._rebuild();
  63801. }
  63802. };
  63803. /**
  63804. * Clear the info related to rendering groups preventing retention point in material dispose.
  63805. */
  63806. RenderTargetTexture.prototype.freeRenderingGroups = function () {
  63807. if (this._renderingManager) {
  63808. this._renderingManager.freeRenderingGroups();
  63809. }
  63810. };
  63811. RenderTargetTexture._REFRESHRATE_RENDER_ONCE = 0;
  63812. RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYFRAME = 1;
  63813. RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYTWOFRAMES = 2;
  63814. return RenderTargetTexture;
  63815. }(BABYLON.Texture));
  63816. BABYLON.RenderTargetTexture = RenderTargetTexture;
  63817. })(BABYLON || (BABYLON = {}));
  63818. //# sourceMappingURL=babylon.renderTargetTexture.js.map
  63819. var BABYLON;
  63820. (function (BABYLON) {
  63821. ;
  63822. var MultiRenderTarget = /** @class */ (function (_super) {
  63823. __extends(MultiRenderTarget, _super);
  63824. function MultiRenderTarget(name, size, count, scene, options) {
  63825. var _this = this;
  63826. var generateMipMaps = options && options.generateMipMaps ? options.generateMipMaps : false;
  63827. var generateDepthTexture = options && options.generateDepthTexture ? options.generateDepthTexture : false;
  63828. var doNotChangeAspectRatio = !options || options.doNotChangeAspectRatio === undefined ? true : options.doNotChangeAspectRatio;
  63829. _this = _super.call(this, name, size, scene, generateMipMaps, doNotChangeAspectRatio) || this;
  63830. _this._engine = scene.getEngine();
  63831. if (!_this.isSupported) {
  63832. _this.dispose();
  63833. return;
  63834. }
  63835. var types = [];
  63836. var samplingModes = [];
  63837. for (var i = 0; i < count; i++) {
  63838. if (options && options.types && options.types[i] !== undefined) {
  63839. types.push(options.types[i]);
  63840. }
  63841. else {
  63842. types.push(options && options.defaultType ? options.defaultType : BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  63843. }
  63844. if (options && options.samplingModes && options.samplingModes[i] !== undefined) {
  63845. samplingModes.push(options.samplingModes[i]);
  63846. }
  63847. else {
  63848. samplingModes.push(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  63849. }
  63850. }
  63851. var generateDepthBuffer = !options || options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  63852. var generateStencilBuffer = !options || options.generateStencilBuffer === undefined ? false : options.generateStencilBuffer;
  63853. _this._size = size;
  63854. _this._multiRenderTargetOptions = {
  63855. samplingModes: samplingModes,
  63856. generateMipMaps: generateMipMaps,
  63857. generateDepthBuffer: generateDepthBuffer,
  63858. generateStencilBuffer: generateStencilBuffer,
  63859. generateDepthTexture: generateDepthTexture,
  63860. types: types,
  63861. textureCount: count
  63862. };
  63863. _this._createInternalTextures();
  63864. _this._createTextures();
  63865. return _this;
  63866. }
  63867. Object.defineProperty(MultiRenderTarget.prototype, "isSupported", {
  63868. get: function () {
  63869. return this._engine.webGLVersion > 1 || this._engine.getCaps().drawBuffersExtension;
  63870. },
  63871. enumerable: true,
  63872. configurable: true
  63873. });
  63874. Object.defineProperty(MultiRenderTarget.prototype, "textures", {
  63875. get: function () {
  63876. return this._textures;
  63877. },
  63878. enumerable: true,
  63879. configurable: true
  63880. });
  63881. Object.defineProperty(MultiRenderTarget.prototype, "depthTexture", {
  63882. get: function () {
  63883. return this._textures[this._textures.length - 1];
  63884. },
  63885. enumerable: true,
  63886. configurable: true
  63887. });
  63888. Object.defineProperty(MultiRenderTarget.prototype, "wrapU", {
  63889. set: function (wrap) {
  63890. if (this._textures) {
  63891. for (var i = 0; i < this._textures.length; i++) {
  63892. this._textures[i].wrapU = wrap;
  63893. }
  63894. }
  63895. },
  63896. enumerable: true,
  63897. configurable: true
  63898. });
  63899. Object.defineProperty(MultiRenderTarget.prototype, "wrapV", {
  63900. set: function (wrap) {
  63901. if (this._textures) {
  63902. for (var i = 0; i < this._textures.length; i++) {
  63903. this._textures[i].wrapV = wrap;
  63904. }
  63905. }
  63906. },
  63907. enumerable: true,
  63908. configurable: true
  63909. });
  63910. MultiRenderTarget.prototype._rebuild = function () {
  63911. this.releaseInternalTextures();
  63912. this._createInternalTextures();
  63913. for (var i = 0; i < this._internalTextures.length; i++) {
  63914. var texture = this._textures[i];
  63915. texture._texture = this._internalTextures[i];
  63916. }
  63917. // Keeps references to frame buffer and stencil/depth buffer
  63918. this._texture = this._internalTextures[0];
  63919. };
  63920. MultiRenderTarget.prototype._createInternalTextures = function () {
  63921. this._internalTextures = this._engine.createMultipleRenderTarget(this._size, this._multiRenderTargetOptions);
  63922. };
  63923. MultiRenderTarget.prototype._createTextures = function () {
  63924. this._textures = [];
  63925. for (var i = 0; i < this._internalTextures.length; i++) {
  63926. var texture = new BABYLON.Texture(null, this.getScene());
  63927. texture._texture = this._internalTextures[i];
  63928. this._textures.push(texture);
  63929. }
  63930. // Keeps references to frame buffer and stencil/depth buffer
  63931. this._texture = this._internalTextures[0];
  63932. };
  63933. Object.defineProperty(MultiRenderTarget.prototype, "samples", {
  63934. get: function () {
  63935. return this._samples;
  63936. },
  63937. set: function (value) {
  63938. if (this._samples === value) {
  63939. return;
  63940. }
  63941. this._samples = this._engine.updateMultipleRenderTargetTextureSampleCount(this._internalTextures, value);
  63942. },
  63943. enumerable: true,
  63944. configurable: true
  63945. });
  63946. MultiRenderTarget.prototype.resize = function (size) {
  63947. this.releaseInternalTextures();
  63948. this._internalTextures = this._engine.createMultipleRenderTarget(size, this._multiRenderTargetOptions);
  63949. this._createInternalTextures();
  63950. };
  63951. MultiRenderTarget.prototype.unbindFrameBuffer = function (engine, faceIndex) {
  63952. var _this = this;
  63953. engine.unBindMultiColorAttachmentFramebuffer(this._internalTextures, this.isCube, function () {
  63954. _this.onAfterRenderObservable.notifyObservers(faceIndex);
  63955. });
  63956. };
  63957. MultiRenderTarget.prototype.dispose = function () {
  63958. this.releaseInternalTextures();
  63959. _super.prototype.dispose.call(this);
  63960. };
  63961. MultiRenderTarget.prototype.releaseInternalTextures = function () {
  63962. if (!this._internalTextures) {
  63963. return;
  63964. }
  63965. for (var i = this._internalTextures.length - 1; i >= 0; i--) {
  63966. if (this._internalTextures[i] !== undefined) {
  63967. this._internalTextures[i].dispose();
  63968. this._internalTextures.splice(i, 1);
  63969. }
  63970. }
  63971. };
  63972. return MultiRenderTarget;
  63973. }(BABYLON.RenderTargetTexture));
  63974. BABYLON.MultiRenderTarget = MultiRenderTarget;
  63975. })(BABYLON || (BABYLON = {}));
  63976. //# sourceMappingURL=babylon.multiRenderTarget.js.map
  63977. var BABYLON;
  63978. (function (BABYLON) {
  63979. var MirrorTexture = /** @class */ (function (_super) {
  63980. __extends(MirrorTexture, _super);
  63981. function MirrorTexture(name, size, scene, generateMipMaps, type, samplingMode, generateDepthBuffer) {
  63982. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  63983. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  63984. if (generateDepthBuffer === void 0) { generateDepthBuffer = true; }
  63985. var _this = _super.call(this, name, size, scene, generateMipMaps, true, type, false, samplingMode, generateDepthBuffer) || this;
  63986. _this.scene = scene;
  63987. _this.mirrorPlane = new BABYLON.Plane(0, 1, 0, 1);
  63988. _this._transformMatrix = BABYLON.Matrix.Zero();
  63989. _this._mirrorMatrix = BABYLON.Matrix.Zero();
  63990. _this._adaptiveBlurKernel = 0;
  63991. _this._blurKernelX = 0;
  63992. _this._blurKernelY = 0;
  63993. _this._blurRatio = 1.0;
  63994. _this.ignoreCameraViewport = true;
  63995. _this._updateGammaSpace();
  63996. _this._imageProcessingConfigChangeObserver = scene.imageProcessingConfiguration.onUpdateParameters.add(function () {
  63997. _this._updateGammaSpace;
  63998. });
  63999. _this.onBeforeRenderObservable.add(function () {
  64000. BABYLON.Matrix.ReflectionToRef(_this.mirrorPlane, _this._mirrorMatrix);
  64001. _this._savedViewMatrix = scene.getViewMatrix();
  64002. _this._mirrorMatrix.multiplyToRef(_this._savedViewMatrix, _this._transformMatrix);
  64003. scene.setTransformMatrix(_this._transformMatrix, scene.getProjectionMatrix());
  64004. scene.clipPlane = _this.mirrorPlane;
  64005. scene.getEngine().cullBackFaces = false;
  64006. scene._mirroredCameraPosition = BABYLON.Vector3.TransformCoordinates(scene.activeCamera.globalPosition, _this._mirrorMatrix);
  64007. });
  64008. _this.onAfterRenderObservable.add(function () {
  64009. scene.setTransformMatrix(_this._savedViewMatrix, scene.getProjectionMatrix());
  64010. scene.getEngine().cullBackFaces = true;
  64011. scene._mirroredCameraPosition = null;
  64012. delete scene.clipPlane;
  64013. });
  64014. return _this;
  64015. }
  64016. Object.defineProperty(MirrorTexture.prototype, "blurRatio", {
  64017. get: function () {
  64018. return this._blurRatio;
  64019. },
  64020. set: function (value) {
  64021. if (this._blurRatio === value) {
  64022. return;
  64023. }
  64024. this._blurRatio = value;
  64025. this._preparePostProcesses();
  64026. },
  64027. enumerable: true,
  64028. configurable: true
  64029. });
  64030. Object.defineProperty(MirrorTexture.prototype, "adaptiveBlurKernel", {
  64031. set: function (value) {
  64032. this._adaptiveBlurKernel = value;
  64033. this._autoComputeBlurKernel();
  64034. },
  64035. enumerable: true,
  64036. configurable: true
  64037. });
  64038. Object.defineProperty(MirrorTexture.prototype, "blurKernel", {
  64039. set: function (value) {
  64040. this.blurKernelX = value;
  64041. this.blurKernelY = value;
  64042. },
  64043. enumerable: true,
  64044. configurable: true
  64045. });
  64046. Object.defineProperty(MirrorTexture.prototype, "blurKernelX", {
  64047. get: function () {
  64048. return this._blurKernelX;
  64049. },
  64050. set: function (value) {
  64051. if (this._blurKernelX === value) {
  64052. return;
  64053. }
  64054. this._blurKernelX = value;
  64055. this._preparePostProcesses();
  64056. },
  64057. enumerable: true,
  64058. configurable: true
  64059. });
  64060. Object.defineProperty(MirrorTexture.prototype, "blurKernelY", {
  64061. get: function () {
  64062. return this._blurKernelY;
  64063. },
  64064. set: function (value) {
  64065. if (this._blurKernelY === value) {
  64066. return;
  64067. }
  64068. this._blurKernelY = value;
  64069. this._preparePostProcesses();
  64070. },
  64071. enumerable: true,
  64072. configurable: true
  64073. });
  64074. MirrorTexture.prototype._autoComputeBlurKernel = function () {
  64075. var engine = this.getScene().getEngine();
  64076. var dw = this.getRenderWidth() / engine.getRenderWidth();
  64077. var dh = this.getRenderHeight() / engine.getRenderHeight();
  64078. this.blurKernelX = this._adaptiveBlurKernel * dw;
  64079. this.blurKernelY = this._adaptiveBlurKernel * dh;
  64080. };
  64081. MirrorTexture.prototype._onRatioRescale = function () {
  64082. if (this._sizeRatio) {
  64083. this.resize(this._initialSizeParameter);
  64084. if (!this._adaptiveBlurKernel) {
  64085. this._preparePostProcesses();
  64086. }
  64087. }
  64088. if (this._adaptiveBlurKernel) {
  64089. this._autoComputeBlurKernel();
  64090. }
  64091. };
  64092. MirrorTexture.prototype._updateGammaSpace = function () {
  64093. this.gammaSpace = !this.scene.imageProcessingConfiguration.isEnabled || !this.scene.imageProcessingConfiguration.applyByPostProcess;
  64094. };
  64095. MirrorTexture.prototype._preparePostProcesses = function () {
  64096. this.clearPostProcesses(true);
  64097. if (this._blurKernelX && this._blurKernelY) {
  64098. var engine = this.getScene().getEngine();
  64099. var textureType = engine.getCaps().textureFloatRender ? BABYLON.Engine.TEXTURETYPE_FLOAT : BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  64100. 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);
  64101. this._blurX.autoClear = false;
  64102. if (this._blurRatio === 1 && this.samples < 2 && this._texture) {
  64103. this._blurX.inputTexture = this._texture;
  64104. }
  64105. else {
  64106. this._blurX.alwaysForcePOT = true;
  64107. }
  64108. 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);
  64109. this._blurY.autoClear = false;
  64110. this._blurY.alwaysForcePOT = this._blurRatio !== 1;
  64111. this.addPostProcess(this._blurX);
  64112. this.addPostProcess(this._blurY);
  64113. }
  64114. else {
  64115. if (this._blurY) {
  64116. this.removePostProcess(this._blurY);
  64117. this._blurY.dispose();
  64118. this._blurY = null;
  64119. }
  64120. if (this._blurX) {
  64121. this.removePostProcess(this._blurX);
  64122. this._blurX.dispose();
  64123. this._blurX = null;
  64124. }
  64125. }
  64126. };
  64127. MirrorTexture.prototype.clone = function () {
  64128. var scene = this.getScene();
  64129. if (!scene) {
  64130. return this;
  64131. }
  64132. var textureSize = this.getSize();
  64133. var newTexture = new MirrorTexture(this.name, textureSize.width, scene, this._renderTargetOptions.generateMipMaps, this._renderTargetOptions.type, this._renderTargetOptions.samplingMode, this._renderTargetOptions.generateDepthBuffer);
  64134. // Base texture
  64135. newTexture.hasAlpha = this.hasAlpha;
  64136. newTexture.level = this.level;
  64137. // Mirror Texture
  64138. newTexture.mirrorPlane = this.mirrorPlane.clone();
  64139. if (this.renderList) {
  64140. newTexture.renderList = this.renderList.slice(0);
  64141. }
  64142. return newTexture;
  64143. };
  64144. MirrorTexture.prototype.serialize = function () {
  64145. if (!this.name) {
  64146. return null;
  64147. }
  64148. var serializationObject = _super.prototype.serialize.call(this);
  64149. serializationObject.mirrorPlane = this.mirrorPlane.asArray();
  64150. return serializationObject;
  64151. };
  64152. MirrorTexture.prototype.dispose = function () {
  64153. _super.prototype.dispose.call(this);
  64154. this.scene.imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingConfigChangeObserver);
  64155. };
  64156. return MirrorTexture;
  64157. }(BABYLON.RenderTargetTexture));
  64158. BABYLON.MirrorTexture = MirrorTexture;
  64159. })(BABYLON || (BABYLON = {}));
  64160. //# sourceMappingURL=babylon.mirrorTexture.js.map
  64161. var BABYLON;
  64162. (function (BABYLON) {
  64163. /**
  64164. * Creates a refraction texture used by refraction channel of the standard material.
  64165. * @param name the texture name
  64166. * @param size size of the underlying texture
  64167. * @param scene root scene
  64168. */
  64169. var RefractionTexture = /** @class */ (function (_super) {
  64170. __extends(RefractionTexture, _super);
  64171. function RefractionTexture(name, size, scene, generateMipMaps) {
  64172. var _this = _super.call(this, name, size, scene, generateMipMaps, true) || this;
  64173. _this.refractionPlane = new BABYLON.Plane(0, 1, 0, 1);
  64174. _this.depth = 2.0;
  64175. _this.onBeforeRenderObservable.add(function () {
  64176. scene.clipPlane = _this.refractionPlane;
  64177. });
  64178. _this.onAfterRenderObservable.add(function () {
  64179. delete scene.clipPlane;
  64180. });
  64181. return _this;
  64182. }
  64183. RefractionTexture.prototype.clone = function () {
  64184. var scene = this.getScene();
  64185. if (!scene) {
  64186. return this;
  64187. }
  64188. var textureSize = this.getSize();
  64189. var newTexture = new RefractionTexture(this.name, textureSize.width, scene, this._generateMipMaps);
  64190. // Base texture
  64191. newTexture.hasAlpha = this.hasAlpha;
  64192. newTexture.level = this.level;
  64193. // Refraction Texture
  64194. newTexture.refractionPlane = this.refractionPlane.clone();
  64195. if (this.renderList) {
  64196. newTexture.renderList = this.renderList.slice(0);
  64197. }
  64198. newTexture.depth = this.depth;
  64199. return newTexture;
  64200. };
  64201. RefractionTexture.prototype.serialize = function () {
  64202. if (!this.name) {
  64203. return null;
  64204. }
  64205. var serializationObject = _super.prototype.serialize.call(this);
  64206. serializationObject.mirrorPlane = this.refractionPlane.asArray();
  64207. serializationObject.depth = this.depth;
  64208. return serializationObject;
  64209. };
  64210. return RefractionTexture;
  64211. }(BABYLON.RenderTargetTexture));
  64212. BABYLON.RefractionTexture = RefractionTexture;
  64213. })(BABYLON || (BABYLON = {}));
  64214. //# sourceMappingURL=babylon.refractionTexture.js.map
  64215. var BABYLON;
  64216. (function (BABYLON) {
  64217. /**
  64218. * A class extending {BABYLON.Texture} allowing drawing on a texture
  64219. * @see http://doc.babylonjs.com/how_to/dynamictexture
  64220. */
  64221. var DynamicTexture = /** @class */ (function (_super) {
  64222. __extends(DynamicTexture, _super);
  64223. /**
  64224. * Creates a {BABYLON.DynamicTexture}
  64225. * @param name defines the name of the texture
  64226. * @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
  64227. * @param scene defines the scene where you want the texture
  64228. * @param generateMipMaps defines the use of MinMaps or not (default is false)
  64229. * @param samplingMode defines the sampling mode to use (default is BABYLON.Texture.TRILINEAR_SAMPLINGMODE)
  64230. * @param format defines the texture format to use (default is BABYLON.Engine.TEXTUREFORMAT_RGBA)
  64231. */
  64232. function DynamicTexture(name, options, scene, generateMipMaps, samplingMode, format) {
  64233. if (scene === void 0) { scene = null; }
  64234. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  64235. if (format === void 0) { format = BABYLON.Engine.TEXTUREFORMAT_RGBA; }
  64236. var _this = _super.call(this, null, scene, !generateMipMaps, undefined, samplingMode, undefined, undefined, undefined, undefined, format) || this;
  64237. _this.name = name;
  64238. _this._engine = _this.getScene().getEngine();
  64239. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  64240. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  64241. _this._generateMipMaps = generateMipMaps;
  64242. if (options.getContext) {
  64243. _this._canvas = options;
  64244. _this._texture = _this._engine.createDynamicTexture(options.width, options.height, generateMipMaps, samplingMode);
  64245. }
  64246. else {
  64247. _this._canvas = document.createElement("canvas");
  64248. if (options.width || options.width === 0) {
  64249. _this._texture = _this._engine.createDynamicTexture(options.width, options.height, generateMipMaps, samplingMode);
  64250. }
  64251. else {
  64252. _this._texture = _this._engine.createDynamicTexture(options, options, generateMipMaps, samplingMode);
  64253. }
  64254. }
  64255. var textureSize = _this.getSize();
  64256. _this._canvas.width = textureSize.width;
  64257. _this._canvas.height = textureSize.height;
  64258. _this._context = _this._canvas.getContext("2d");
  64259. return _this;
  64260. }
  64261. Object.defineProperty(DynamicTexture.prototype, "canRescale", {
  64262. /**
  64263. * Gets the current state of canRescale
  64264. */
  64265. get: function () {
  64266. return true;
  64267. },
  64268. enumerable: true,
  64269. configurable: true
  64270. });
  64271. DynamicTexture.prototype._recreate = function (textureSize) {
  64272. this._canvas.width = textureSize.width;
  64273. this._canvas.height = textureSize.height;
  64274. this.releaseInternalTexture();
  64275. this._texture = this._engine.createDynamicTexture(textureSize.width, textureSize.height, this._generateMipMaps, this._samplingMode);
  64276. };
  64277. /**
  64278. * Scales the texture
  64279. * @param ratio the scale factor to apply to both width and height
  64280. */
  64281. DynamicTexture.prototype.scale = function (ratio) {
  64282. var textureSize = this.getSize();
  64283. textureSize.width *= ratio;
  64284. textureSize.height *= ratio;
  64285. this._recreate(textureSize);
  64286. };
  64287. /**
  64288. * Resizes the texture
  64289. * @param width the new width
  64290. * @param height the new height
  64291. */
  64292. DynamicTexture.prototype.scaleTo = function (width, height) {
  64293. var textureSize = this.getSize();
  64294. textureSize.width = width;
  64295. textureSize.height = height;
  64296. this._recreate(textureSize);
  64297. };
  64298. /**
  64299. * Gets the context of the canvas used by the texture
  64300. * @returns the canvas context of the dynamic texture
  64301. */
  64302. DynamicTexture.prototype.getContext = function () {
  64303. return this._context;
  64304. };
  64305. /**
  64306. * Clears the texture
  64307. */
  64308. DynamicTexture.prototype.clear = function () {
  64309. var size = this.getSize();
  64310. this._context.fillRect(0, 0, size.width, size.height);
  64311. };
  64312. /**
  64313. * Updates the texture
  64314. * @param invertY defines the direction for the Y axis (default is true - y increases downwards)
  64315. */
  64316. DynamicTexture.prototype.update = function (invertY) {
  64317. this._engine.updateDynamicTexture(this._texture, this._canvas, invertY === undefined ? true : invertY, undefined, this._format || undefined);
  64318. };
  64319. /**
  64320. * Draws text onto the texture
  64321. * @param text defines the text to be drawn
  64322. * @param x defines the placement of the text from the left
  64323. * @param y defines the placement of the text from the top when invertY is true and from the bottom when false
  64324. * @param font defines the font to be used with font-style, font-size, font-name
  64325. * @param color defines the color used for the text
  64326. * @param clearColor defines the color for the canvas, use null to not overwrite canvas
  64327. * @param invertY defines the direction for the Y axis (default is true - y increases downwards)
  64328. * @param update defines whether texture is immediately update (default is true)
  64329. */
  64330. DynamicTexture.prototype.drawText = function (text, x, y, font, color, clearColor, invertY, update) {
  64331. if (update === void 0) { update = true; }
  64332. var size = this.getSize();
  64333. if (clearColor) {
  64334. this._context.fillStyle = clearColor;
  64335. this._context.fillRect(0, 0, size.width, size.height);
  64336. }
  64337. this._context.font = font;
  64338. if (x === null || x === undefined) {
  64339. var textSize = this._context.measureText(text);
  64340. x = (size.width - textSize.width) / 2;
  64341. }
  64342. if (y === null || y === undefined) {
  64343. var fontSize = parseInt((font.replace(/\D/g, '')));
  64344. ;
  64345. y = (size.height / 2) + (fontSize / 3.65);
  64346. }
  64347. this._context.fillStyle = color;
  64348. this._context.fillText(text, x, y);
  64349. if (update) {
  64350. this.update(invertY);
  64351. }
  64352. };
  64353. /**
  64354. * Clones the texture
  64355. * @returns the clone of the texture.
  64356. */
  64357. DynamicTexture.prototype.clone = function () {
  64358. var scene = this.getScene();
  64359. if (!scene) {
  64360. return this;
  64361. }
  64362. var textureSize = this.getSize();
  64363. var newTexture = new DynamicTexture(this.name, textureSize, scene, this._generateMipMaps);
  64364. // Base texture
  64365. newTexture.hasAlpha = this.hasAlpha;
  64366. newTexture.level = this.level;
  64367. // Dynamic Texture
  64368. newTexture.wrapU = this.wrapU;
  64369. newTexture.wrapV = this.wrapV;
  64370. return newTexture;
  64371. };
  64372. /** @hidden */
  64373. DynamicTexture.prototype._rebuild = function () {
  64374. this.update();
  64375. };
  64376. return DynamicTexture;
  64377. }(BABYLON.Texture));
  64378. BABYLON.DynamicTexture = DynamicTexture;
  64379. })(BABYLON || (BABYLON = {}));
  64380. //# sourceMappingURL=babylon.dynamicTexture.js.map
  64381. var BABYLON;
  64382. (function (BABYLON) {
  64383. var VideoTexture = /** @class */ (function (_super) {
  64384. __extends(VideoTexture, _super);
  64385. /**
  64386. * Creates a video texture.
  64387. * Sample : https://doc.babylonjs.com/how_to/video_texture
  64388. * @param {string | null} name optional name, will detect from video source, if not defined
  64389. * @param {(string | string[] | HTMLVideoElement)} src can be used to provide an url, array of urls or an already setup HTML video element.
  64390. * @param {BABYLON.Scene} scene is obviously the current scene.
  64391. * @param {boolean} generateMipMaps can be used to turn on mipmaps (Can be expensive for videoTextures because they are often updated).
  64392. * @param {boolean} invertY is false by default but can be used to invert video on Y axis
  64393. * @param {number} samplingMode controls the sampling method and is set to TRILINEAR_SAMPLINGMODE by default
  64394. * @param {VideoTextureSettings} [settings] allows finer control over video usage
  64395. */
  64396. function VideoTexture(name, src, scene, generateMipMaps, invertY, samplingMode, settings) {
  64397. if (generateMipMaps === void 0) { generateMipMaps = false; }
  64398. if (invertY === void 0) { invertY = false; }
  64399. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  64400. if (settings === void 0) { settings = {
  64401. autoPlay: true,
  64402. loop: true,
  64403. autoUpdateTexture: true,
  64404. }; }
  64405. var _this = _super.call(this, null, scene, !generateMipMaps, invertY) || this;
  64406. _this._stillImageCaptured = false;
  64407. _this._createInternalTexture = function () {
  64408. if (_this._texture != null) {
  64409. return;
  64410. }
  64411. if (!_this._engine.needPOTTextures ||
  64412. (BABYLON.Tools.IsExponentOfTwo(_this.video.videoWidth) && BABYLON.Tools.IsExponentOfTwo(_this.video.videoHeight))) {
  64413. _this.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  64414. _this.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  64415. }
  64416. else {
  64417. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  64418. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  64419. _this._generateMipMaps = false;
  64420. }
  64421. _this._texture = _this._engine.createDynamicTexture(_this.video.videoWidth, _this.video.videoHeight, _this._generateMipMaps, _this._samplingMode);
  64422. _this._texture.isReady = true;
  64423. _this._updateInternalTexture();
  64424. if (_this._onLoadObservable && _this._onLoadObservable.hasObservers()) {
  64425. _this.onLoadObservable.notifyObservers(_this);
  64426. }
  64427. };
  64428. _this.reset = function () {
  64429. if (_this._texture == null) {
  64430. return;
  64431. }
  64432. _this._texture.dispose();
  64433. _this._texture = null;
  64434. };
  64435. _this._updateInternalTexture = function (e) {
  64436. if (_this._texture == null || !_this._texture.isReady) {
  64437. return;
  64438. }
  64439. if (_this.video.readyState < _this.video.HAVE_CURRENT_DATA) {
  64440. return;
  64441. }
  64442. _this._engine.updateVideoTexture(_this._texture, _this.video, _this._invertY);
  64443. };
  64444. _this._engine = _this.getScene().getEngine();
  64445. _this._generateMipMaps = generateMipMaps;
  64446. _this._samplingMode = samplingMode;
  64447. _this.autoUpdateTexture = settings.autoUpdateTexture;
  64448. _this.name = name || _this._getName(src);
  64449. _this.video = _this._getVideo(src);
  64450. if (settings.autoPlay !== undefined) {
  64451. _this.video.autoplay = settings.autoPlay;
  64452. }
  64453. if (settings.loop !== undefined) {
  64454. _this.video.loop = settings.loop;
  64455. }
  64456. _this.video.addEventListener("canplay", _this._createInternalTexture);
  64457. _this.video.addEventListener("paused", _this._updateInternalTexture);
  64458. _this.video.addEventListener("seeked", _this._updateInternalTexture);
  64459. _this.video.addEventListener("emptied", _this.reset);
  64460. if (_this.video.readyState >= _this.video.HAVE_CURRENT_DATA) {
  64461. _this._createInternalTexture();
  64462. }
  64463. return _this;
  64464. }
  64465. VideoTexture.prototype._getName = function (src) {
  64466. if (src instanceof HTMLVideoElement) {
  64467. return src.currentSrc;
  64468. }
  64469. if (typeof src === "object") {
  64470. return src.toString();
  64471. }
  64472. return src;
  64473. };
  64474. ;
  64475. VideoTexture.prototype._getVideo = function (src) {
  64476. if (src instanceof HTMLVideoElement) {
  64477. BABYLON.Tools.SetCorsBehavior(src.currentSrc, src);
  64478. return src;
  64479. }
  64480. var video = document.createElement("video");
  64481. if (typeof src === "string") {
  64482. BABYLON.Tools.SetCorsBehavior(src, video);
  64483. video.src = src;
  64484. }
  64485. else {
  64486. BABYLON.Tools.SetCorsBehavior(src[0], video);
  64487. src.forEach(function (url) {
  64488. var source = document.createElement("source");
  64489. source.src = url;
  64490. video.appendChild(source);
  64491. });
  64492. }
  64493. return video;
  64494. };
  64495. ;
  64496. /**
  64497. * Internal method to initiate `update`.
  64498. */
  64499. VideoTexture.prototype._rebuild = function () {
  64500. this.update();
  64501. };
  64502. /**
  64503. * Update Texture in the `auto` mode. Does not do anything if `settings.autoUpdateTexture` is false.
  64504. */
  64505. VideoTexture.prototype.update = function () {
  64506. if (!this.autoUpdateTexture) {
  64507. // Expecting user to call `updateTexture` manually
  64508. return;
  64509. }
  64510. this.updateTexture(true);
  64511. };
  64512. /**
  64513. * Update Texture in `manual` mode. Does not do anything if not visible or paused.
  64514. * @param isVisible Visibility state, detected by user using `scene.getActiveMeshes()` or othervise.
  64515. */
  64516. VideoTexture.prototype.updateTexture = function (isVisible) {
  64517. if (!isVisible) {
  64518. return;
  64519. }
  64520. if (this.video.paused && this._stillImageCaptured) {
  64521. return;
  64522. }
  64523. this._stillImageCaptured = true;
  64524. this._updateInternalTexture();
  64525. };
  64526. /**
  64527. * Change video content. Changing video instance or setting multiple urls (as in constructor) is not supported.
  64528. * @param url New url.
  64529. */
  64530. VideoTexture.prototype.updateURL = function (url) {
  64531. this.video.src = url;
  64532. };
  64533. VideoTexture.prototype.dispose = function () {
  64534. _super.prototype.dispose.call(this);
  64535. this.video.removeEventListener("canplay", this._createInternalTexture);
  64536. this.video.removeEventListener("paused", this._updateInternalTexture);
  64537. this.video.removeEventListener("seeked", this._updateInternalTexture);
  64538. this.video.removeEventListener("emptied", this.reset);
  64539. this.video.pause();
  64540. };
  64541. VideoTexture.CreateFromWebCam = function (scene, onReady, constraints) {
  64542. var video = document.createElement("video");
  64543. var constraintsDeviceId;
  64544. if (constraints && constraints.deviceId) {
  64545. constraintsDeviceId = {
  64546. exact: constraints.deviceId,
  64547. };
  64548. }
  64549. window.URL = window.URL || window.webkitURL || window.mozURL || window.msURL;
  64550. if (navigator.mediaDevices) {
  64551. navigator.mediaDevices.getUserMedia({ video: constraints })
  64552. .then(function (stream) {
  64553. if (video.mozSrcObject !== undefined) {
  64554. // hack for Firefox < 19
  64555. video.mozSrcObject = stream;
  64556. }
  64557. else {
  64558. video.srcObject = stream;
  64559. }
  64560. var onPlaying = function () {
  64561. if (onReady) {
  64562. onReady(new VideoTexture("video", video, scene, true, true));
  64563. }
  64564. video.removeEventListener("playing", onPlaying);
  64565. };
  64566. video.addEventListener("playing", onPlaying);
  64567. video.play();
  64568. })
  64569. .catch(function (err) {
  64570. BABYLON.Tools.Error(err.name);
  64571. });
  64572. }
  64573. else {
  64574. navigator.getUserMedia =
  64575. navigator.getUserMedia ||
  64576. navigator.webkitGetUserMedia ||
  64577. navigator.mozGetUserMedia ||
  64578. navigator.msGetUserMedia;
  64579. if (navigator.getUserMedia) {
  64580. navigator.getUserMedia({
  64581. video: {
  64582. deviceId: constraintsDeviceId,
  64583. width: {
  64584. min: (constraints && constraints.minWidth) || 256,
  64585. max: (constraints && constraints.maxWidth) || 640,
  64586. },
  64587. height: {
  64588. min: (constraints && constraints.minHeight) || 256,
  64589. max: (constraints && constraints.maxHeight) || 480,
  64590. },
  64591. },
  64592. }, function (stream) {
  64593. if (video.mozSrcObject !== undefined) {
  64594. // hack for Firefox < 19
  64595. video.mozSrcObject = stream;
  64596. }
  64597. else {
  64598. video.src = (window.URL && window.URL.createObjectURL(stream)) || stream;
  64599. }
  64600. video.play();
  64601. if (onReady) {
  64602. onReady(new VideoTexture("video", video, scene, true, true));
  64603. }
  64604. }, function (e) {
  64605. BABYLON.Tools.Error(e.name);
  64606. });
  64607. }
  64608. }
  64609. };
  64610. return VideoTexture;
  64611. }(BABYLON.Texture));
  64612. BABYLON.VideoTexture = VideoTexture;
  64613. })(BABYLON || (BABYLON = {}));
  64614. //# sourceMappingURL=babylon.videoTexture.js.map
  64615. var BABYLON;
  64616. (function (BABYLON) {
  64617. var RawTexture = /** @class */ (function (_super) {
  64618. __extends(RawTexture, _super);
  64619. function RawTexture(data, width, height, format, scene, generateMipMaps, invertY, samplingMode, type) {
  64620. if (generateMipMaps === void 0) { generateMipMaps = true; }
  64621. if (invertY === void 0) { invertY = false; }
  64622. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  64623. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  64624. var _this = _super.call(this, null, scene, !generateMipMaps, invertY) || this;
  64625. _this.format = format;
  64626. _this._engine = scene.getEngine();
  64627. _this._texture = scene.getEngine().createRawTexture(data, width, height, format, generateMipMaps, invertY, samplingMode, null, type);
  64628. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  64629. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  64630. return _this;
  64631. }
  64632. RawTexture.prototype.update = function (data) {
  64633. this._engine.updateRawTexture(this._texture, data, this._texture.format, this._texture.invertY, undefined, this._texture.type);
  64634. };
  64635. // Statics
  64636. RawTexture.CreateLuminanceTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  64637. if (generateMipMaps === void 0) { generateMipMaps = true; }
  64638. if (invertY === void 0) { invertY = false; }
  64639. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  64640. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_LUMINANCE, scene, generateMipMaps, invertY, samplingMode);
  64641. };
  64642. RawTexture.CreateLuminanceAlphaTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  64643. if (generateMipMaps === void 0) { generateMipMaps = true; }
  64644. if (invertY === void 0) { invertY = false; }
  64645. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  64646. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_LUMINANCE_ALPHA, scene, generateMipMaps, invertY, samplingMode);
  64647. };
  64648. RawTexture.CreateAlphaTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  64649. if (generateMipMaps === void 0) { generateMipMaps = true; }
  64650. if (invertY === void 0) { invertY = false; }
  64651. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  64652. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_ALPHA, scene, generateMipMaps, invertY, samplingMode);
  64653. };
  64654. RawTexture.CreateRGBTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode, type) {
  64655. if (generateMipMaps === void 0) { generateMipMaps = true; }
  64656. if (invertY === void 0) { invertY = false; }
  64657. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  64658. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  64659. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_RGB, scene, generateMipMaps, invertY, samplingMode, type);
  64660. };
  64661. RawTexture.CreateRGBATexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode, type) {
  64662. if (generateMipMaps === void 0) { generateMipMaps = true; }
  64663. if (invertY === void 0) { invertY = false; }
  64664. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  64665. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  64666. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_RGBA, scene, generateMipMaps, invertY, samplingMode, type);
  64667. };
  64668. return RawTexture;
  64669. }(BABYLON.Texture));
  64670. BABYLON.RawTexture = RawTexture;
  64671. })(BABYLON || (BABYLON = {}));
  64672. //# sourceMappingURL=babylon.rawTexture.js.map
  64673. var BABYLON;
  64674. (function (BABYLON) {
  64675. /**
  64676. * Class used to store 3D textures containing user data
  64677. */
  64678. var RawTexture3D = /** @class */ (function (_super) {
  64679. __extends(RawTexture3D, _super);
  64680. /**
  64681. * Create a new RawTexture3D
  64682. * @param data defines the data of the texture
  64683. * @param width defines the width of the texture
  64684. * @param height defines the height of the texture
  64685. * @param depth defines the depth of the texture
  64686. * @param format defines the texture format to use
  64687. * @param scene defines the hosting scene
  64688. * @param generateMipMaps defines a boolean indicating if mip levels should be generated (true by default)
  64689. * @param invertY defines if texture must be stored with Y axis inverted
  64690. * @param samplingMode defines the sampling mode to use (BABYLON.Texture.TRILINEAR_SAMPLINGMODE by default)
  64691. */
  64692. function RawTexture3D(data, width, height, depth,
  64693. /** Gets or sets the texture format to use*/
  64694. format, scene, generateMipMaps, invertY, samplingMode) {
  64695. if (generateMipMaps === void 0) { generateMipMaps = true; }
  64696. if (invertY === void 0) { invertY = false; }
  64697. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  64698. var _this = _super.call(this, null, scene, !generateMipMaps, invertY) || this;
  64699. _this.format = format;
  64700. _this._engine = scene.getEngine();
  64701. _this._texture = scene.getEngine().createRawTexture3D(data, width, height, depth, format, generateMipMaps, invertY, samplingMode);
  64702. _this.is3D = true;
  64703. return _this;
  64704. }
  64705. /**
  64706. * Update the texture with new data
  64707. * @param data defines the data to store in the texture
  64708. */
  64709. RawTexture3D.prototype.update = function (data) {
  64710. if (!this._texture) {
  64711. return;
  64712. }
  64713. this._engine.updateRawTexture3D(this._texture, data, this._texture.format, this._texture.invertY);
  64714. };
  64715. return RawTexture3D;
  64716. }(BABYLON.Texture));
  64717. BABYLON.RawTexture3D = RawTexture3D;
  64718. })(BABYLON || (BABYLON = {}));
  64719. //# sourceMappingURL=babylon.rawTexture3D.js.map
  64720. var BABYLON;
  64721. (function (BABYLON) {
  64722. /**
  64723. * PostProcess can be used to apply a shader to a texture after it has been rendered
  64724. * See https://doc.babylonjs.com/how_to/how_to_use_postprocesses
  64725. */
  64726. var PostProcess = /** @class */ (function () {
  64727. /**
  64728. * Creates a new instance PostProcess
  64729. * @param name The name of the PostProcess.
  64730. * @param fragmentUrl The url of the fragment shader to be used.
  64731. * @param parameters Array of the names of uniform non-sampler2D variables that will be passed to the shader.
  64732. * @param samplers Array of the names of uniform sampler2D variables that will be passed to the shader.
  64733. * @param options The required width/height ratio to downsize to before computing the render pass. (Use 1.0 for full size)
  64734. * @param camera The camera to apply the render pass to.
  64735. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  64736. * @param engine The engine which the post process will be applied. (default: current engine)
  64737. * @param reusable If the post process can be reused on the same frame. (default: false)
  64738. * @param defines String of defines that will be set when running the fragment shader. (default: null)
  64739. * @param textureType Type of textures used when performing the post process. (default: 0)
  64740. * @param vertexUrl The url of the vertex shader to be used. (default: "postprocess")
  64741. * @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
  64742. * @param blockCompilation If the shader should not be compiled imediatly. (default: false)
  64743. */
  64744. function PostProcess(/** Name of the PostProcess. */ name, fragmentUrl, parameters, samplers, options, camera, samplingMode, engine, reusable, defines, textureType, vertexUrl, indexParameters, blockCompilation) {
  64745. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE; }
  64746. if (defines === void 0) { defines = null; }
  64747. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  64748. if (vertexUrl === void 0) { vertexUrl = "postprocess"; }
  64749. if (blockCompilation === void 0) { blockCompilation = false; }
  64750. this.name = name;
  64751. /**
  64752. * Width of the texture to apply the post process on
  64753. */
  64754. this.width = -1;
  64755. /**
  64756. * Height of the texture to apply the post process on
  64757. */
  64758. this.height = -1;
  64759. /**
  64760. * Internal, reference to the location where this postprocess was output to. (Typically the texture on the next postprocess in the chain)
  64761. */
  64762. this._outputTexture = null;
  64763. /**
  64764. * If the buffer needs to be cleared before applying the post process. (default: true)
  64765. * Should be set to false if shader will overwrite all previous pixels.
  64766. */
  64767. this.autoClear = true;
  64768. /**
  64769. * Type of alpha mode to use when performing the post process (default: Engine.ALPHA_DISABLE)
  64770. */
  64771. this.alphaMode = BABYLON.Engine.ALPHA_DISABLE;
  64772. /**
  64773. * Animations to be used for the post processing
  64774. */
  64775. this.animations = new Array();
  64776. /**
  64777. * Enable Pixel Perfect mode where texture is not scaled to be power of 2.
  64778. * Can only be used on a single postprocess or on the last one of a chain. (default: false)
  64779. */
  64780. this.enablePixelPerfectMode = false;
  64781. /**
  64782. * Scale mode for the post process (default: Engine.SCALEMODE_FLOOR)
  64783. */
  64784. this.scaleMode = BABYLON.Engine.SCALEMODE_FLOOR;
  64785. /**
  64786. * Force textures to be a power of two (default: false)
  64787. */
  64788. this.alwaysForcePOT = false;
  64789. /**
  64790. * Number of sample textures (default: 1)
  64791. */
  64792. this.samples = 1;
  64793. /**
  64794. * Modify the scale of the post process to be the same as the viewport (default: false)
  64795. */
  64796. this.adaptScaleToCurrentViewport = false;
  64797. this._reusable = false;
  64798. /**
  64799. * Smart array of input and output textures for the post process.
  64800. */
  64801. this._textures = new BABYLON.SmartArray(2);
  64802. /**
  64803. * The index in _textures that corresponds to the output texture.
  64804. */
  64805. this._currentRenderTextureInd = 0;
  64806. this._scaleRatio = new BABYLON.Vector2(1, 1);
  64807. this._texelSize = BABYLON.Vector2.Zero();
  64808. // Events
  64809. /**
  64810. * An event triggered when the postprocess is activated.
  64811. */
  64812. this.onActivateObservable = new BABYLON.Observable();
  64813. /**
  64814. * An event triggered when the postprocess changes its size.
  64815. */
  64816. this.onSizeChangedObservable = new BABYLON.Observable();
  64817. /**
  64818. * An event triggered when the postprocess applies its effect.
  64819. */
  64820. this.onApplyObservable = new BABYLON.Observable();
  64821. /**
  64822. * An event triggered before rendering the postprocess
  64823. */
  64824. this.onBeforeRenderObservable = new BABYLON.Observable();
  64825. /**
  64826. * An event triggered after rendering the postprocess
  64827. */
  64828. this.onAfterRenderObservable = new BABYLON.Observable();
  64829. if (camera != null) {
  64830. this._camera = camera;
  64831. this._scene = camera.getScene();
  64832. camera.attachPostProcess(this);
  64833. this._engine = this._scene.getEngine();
  64834. this._scene.postProcesses.push(this);
  64835. }
  64836. else if (engine) {
  64837. this._engine = engine;
  64838. this._engine.postProcesses.push(this);
  64839. }
  64840. this._options = options;
  64841. this.renderTargetSamplingMode = samplingMode ? samplingMode : BABYLON.Texture.NEAREST_SAMPLINGMODE;
  64842. this._reusable = reusable || false;
  64843. this._textureType = textureType;
  64844. this._samplers = samplers || [];
  64845. this._samplers.push("textureSampler");
  64846. this._fragmentUrl = fragmentUrl;
  64847. this._vertexUrl = vertexUrl;
  64848. this._parameters = parameters || [];
  64849. this._parameters.push("scale");
  64850. this._indexParameters = indexParameters;
  64851. if (!blockCompilation) {
  64852. this.updateEffect(defines);
  64853. }
  64854. }
  64855. Object.defineProperty(PostProcess.prototype, "onActivate", {
  64856. /**
  64857. * A function that is added to the onActivateObservable
  64858. */
  64859. set: function (callback) {
  64860. if (this._onActivateObserver) {
  64861. this.onActivateObservable.remove(this._onActivateObserver);
  64862. }
  64863. if (callback) {
  64864. this._onActivateObserver = this.onActivateObservable.add(callback);
  64865. }
  64866. },
  64867. enumerable: true,
  64868. configurable: true
  64869. });
  64870. Object.defineProperty(PostProcess.prototype, "onSizeChanged", {
  64871. /**
  64872. * A function that is added to the onSizeChangedObservable
  64873. */
  64874. set: function (callback) {
  64875. if (this._onSizeChangedObserver) {
  64876. this.onSizeChangedObservable.remove(this._onSizeChangedObserver);
  64877. }
  64878. this._onSizeChangedObserver = this.onSizeChangedObservable.add(callback);
  64879. },
  64880. enumerable: true,
  64881. configurable: true
  64882. });
  64883. Object.defineProperty(PostProcess.prototype, "onApply", {
  64884. /**
  64885. * A function that is added to the onApplyObservable
  64886. */
  64887. set: function (callback) {
  64888. if (this._onApplyObserver) {
  64889. this.onApplyObservable.remove(this._onApplyObserver);
  64890. }
  64891. this._onApplyObserver = this.onApplyObservable.add(callback);
  64892. },
  64893. enumerable: true,
  64894. configurable: true
  64895. });
  64896. Object.defineProperty(PostProcess.prototype, "onBeforeRender", {
  64897. /**
  64898. * A function that is added to the onBeforeRenderObservable
  64899. */
  64900. set: function (callback) {
  64901. if (this._onBeforeRenderObserver) {
  64902. this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
  64903. }
  64904. this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
  64905. },
  64906. enumerable: true,
  64907. configurable: true
  64908. });
  64909. Object.defineProperty(PostProcess.prototype, "onAfterRender", {
  64910. /**
  64911. * A function that is added to the onAfterRenderObservable
  64912. */
  64913. set: function (callback) {
  64914. if (this._onAfterRenderObserver) {
  64915. this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  64916. }
  64917. this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
  64918. },
  64919. enumerable: true,
  64920. configurable: true
  64921. });
  64922. Object.defineProperty(PostProcess.prototype, "inputTexture", {
  64923. /**
  64924. * 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
  64925. * render it's output into this texture and this texture will be used as textureSampler in the fragment shader of this post process.
  64926. */
  64927. get: function () {
  64928. return this._textures.data[this._currentRenderTextureInd];
  64929. },
  64930. set: function (value) {
  64931. this._forcedOutputTexture = value;
  64932. },
  64933. enumerable: true,
  64934. configurable: true
  64935. });
  64936. /**
  64937. * Gets the camera which post process is applied to.
  64938. * @returns The camera the post process is applied to.
  64939. */
  64940. PostProcess.prototype.getCamera = function () {
  64941. return this._camera;
  64942. };
  64943. Object.defineProperty(PostProcess.prototype, "texelSize", {
  64944. /**
  64945. * Gets the texel size of the postprocess.
  64946. * See https://en.wikipedia.org/wiki/Texel_(graphics)
  64947. */
  64948. get: function () {
  64949. if (this._shareOutputWithPostProcess) {
  64950. return this._shareOutputWithPostProcess.texelSize;
  64951. }
  64952. if (this._forcedOutputTexture) {
  64953. this._texelSize.copyFromFloats(1.0 / this._forcedOutputTexture.width, 1.0 / this._forcedOutputTexture.height);
  64954. }
  64955. return this._texelSize;
  64956. },
  64957. enumerable: true,
  64958. configurable: true
  64959. });
  64960. /**
  64961. * Gets the engine which this post process belongs to.
  64962. * @returns The engine the post process was enabled with.
  64963. */
  64964. PostProcess.prototype.getEngine = function () {
  64965. return this._engine;
  64966. };
  64967. /**
  64968. * The effect that is created when initializing the post process.
  64969. * @returns The created effect corrisponding the the postprocess.
  64970. */
  64971. PostProcess.prototype.getEffect = function () {
  64972. return this._effect;
  64973. };
  64974. /**
  64975. * To avoid multiple redundant textures for multiple post process, the output the output texture for this post process can be shared with another.
  64976. * @param postProcess The post process to share the output with.
  64977. * @returns This post process.
  64978. */
  64979. PostProcess.prototype.shareOutputWith = function (postProcess) {
  64980. this._disposeTextures();
  64981. this._shareOutputWithPostProcess = postProcess;
  64982. return this;
  64983. };
  64984. /**
  64985. * Reverses the effect of calling shareOutputWith and returns the post process back to its original state.
  64986. * This should be called if the post process that shares output with this post process is disabled/disposed.
  64987. */
  64988. PostProcess.prototype.useOwnOutput = function () {
  64989. if (this._textures.length == 0) {
  64990. this._textures = new BABYLON.SmartArray(2);
  64991. }
  64992. this._shareOutputWithPostProcess = null;
  64993. };
  64994. /**
  64995. * Updates the effect with the current post process compile time values and recompiles the shader.
  64996. * @param defines Define statements that should be added at the beginning of the shader. (default: null)
  64997. * @param uniforms Set of uniform variables that will be passed to the shader. (default: null)
  64998. * @param samplers Set of Texture2D variables that will be passed to the shader. (default: null)
  64999. * @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
  65000. * @param onCompiled Called when the shader has been compiled.
  65001. * @param onError Called if there is an error when compiling a shader.
  65002. */
  65003. PostProcess.prototype.updateEffect = function (defines, uniforms, samplers, indexParameters, onCompiled, onError) {
  65004. if (defines === void 0) { defines = null; }
  65005. if (uniforms === void 0) { uniforms = null; }
  65006. if (samplers === void 0) { samplers = null; }
  65007. 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);
  65008. };
  65009. /**
  65010. * The post process is reusable if it can be used multiple times within one frame.
  65011. * @returns If the post process is reusable
  65012. */
  65013. PostProcess.prototype.isReusable = function () {
  65014. return this._reusable;
  65015. };
  65016. /** invalidate frameBuffer to hint the postprocess to create a depth buffer */
  65017. PostProcess.prototype.markTextureDirty = function () {
  65018. this.width = -1;
  65019. };
  65020. /**
  65021. * Activates the post process by intializing the textures to be used when executed. Notifies onActivateObservable.
  65022. * 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.
  65023. * @param camera The camera that will be used in the post process. This camera will be used when calling onActivateObservable.
  65024. * @param sourceTexture The source texture to be inspected to get the width and height if not specified in the post process constructor. (default: null)
  65025. * @param forceDepthStencil If true, a depth and stencil buffer will be generated. (default: false)
  65026. * @returns The target texture that was bound to be written to.
  65027. */
  65028. PostProcess.prototype.activate = function (camera, sourceTexture, forceDepthStencil) {
  65029. var _this = this;
  65030. if (sourceTexture === void 0) { sourceTexture = null; }
  65031. camera = camera || this._camera;
  65032. var scene = camera.getScene();
  65033. var engine = scene.getEngine();
  65034. var maxSize = engine.getCaps().maxTextureSize;
  65035. var requiredWidth = ((sourceTexture ? sourceTexture.width : this._engine.getRenderWidth(true)) * this._options) | 0;
  65036. var requiredHeight = ((sourceTexture ? sourceTexture.height : this._engine.getRenderHeight(true)) * this._options) | 0;
  65037. // 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
  65038. var webVRCamera = camera.parent;
  65039. if (webVRCamera && (webVRCamera.leftCamera == camera || webVRCamera.rightCamera == camera)) {
  65040. requiredWidth /= 2;
  65041. }
  65042. var desiredWidth = (this._options.width || requiredWidth);
  65043. var desiredHeight = this._options.height || requiredHeight;
  65044. if (!this._shareOutputWithPostProcess && !this._forcedOutputTexture) {
  65045. if (this.adaptScaleToCurrentViewport) {
  65046. var currentViewport = engine.currentViewport;
  65047. if (currentViewport) {
  65048. desiredWidth *= currentViewport.width;
  65049. desiredHeight *= currentViewport.height;
  65050. }
  65051. }
  65052. if (this.renderTargetSamplingMode === BABYLON.Texture.TRILINEAR_SAMPLINGMODE || this.alwaysForcePOT) {
  65053. if (!this._options.width) {
  65054. desiredWidth = engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(desiredWidth, maxSize, this.scaleMode) : desiredWidth;
  65055. }
  65056. if (!this._options.height) {
  65057. desiredHeight = engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(desiredHeight, maxSize, this.scaleMode) : desiredHeight;
  65058. }
  65059. }
  65060. if (this.width !== desiredWidth || this.height !== desiredHeight) {
  65061. if (this._textures.length > 0) {
  65062. for (var i = 0; i < this._textures.length; i++) {
  65063. this._engine._releaseTexture(this._textures.data[i]);
  65064. }
  65065. this._textures.reset();
  65066. }
  65067. this.width = desiredWidth;
  65068. this.height = desiredHeight;
  65069. var textureSize = { width: this.width, height: this.height };
  65070. var textureOptions = {
  65071. generateMipMaps: false,
  65072. generateDepthBuffer: forceDepthStencil || camera._postProcesses.indexOf(this) === 0,
  65073. generateStencilBuffer: (forceDepthStencil || camera._postProcesses.indexOf(this) === 0) && this._engine.isStencilEnable,
  65074. samplingMode: this.renderTargetSamplingMode,
  65075. type: this._textureType
  65076. };
  65077. this._textures.push(this._engine.createRenderTargetTexture(textureSize, textureOptions));
  65078. if (this._reusable) {
  65079. this._textures.push(this._engine.createRenderTargetTexture(textureSize, textureOptions));
  65080. }
  65081. this._texelSize.copyFromFloats(1.0 / this.width, 1.0 / this.height);
  65082. this.onSizeChangedObservable.notifyObservers(this);
  65083. }
  65084. this._textures.forEach(function (texture) {
  65085. if (texture.samples !== _this.samples) {
  65086. _this._engine.updateRenderTargetTextureSampleCount(texture, _this.samples);
  65087. }
  65088. });
  65089. }
  65090. var target;
  65091. if (this._shareOutputWithPostProcess) {
  65092. target = this._shareOutputWithPostProcess.inputTexture;
  65093. }
  65094. else if (this._forcedOutputTexture) {
  65095. target = this._forcedOutputTexture;
  65096. this.width = this._forcedOutputTexture.width;
  65097. this.height = this._forcedOutputTexture.height;
  65098. }
  65099. else {
  65100. target = this.inputTexture;
  65101. }
  65102. // Bind the input of this post process to be used as the output of the previous post process.
  65103. if (this.enablePixelPerfectMode) {
  65104. this._scaleRatio.copyFromFloats(requiredWidth / desiredWidth, requiredHeight / desiredHeight);
  65105. this._engine.bindFramebuffer(target, 0, requiredWidth, requiredHeight, true);
  65106. }
  65107. else {
  65108. this._scaleRatio.copyFromFloats(1, 1);
  65109. this._engine.bindFramebuffer(target, 0, undefined, undefined, true);
  65110. }
  65111. this.onActivateObservable.notifyObservers(camera);
  65112. // Clear
  65113. if (this.autoClear && this.alphaMode === BABYLON.Engine.ALPHA_DISABLE) {
  65114. this._engine.clear(this.clearColor ? this.clearColor : scene.clearColor, true, true, true);
  65115. }
  65116. if (this._reusable) {
  65117. this._currentRenderTextureInd = (this._currentRenderTextureInd + 1) % 2;
  65118. }
  65119. return target;
  65120. };
  65121. Object.defineProperty(PostProcess.prototype, "isSupported", {
  65122. /**
  65123. * If the post process is supported.
  65124. */
  65125. get: function () {
  65126. return this._effect.isSupported;
  65127. },
  65128. enumerable: true,
  65129. configurable: true
  65130. });
  65131. Object.defineProperty(PostProcess.prototype, "aspectRatio", {
  65132. /**
  65133. * The aspect ratio of the output texture.
  65134. */
  65135. get: function () {
  65136. if (this._shareOutputWithPostProcess) {
  65137. return this._shareOutputWithPostProcess.aspectRatio;
  65138. }
  65139. if (this._forcedOutputTexture) {
  65140. return this._forcedOutputTexture.width / this._forcedOutputTexture.height;
  65141. }
  65142. return this.width / this.height;
  65143. },
  65144. enumerable: true,
  65145. configurable: true
  65146. });
  65147. /**
  65148. * Get a value indicating if the post-process is ready to be used
  65149. * @returns true if the post-process is ready (shader is compiled)
  65150. */
  65151. PostProcess.prototype.isReady = function () {
  65152. return this._effect && this._effect.isReady();
  65153. };
  65154. /**
  65155. * Binds all textures and uniforms to the shader, this will be run on every pass.
  65156. * @returns the effect corrisponding to this post process. Null if not compiled or not ready.
  65157. */
  65158. PostProcess.prototype.apply = function () {
  65159. // Check
  65160. if (!this._effect || !this._effect.isReady())
  65161. return null;
  65162. // States
  65163. this._engine.enableEffect(this._effect);
  65164. this._engine.setState(false);
  65165. this._engine.setDepthBuffer(false);
  65166. this._engine.setDepthWrite(false);
  65167. // Alpha
  65168. this._engine.setAlphaMode(this.alphaMode);
  65169. if (this.alphaConstants) {
  65170. this.getEngine().setAlphaConstants(this.alphaConstants.r, this.alphaConstants.g, this.alphaConstants.b, this.alphaConstants.a);
  65171. }
  65172. // Bind the output texture of the preivous post process as the input to this post process.
  65173. var source;
  65174. if (this._shareOutputWithPostProcess) {
  65175. source = this._shareOutputWithPostProcess.inputTexture;
  65176. }
  65177. else if (this._forcedOutputTexture) {
  65178. source = this._forcedOutputTexture;
  65179. }
  65180. else {
  65181. source = this.inputTexture;
  65182. }
  65183. this._effect._bindTexture("textureSampler", source);
  65184. // Parameters
  65185. this._effect.setVector2("scale", this._scaleRatio);
  65186. this.onApplyObservable.notifyObservers(this._effect);
  65187. return this._effect;
  65188. };
  65189. PostProcess.prototype._disposeTextures = function () {
  65190. if (this._shareOutputWithPostProcess || this._forcedOutputTexture) {
  65191. return;
  65192. }
  65193. if (this._textures.length > 0) {
  65194. for (var i = 0; i < this._textures.length; i++) {
  65195. this._engine._releaseTexture(this._textures.data[i]);
  65196. }
  65197. }
  65198. this._textures.dispose();
  65199. };
  65200. /**
  65201. * Disposes the post process.
  65202. * @param camera The camera to dispose the post process on.
  65203. */
  65204. PostProcess.prototype.dispose = function (camera) {
  65205. camera = camera || this._camera;
  65206. this._disposeTextures();
  65207. if (this._scene) {
  65208. var index_1 = this._scene.postProcesses.indexOf(this);
  65209. if (index_1 !== -1) {
  65210. this._scene.postProcesses.splice(index_1, 1);
  65211. }
  65212. }
  65213. else {
  65214. var index_2 = this._engine.postProcesses.indexOf(this);
  65215. if (index_2 !== -1) {
  65216. this._engine.postProcesses.splice(index_2, 1);
  65217. }
  65218. }
  65219. if (!camera) {
  65220. return;
  65221. }
  65222. camera.detachPostProcess(this);
  65223. var index = camera._postProcesses.indexOf(this);
  65224. if (index === 0 && camera._postProcesses.length > 0) {
  65225. var firstPostProcess = this._camera._getFirstPostProcess();
  65226. if (firstPostProcess) {
  65227. firstPostProcess.markTextureDirty();
  65228. }
  65229. }
  65230. this.onActivateObservable.clear();
  65231. this.onAfterRenderObservable.clear();
  65232. this.onApplyObservable.clear();
  65233. this.onBeforeRenderObservable.clear();
  65234. this.onSizeChangedObservable.clear();
  65235. };
  65236. return PostProcess;
  65237. }());
  65238. BABYLON.PostProcess = PostProcess;
  65239. })(BABYLON || (BABYLON = {}));
  65240. //# sourceMappingURL=babylon.postProcess.js.map
  65241. var BABYLON;
  65242. (function (BABYLON) {
  65243. var PassPostProcess = /** @class */ (function (_super) {
  65244. __extends(PassPostProcess, _super);
  65245. function PassPostProcess(name, options, camera, samplingMode, engine, reusable, textureType, blockCompilation) {
  65246. if (camera === void 0) { camera = null; }
  65247. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  65248. if (blockCompilation === void 0) { blockCompilation = false; }
  65249. return _super.call(this, name, "pass", null, null, options, camera, samplingMode, engine, reusable, undefined, textureType, undefined, null, blockCompilation) || this;
  65250. }
  65251. return PassPostProcess;
  65252. }(BABYLON.PostProcess));
  65253. BABYLON.PassPostProcess = PassPostProcess;
  65254. })(BABYLON || (BABYLON = {}));
  65255. //# sourceMappingURL=babylon.passPostProcess.js.map
  65256. var __assign = (this && this.__assign) || Object.assign || function(t) {
  65257. for (var s, i = 1, n = arguments.length; i < n; i++) {
  65258. s = arguments[i];
  65259. for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
  65260. t[p] = s[p];
  65261. }
  65262. return t;
  65263. };
  65264. var BABYLON;
  65265. (function (BABYLON) {
  65266. /**
  65267. * Default implementation IShadowGenerator.
  65268. * This is the main object responsible of generating shadows in the framework.
  65269. * Documentation: https://doc.babylonjs.com/babylon101/shadows
  65270. */
  65271. var ShadowGenerator = /** @class */ (function () {
  65272. /**
  65273. * Creates a ShadowGenerator object.
  65274. * A ShadowGenerator is the required tool to use the shadows.
  65275. * Each light casting shadows needs to use its own ShadowGenerator.
  65276. * Documentation : http://doc.babylonjs.com/tutorials/shadows
  65277. * @param mapSize The size of the texture what stores the shadows. Example : 1024.
  65278. * @param light The light object generating the shadows.
  65279. * @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.
  65280. */
  65281. function ShadowGenerator(mapSize, light, useFullFloatFirst) {
  65282. this._bias = 0.00005;
  65283. this._normalBias = 0;
  65284. this._blurBoxOffset = 1;
  65285. this._blurScale = 2;
  65286. this._blurKernel = 1;
  65287. this._useKernelBlur = false;
  65288. this._filter = ShadowGenerator.FILTER_NONE;
  65289. this._filteringQuality = ShadowGenerator.QUALITY_HIGH;
  65290. this._contactHardeningLightSizeUVRatio = 0.1;
  65291. this._darkness = 0;
  65292. this._transparencyShadow = false;
  65293. /**
  65294. * Controls the extent to which the shadows fade out at the edge of the frustum
  65295. * Used only by directionals and spots
  65296. */
  65297. this.frustumEdgeFalloff = 0;
  65298. /**
  65299. * If true the shadow map is generated by rendering the back face of the mesh instead of the front face.
  65300. * This can help with self-shadowing as the geometry making up the back of objects is slightly offset.
  65301. * It might on the other hand introduce peter panning.
  65302. */
  65303. this.forceBackFacesOnly = false;
  65304. this._lightDirection = BABYLON.Vector3.Zero();
  65305. this._viewMatrix = BABYLON.Matrix.Zero();
  65306. this._projectionMatrix = BABYLON.Matrix.Zero();
  65307. this._transformMatrix = BABYLON.Matrix.Zero();
  65308. this._cachedPosition = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  65309. this._cachedDirection = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  65310. this._currentFaceIndex = 0;
  65311. this._currentFaceIndexCache = 0;
  65312. this._defaultTextureMatrix = BABYLON.Matrix.Identity();
  65313. this._mapSize = mapSize;
  65314. this._light = light;
  65315. this._scene = light.getScene();
  65316. light._shadowGenerator = this;
  65317. // Texture type fallback from float to int if not supported.
  65318. var caps = this._scene.getEngine().getCaps();
  65319. if (!useFullFloatFirst) {
  65320. if (caps.textureHalfFloatRender && caps.textureHalfFloatLinearFiltering) {
  65321. this._textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  65322. }
  65323. else if (caps.textureFloatRender && caps.textureFloatLinearFiltering) {
  65324. this._textureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  65325. }
  65326. else {
  65327. this._textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  65328. }
  65329. }
  65330. else {
  65331. if (caps.textureFloatRender && caps.textureFloatLinearFiltering) {
  65332. this._textureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  65333. }
  65334. else if (caps.textureHalfFloatRender && caps.textureHalfFloatLinearFiltering) {
  65335. this._textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  65336. }
  65337. else {
  65338. this._textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  65339. }
  65340. }
  65341. this._initializeGenerator();
  65342. this._applyFilterValues();
  65343. }
  65344. Object.defineProperty(ShadowGenerator.prototype, "bias", {
  65345. /**
  65346. * Gets the bias: offset applied on the depth preventing acnea (in light direction).
  65347. */
  65348. get: function () {
  65349. return this._bias;
  65350. },
  65351. /**
  65352. * Sets the bias: offset applied on the depth preventing acnea (in light direction).
  65353. */
  65354. set: function (bias) {
  65355. this._bias = bias;
  65356. },
  65357. enumerable: true,
  65358. configurable: true
  65359. });
  65360. Object.defineProperty(ShadowGenerator.prototype, "normalBias", {
  65361. /**
  65362. * Gets the normalBias: offset applied on the depth preventing acnea (along side the normal direction and proportinal to the light/normal angle).
  65363. */
  65364. get: function () {
  65365. return this._normalBias;
  65366. },
  65367. /**
  65368. * Sets the normalBias: offset applied on the depth preventing acnea (along side the normal direction and proportinal to the light/normal angle).
  65369. */
  65370. set: function (normalBias) {
  65371. this._normalBias = normalBias;
  65372. },
  65373. enumerable: true,
  65374. configurable: true
  65375. });
  65376. Object.defineProperty(ShadowGenerator.prototype, "blurBoxOffset", {
  65377. /**
  65378. * Gets the blur box offset: offset applied during the blur pass.
  65379. * Only usefull if useKernelBlur = false
  65380. */
  65381. get: function () {
  65382. return this._blurBoxOffset;
  65383. },
  65384. /**
  65385. * Sets the blur box offset: offset applied during the blur pass.
  65386. * Only usefull if useKernelBlur = false
  65387. */
  65388. set: function (value) {
  65389. if (this._blurBoxOffset === value) {
  65390. return;
  65391. }
  65392. this._blurBoxOffset = value;
  65393. this._disposeBlurPostProcesses();
  65394. },
  65395. enumerable: true,
  65396. configurable: true
  65397. });
  65398. Object.defineProperty(ShadowGenerator.prototype, "blurScale", {
  65399. /**
  65400. * Gets the blur scale: scale of the blurred texture compared to the main shadow map.
  65401. * 2 means half of the size.
  65402. */
  65403. get: function () {
  65404. return this._blurScale;
  65405. },
  65406. /**
  65407. * Sets the blur scale: scale of the blurred texture compared to the main shadow map.
  65408. * 2 means half of the size.
  65409. */
  65410. set: function (value) {
  65411. if (this._blurScale === value) {
  65412. return;
  65413. }
  65414. this._blurScale = value;
  65415. this._disposeBlurPostProcesses();
  65416. },
  65417. enumerable: true,
  65418. configurable: true
  65419. });
  65420. Object.defineProperty(ShadowGenerator.prototype, "blurKernel", {
  65421. /**
  65422. * Gets the blur kernel: kernel size of the blur pass.
  65423. * Only usefull if useKernelBlur = true
  65424. */
  65425. get: function () {
  65426. return this._blurKernel;
  65427. },
  65428. /**
  65429. * Sets the blur kernel: kernel size of the blur pass.
  65430. * Only usefull if useKernelBlur = true
  65431. */
  65432. set: function (value) {
  65433. if (this._blurKernel === value) {
  65434. return;
  65435. }
  65436. this._blurKernel = value;
  65437. this._disposeBlurPostProcesses();
  65438. },
  65439. enumerable: true,
  65440. configurable: true
  65441. });
  65442. Object.defineProperty(ShadowGenerator.prototype, "useKernelBlur", {
  65443. /**
  65444. * Gets whether the blur pass is a kernel blur (if true) or box blur.
  65445. * Only usefull in filtered mode (useBlurExponentialShadowMap...)
  65446. */
  65447. get: function () {
  65448. return this._useKernelBlur;
  65449. },
  65450. /**
  65451. * Sets whether the blur pass is a kernel blur (if true) or box blur.
  65452. * Only usefull in filtered mode (useBlurExponentialShadowMap...)
  65453. */
  65454. set: function (value) {
  65455. if (this._useKernelBlur === value) {
  65456. return;
  65457. }
  65458. this._useKernelBlur = value;
  65459. this._disposeBlurPostProcesses();
  65460. },
  65461. enumerable: true,
  65462. configurable: true
  65463. });
  65464. Object.defineProperty(ShadowGenerator.prototype, "depthScale", {
  65465. /**
  65466. * Gets the depth scale used in ESM mode.
  65467. */
  65468. get: function () {
  65469. return this._depthScale !== undefined ? this._depthScale : this._light.getDepthScale();
  65470. },
  65471. /**
  65472. * Sets the depth scale used in ESM mode.
  65473. * This can override the scale stored on the light.
  65474. */
  65475. set: function (value) {
  65476. this._depthScale = value;
  65477. },
  65478. enumerable: true,
  65479. configurable: true
  65480. });
  65481. Object.defineProperty(ShadowGenerator.prototype, "filter", {
  65482. /**
  65483. * Gets the current mode of the shadow generator (normal, PCF, ESM...).
  65484. * The returned value is a number equal to one of the available mode defined in ShadowMap.FILTER_x like _FILTER_NONE
  65485. */
  65486. get: function () {
  65487. return this._filter;
  65488. },
  65489. /**
  65490. * Sets the current mode of the shadow generator (normal, PCF, ESM...).
  65491. * The returned value is a number equal to one of the available mode defined in ShadowMap.FILTER_x like _FILTER_NONE
  65492. */
  65493. set: function (value) {
  65494. // Blurring the cubemap is going to be too expensive. Reverting to unblurred version
  65495. if (this._light.needCube()) {
  65496. if (value === ShadowGenerator.FILTER_BLUREXPONENTIALSHADOWMAP) {
  65497. this.useExponentialShadowMap = true;
  65498. return;
  65499. }
  65500. else if (value === ShadowGenerator.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP) {
  65501. this.useCloseExponentialShadowMap = true;
  65502. return;
  65503. }
  65504. // PCF on cubemap would also be expensive
  65505. else if (value === ShadowGenerator.FILTER_PCF || value === ShadowGenerator.FILTER_PCSS) {
  65506. this.usePoissonSampling = true;
  65507. return;
  65508. }
  65509. }
  65510. // Weblg1 fallback for PCF.
  65511. if (value === ShadowGenerator.FILTER_PCF || value === ShadowGenerator.FILTER_PCSS) {
  65512. if (this._scene.getEngine().webGLVersion === 1) {
  65513. this.usePoissonSampling = true;
  65514. return;
  65515. }
  65516. }
  65517. if (this._filter === value) {
  65518. return;
  65519. }
  65520. this._filter = value;
  65521. this._disposeBlurPostProcesses();
  65522. this._applyFilterValues();
  65523. this._light._markMeshesAsLightDirty();
  65524. },
  65525. enumerable: true,
  65526. configurable: true
  65527. });
  65528. Object.defineProperty(ShadowGenerator.prototype, "usePoissonSampling", {
  65529. /**
  65530. * Gets if the current filter is set to Poisson Sampling.
  65531. */
  65532. get: function () {
  65533. return this.filter === ShadowGenerator.FILTER_POISSONSAMPLING;
  65534. },
  65535. /**
  65536. * Sets the current filter to Poisson Sampling.
  65537. */
  65538. set: function (value) {
  65539. if (!value && this.filter !== ShadowGenerator.FILTER_POISSONSAMPLING) {
  65540. return;
  65541. }
  65542. this.filter = (value ? ShadowGenerator.FILTER_POISSONSAMPLING : ShadowGenerator.FILTER_NONE);
  65543. },
  65544. enumerable: true,
  65545. configurable: true
  65546. });
  65547. Object.defineProperty(ShadowGenerator.prototype, "useVarianceShadowMap", {
  65548. /**
  65549. * Gets if the current filter is set to VSM.
  65550. * DEPRECATED. Should use useExponentialShadowMap instead.
  65551. */
  65552. get: function () {
  65553. BABYLON.Tools.Warn("VSM are now replaced by ESM. Please use useExponentialShadowMap instead.");
  65554. return this.useExponentialShadowMap;
  65555. },
  65556. /**
  65557. * Sets the current filter is to VSM.
  65558. * DEPRECATED. Should use useExponentialShadowMap instead.
  65559. */
  65560. set: function (value) {
  65561. BABYLON.Tools.Warn("VSM are now replaced by ESM. Please use useExponentialShadowMap instead.");
  65562. this.useExponentialShadowMap = value;
  65563. },
  65564. enumerable: true,
  65565. configurable: true
  65566. });
  65567. Object.defineProperty(ShadowGenerator.prototype, "useBlurVarianceShadowMap", {
  65568. /**
  65569. * Gets if the current filter is set to blurred VSM.
  65570. * DEPRECATED. Should use useBlurExponentialShadowMap instead.
  65571. */
  65572. get: function () {
  65573. BABYLON.Tools.Warn("VSM are now replaced by ESM. Please use useBlurExponentialShadowMap instead.");
  65574. return this.useBlurExponentialShadowMap;
  65575. },
  65576. /**
  65577. * Sets the current filter is to blurred VSM.
  65578. * DEPRECATED. Should use useBlurExponentialShadowMap instead.
  65579. */
  65580. set: function (value) {
  65581. BABYLON.Tools.Warn("VSM are now replaced by ESM. Please use useBlurExponentialShadowMap instead.");
  65582. this.useBlurExponentialShadowMap = value;
  65583. },
  65584. enumerable: true,
  65585. configurable: true
  65586. });
  65587. Object.defineProperty(ShadowGenerator.prototype, "useExponentialShadowMap", {
  65588. /**
  65589. * Gets if the current filter is set to ESM.
  65590. */
  65591. get: function () {
  65592. return this.filter === ShadowGenerator.FILTER_EXPONENTIALSHADOWMAP;
  65593. },
  65594. /**
  65595. * Sets the current filter is to ESM.
  65596. */
  65597. set: function (value) {
  65598. if (!value && this.filter !== ShadowGenerator.FILTER_EXPONENTIALSHADOWMAP) {
  65599. return;
  65600. }
  65601. this.filter = (value ? ShadowGenerator.FILTER_EXPONENTIALSHADOWMAP : ShadowGenerator.FILTER_NONE);
  65602. },
  65603. enumerable: true,
  65604. configurable: true
  65605. });
  65606. Object.defineProperty(ShadowGenerator.prototype, "useBlurExponentialShadowMap", {
  65607. /**
  65608. * Gets if the current filter is set to filtered ESM.
  65609. */
  65610. get: function () {
  65611. return this.filter === ShadowGenerator.FILTER_BLUREXPONENTIALSHADOWMAP;
  65612. },
  65613. /**
  65614. * Gets if the current filter is set to filtered ESM.
  65615. */
  65616. set: function (value) {
  65617. if (!value && this.filter !== ShadowGenerator.FILTER_BLUREXPONENTIALSHADOWMAP) {
  65618. return;
  65619. }
  65620. this.filter = (value ? ShadowGenerator.FILTER_BLUREXPONENTIALSHADOWMAP : ShadowGenerator.FILTER_NONE);
  65621. },
  65622. enumerable: true,
  65623. configurable: true
  65624. });
  65625. Object.defineProperty(ShadowGenerator.prototype, "useCloseExponentialShadowMap", {
  65626. /**
  65627. * Gets if the current filter is set to "close ESM" (using the inverse of the
  65628. * exponential to prevent steep falloff artifacts).
  65629. */
  65630. get: function () {
  65631. return this.filter === ShadowGenerator.FILTER_CLOSEEXPONENTIALSHADOWMAP;
  65632. },
  65633. /**
  65634. * Sets the current filter to "close ESM" (using the inverse of the
  65635. * exponential to prevent steep falloff artifacts).
  65636. */
  65637. set: function (value) {
  65638. if (!value && this.filter !== ShadowGenerator.FILTER_CLOSEEXPONENTIALSHADOWMAP) {
  65639. return;
  65640. }
  65641. this.filter = (value ? ShadowGenerator.FILTER_CLOSEEXPONENTIALSHADOWMAP : ShadowGenerator.FILTER_NONE);
  65642. },
  65643. enumerable: true,
  65644. configurable: true
  65645. });
  65646. Object.defineProperty(ShadowGenerator.prototype, "useBlurCloseExponentialShadowMap", {
  65647. /**
  65648. * Gets if the current filter is set to filtered "close ESM" (using the inverse of the
  65649. * exponential to prevent steep falloff artifacts).
  65650. */
  65651. get: function () {
  65652. return this.filter === ShadowGenerator.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP;
  65653. },
  65654. /**
  65655. * Sets the current filter to filtered "close ESM" (using the inverse of the
  65656. * exponential to prevent steep falloff artifacts).
  65657. */
  65658. set: function (value) {
  65659. if (!value && this.filter !== ShadowGenerator.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP) {
  65660. return;
  65661. }
  65662. this.filter = (value ? ShadowGenerator.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP : ShadowGenerator.FILTER_NONE);
  65663. },
  65664. enumerable: true,
  65665. configurable: true
  65666. });
  65667. Object.defineProperty(ShadowGenerator.prototype, "usePercentageCloserFiltering", {
  65668. /**
  65669. * Gets if the current filter is set to "PCF" (percentage closer filtering).
  65670. */
  65671. get: function () {
  65672. return this.filter === ShadowGenerator.FILTER_PCF;
  65673. },
  65674. /**
  65675. * Sets the current filter to "PCF" (percentage closer filtering).
  65676. */
  65677. set: function (value) {
  65678. if (!value && this.filter !== ShadowGenerator.FILTER_PCF) {
  65679. return;
  65680. }
  65681. this.filter = (value ? ShadowGenerator.FILTER_PCF : ShadowGenerator.FILTER_NONE);
  65682. },
  65683. enumerable: true,
  65684. configurable: true
  65685. });
  65686. Object.defineProperty(ShadowGenerator.prototype, "filteringQuality", {
  65687. /**
  65688. * Gets the PCF or PCSS Quality.
  65689. * Only valid if usePercentageCloserFiltering or usePercentageCloserFiltering is true.
  65690. */
  65691. get: function () {
  65692. return this._filteringQuality;
  65693. },
  65694. /**
  65695. * Sets the PCF or PCSS Quality.
  65696. * Only valid if usePercentageCloserFiltering or usePercentageCloserFiltering is true.
  65697. */
  65698. set: function (filteringQuality) {
  65699. this._filteringQuality = filteringQuality;
  65700. },
  65701. enumerable: true,
  65702. configurable: true
  65703. });
  65704. Object.defineProperty(ShadowGenerator.prototype, "useContactHardeningShadow", {
  65705. /**
  65706. * Gets if the current filter is set to "PCSS" (contact hardening).
  65707. */
  65708. get: function () {
  65709. return this.filter === ShadowGenerator.FILTER_PCSS;
  65710. },
  65711. /**
  65712. * Sets the current filter to "PCSS" (contact hardening).
  65713. */
  65714. set: function (value) {
  65715. if (!value && this.filter !== ShadowGenerator.FILTER_PCSS) {
  65716. return;
  65717. }
  65718. this.filter = (value ? ShadowGenerator.FILTER_PCSS : ShadowGenerator.FILTER_NONE);
  65719. },
  65720. enumerable: true,
  65721. configurable: true
  65722. });
  65723. Object.defineProperty(ShadowGenerator.prototype, "contactHardeningLightSizeUVRatio", {
  65724. /**
  65725. * Gets the Light Size (in shadow map uv unit) used in PCSS to determine the blocker search area and the penumbra size.
  65726. * Using a ratio helps keeping shape stability independently of the map size.
  65727. *
  65728. * It does not account for the light projection as it was having too much
  65729. * instability during the light setup or during light position changes.
  65730. *
  65731. * Only valid if useContactHardeningShadow is true.
  65732. */
  65733. get: function () {
  65734. return this._contactHardeningLightSizeUVRatio;
  65735. },
  65736. /**
  65737. * Sets the Light Size (in shadow map uv unit) used in PCSS to determine the blocker search area and the penumbra size.
  65738. * Using a ratio helps keeping shape stability independently of the map size.
  65739. *
  65740. * It does not account for the light projection as it was having too much
  65741. * instability during the light setup or during light position changes.
  65742. *
  65743. * Only valid if useContactHardeningShadow is true.
  65744. */
  65745. set: function (contactHardeningLightSizeUVRatio) {
  65746. this._contactHardeningLightSizeUVRatio = contactHardeningLightSizeUVRatio;
  65747. },
  65748. enumerable: true,
  65749. configurable: true
  65750. });
  65751. /**
  65752. * Returns the darkness value (float). This can only decrease the actual darkness of a shadow.
  65753. * 0 means strongest and 1 would means no shadow.
  65754. * @returns the darkness.
  65755. */
  65756. ShadowGenerator.prototype.getDarkness = function () {
  65757. return this._darkness;
  65758. };
  65759. /**
  65760. * Sets the darkness value (float). This can only decrease the actual darkness of a shadow.
  65761. * @param darkness The darkness value 0 means strongest and 1 would means no shadow.
  65762. * @returns the shadow generator allowing fluent coding.
  65763. */
  65764. ShadowGenerator.prototype.setDarkness = function (darkness) {
  65765. if (darkness >= 1.0)
  65766. this._darkness = 1.0;
  65767. else if (darkness <= 0.0)
  65768. this._darkness = 0.0;
  65769. else
  65770. this._darkness = darkness;
  65771. return this;
  65772. };
  65773. /**
  65774. * Sets the ability to have transparent shadow (boolean).
  65775. * @param transparent True if transparent else False
  65776. * @returns the shadow generator allowing fluent coding
  65777. */
  65778. ShadowGenerator.prototype.setTransparencyShadow = function (transparent) {
  65779. this._transparencyShadow = transparent;
  65780. return this;
  65781. };
  65782. /**
  65783. * Gets the main RTT containing the shadow map (usually storing depth from the light point of view).
  65784. * @returns The render target texture if present otherwise, null
  65785. */
  65786. ShadowGenerator.prototype.getShadowMap = function () {
  65787. return this._shadowMap;
  65788. };
  65789. /**
  65790. * Gets the RTT used during rendering (can be a blurred version of the shadow map or the shadow map itself).
  65791. * @returns The render target texture if the shadow map is present otherwise, null
  65792. */
  65793. ShadowGenerator.prototype.getShadowMapForRendering = function () {
  65794. if (this._shadowMap2) {
  65795. return this._shadowMap2;
  65796. }
  65797. return this._shadowMap;
  65798. };
  65799. /**
  65800. * Helper function to add a mesh and its descendants to the list of shadow casters.
  65801. * @param mesh Mesh to add
  65802. * @param includeDescendants boolean indicating if the descendants should be added. Default to true
  65803. * @returns the Shadow Generator itself
  65804. */
  65805. ShadowGenerator.prototype.addShadowCaster = function (mesh, includeDescendants) {
  65806. if (includeDescendants === void 0) { includeDescendants = true; }
  65807. if (!this._shadowMap) {
  65808. return this;
  65809. }
  65810. if (!this._shadowMap.renderList) {
  65811. this._shadowMap.renderList = [];
  65812. }
  65813. this._shadowMap.renderList.push(mesh);
  65814. if (includeDescendants) {
  65815. (_a = this._shadowMap.renderList).push.apply(_a, mesh.getChildMeshes());
  65816. }
  65817. return this;
  65818. var _a;
  65819. };
  65820. /**
  65821. * Helper function to remove a mesh and its descendants from the list of shadow casters
  65822. * @param mesh Mesh to remove
  65823. * @param includeDescendants boolean indicating if the descendants should be removed. Default to true
  65824. * @returns the Shadow Generator itself
  65825. */
  65826. ShadowGenerator.prototype.removeShadowCaster = function (mesh, includeDescendants) {
  65827. if (includeDescendants === void 0) { includeDescendants = true; }
  65828. if (!this._shadowMap || !this._shadowMap.renderList) {
  65829. return this;
  65830. }
  65831. var index = this._shadowMap.renderList.indexOf(mesh);
  65832. if (index !== -1) {
  65833. this._shadowMap.renderList.splice(index, 1);
  65834. }
  65835. if (includeDescendants) {
  65836. for (var _i = 0, _a = mesh.getChildren(); _i < _a.length; _i++) {
  65837. var child = _a[_i];
  65838. this.removeShadowCaster(child);
  65839. }
  65840. }
  65841. return this;
  65842. };
  65843. /**
  65844. * Returns the associated light object.
  65845. * @returns the light generating the shadow
  65846. */
  65847. ShadowGenerator.prototype.getLight = function () {
  65848. return this._light;
  65849. };
  65850. ShadowGenerator.prototype._initializeGenerator = function () {
  65851. this._light._markMeshesAsLightDirty();
  65852. this._initializeShadowMap();
  65853. };
  65854. ShadowGenerator.prototype._initializeShadowMap = function () {
  65855. var _this = this;
  65856. // Render target
  65857. var engine = this._scene.getEngine();
  65858. if (engine.webGLVersion > 1) {
  65859. this._shadowMap = new BABYLON.RenderTargetTexture(this._light.name + "_shadowMap", this._mapSize, this._scene, false, true, this._textureType, this._light.needCube(), undefined, false, false);
  65860. this._shadowMap.createDepthStencilTexture(BABYLON.Engine.LESS, true);
  65861. }
  65862. else {
  65863. this._shadowMap = new BABYLON.RenderTargetTexture(this._light.name + "_shadowMap", this._mapSize, this._scene, false, true, this._textureType, this._light.needCube());
  65864. }
  65865. this._shadowMap.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  65866. this._shadowMap.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  65867. this._shadowMap.anisotropicFilteringLevel = 1;
  65868. this._shadowMap.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  65869. this._shadowMap.renderParticles = false;
  65870. this._shadowMap.ignoreCameraViewport = true;
  65871. // Record Face Index before render.
  65872. this._shadowMap.onBeforeRenderObservable.add(function (faceIndex) {
  65873. _this._currentFaceIndex = faceIndex;
  65874. if (_this._filter === ShadowGenerator.FILTER_PCF) {
  65875. engine.setColorWrite(false);
  65876. }
  65877. });
  65878. // Custom render function.
  65879. this._shadowMap.customRenderFunction = this._renderForShadowMap.bind(this);
  65880. // Blur if required afer render.
  65881. this._shadowMap.onAfterUnbindObservable.add(function () {
  65882. if (_this._filter === ShadowGenerator.FILTER_PCF) {
  65883. engine.setColorWrite(true);
  65884. }
  65885. if (!_this.useBlurExponentialShadowMap && !_this.useBlurCloseExponentialShadowMap) {
  65886. return;
  65887. }
  65888. var shadowMap = _this.getShadowMapForRendering();
  65889. if (shadowMap) {
  65890. _this._scene.postProcessManager.directRender(_this._blurPostProcesses, shadowMap.getInternalTexture(), true);
  65891. }
  65892. });
  65893. // Clear according to the chosen filter.
  65894. var clearZero = new BABYLON.Color4(0, 0, 0, 0);
  65895. var clearOne = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  65896. this._shadowMap.onClearObservable.add(function (engine) {
  65897. if (_this._filter === ShadowGenerator.FILTER_PCF) {
  65898. engine.clear(clearOne, false, true, false);
  65899. }
  65900. else if (_this.useExponentialShadowMap || _this.useBlurExponentialShadowMap) {
  65901. engine.clear(clearZero, true, true, false);
  65902. }
  65903. else {
  65904. engine.clear(clearOne, true, true, false);
  65905. }
  65906. });
  65907. };
  65908. ShadowGenerator.prototype._initializeBlurRTTAndPostProcesses = function () {
  65909. var _this = this;
  65910. var engine = this._scene.getEngine();
  65911. var targetSize = this._mapSize / this.blurScale;
  65912. if (!this.useKernelBlur || this.blurScale !== 1.0) {
  65913. this._shadowMap2 = new BABYLON.RenderTargetTexture(this._light.name + "_shadowMap2", targetSize, this._scene, false, true, this._textureType);
  65914. this._shadowMap2.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  65915. this._shadowMap2.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  65916. this._shadowMap2.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  65917. }
  65918. if (this.useKernelBlur) {
  65919. 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);
  65920. this._kernelBlurXPostprocess.width = targetSize;
  65921. this._kernelBlurXPostprocess.height = targetSize;
  65922. this._kernelBlurXPostprocess.onApplyObservable.add(function (effect) {
  65923. effect.setTexture("textureSampler", _this._shadowMap);
  65924. });
  65925. 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);
  65926. this._kernelBlurXPostprocess.autoClear = false;
  65927. this._kernelBlurYPostprocess.autoClear = false;
  65928. if (this._textureType === BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT) {
  65929. this._kernelBlurXPostprocess.packedFloat = true;
  65930. this._kernelBlurYPostprocess.packedFloat = true;
  65931. }
  65932. this._blurPostProcesses = [this._kernelBlurXPostprocess, this._kernelBlurYPostprocess];
  65933. }
  65934. else {
  65935. 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);
  65936. this._boxBlurPostprocess.onApplyObservable.add(function (effect) {
  65937. effect.setFloat2("screenSize", targetSize, targetSize);
  65938. effect.setTexture("textureSampler", _this._shadowMap);
  65939. });
  65940. this._boxBlurPostprocess.autoClear = false;
  65941. this._blurPostProcesses = [this._boxBlurPostprocess];
  65942. }
  65943. };
  65944. ShadowGenerator.prototype._renderForShadowMap = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes, depthOnlySubMeshes) {
  65945. var index;
  65946. var engine = this._scene.getEngine();
  65947. if (depthOnlySubMeshes.length) {
  65948. engine.setColorWrite(false);
  65949. for (index = 0; index < depthOnlySubMeshes.length; index++) {
  65950. this._renderSubMeshForShadowMap(depthOnlySubMeshes.data[index]);
  65951. }
  65952. engine.setColorWrite(true);
  65953. }
  65954. for (index = 0; index < opaqueSubMeshes.length; index++) {
  65955. this._renderSubMeshForShadowMap(opaqueSubMeshes.data[index]);
  65956. }
  65957. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  65958. this._renderSubMeshForShadowMap(alphaTestSubMeshes.data[index]);
  65959. }
  65960. if (this._transparencyShadow) {
  65961. for (index = 0; index < transparentSubMeshes.length; index++) {
  65962. this._renderSubMeshForShadowMap(transparentSubMeshes.data[index]);
  65963. }
  65964. }
  65965. };
  65966. ShadowGenerator.prototype._renderSubMeshForShadowMap = function (subMesh) {
  65967. var _this = this;
  65968. var mesh = subMesh.getRenderingMesh();
  65969. var scene = this._scene;
  65970. var engine = scene.getEngine();
  65971. var material = subMesh.getMaterial();
  65972. if (!material) {
  65973. return;
  65974. }
  65975. // Culling
  65976. engine.setState(material.backFaceCulling);
  65977. // Managing instances
  65978. var batch = mesh._getInstancesRenderList(subMesh._id);
  65979. if (batch.mustReturn) {
  65980. return;
  65981. }
  65982. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  65983. if (this.isReady(subMesh, hardwareInstancedRendering)) {
  65984. engine.enableEffect(this._effect);
  65985. mesh._bind(subMesh, this._effect, BABYLON.Material.TriangleFillMode);
  65986. this._effect.setFloat3("biasAndScale", this.bias, this.normalBias, this.depthScale);
  65987. this._effect.setMatrix("viewProjection", this.getTransformMatrix());
  65988. if (this.getLight().getTypeID() === BABYLON.Light.LIGHTTYPEID_DIRECTIONALLIGHT) {
  65989. this._effect.setVector3("lightData", this._cachedDirection);
  65990. }
  65991. else {
  65992. this._effect.setVector3("lightData", this._cachedPosition);
  65993. }
  65994. if (scene.activeCamera) {
  65995. this._effect.setFloat2("depthValues", this.getLight().getDepthMinZ(scene.activeCamera), this.getLight().getDepthMinZ(scene.activeCamera) + this.getLight().getDepthMaxZ(scene.activeCamera));
  65996. }
  65997. // Alpha test
  65998. if (material && material.needAlphaTesting()) {
  65999. var alphaTexture = material.getAlphaTestTexture();
  66000. if (alphaTexture) {
  66001. this._effect.setTexture("diffuseSampler", alphaTexture);
  66002. this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix() || this._defaultTextureMatrix);
  66003. }
  66004. }
  66005. // Bones
  66006. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  66007. this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices((mesh)));
  66008. }
  66009. // Morph targets
  66010. BABYLON.MaterialHelper.BindMorphTargetParameters(mesh, this._effect);
  66011. if (this.forceBackFacesOnly) {
  66012. engine.setState(true, 0, false, true);
  66013. }
  66014. // Draw
  66015. mesh._processRendering(subMesh, this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._effect.setMatrix("world", world); });
  66016. if (this.forceBackFacesOnly) {
  66017. engine.setState(true, 0, false, false);
  66018. }
  66019. }
  66020. else {
  66021. // Need to reset refresh rate of the shadowMap
  66022. if (this._shadowMap) {
  66023. this._shadowMap.resetRefreshCounter();
  66024. }
  66025. }
  66026. };
  66027. ShadowGenerator.prototype._applyFilterValues = function () {
  66028. if (!this._shadowMap) {
  66029. return;
  66030. }
  66031. if (this.filter === ShadowGenerator.FILTER_NONE || this.filter === ShadowGenerator.FILTER_PCSS) {
  66032. this._shadowMap.updateSamplingMode(BABYLON.Texture.NEAREST_SAMPLINGMODE);
  66033. }
  66034. else {
  66035. this._shadowMap.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  66036. }
  66037. };
  66038. /**
  66039. * Forces all the attached effect to compile to enable rendering only once ready vs. lazyly compiling effects.
  66040. * @param onCompiled Callback triggered at the and of the effects compilation
  66041. * @param options Sets of optional options forcing the compilation with different modes
  66042. */
  66043. ShadowGenerator.prototype.forceCompilation = function (onCompiled, options) {
  66044. var _this = this;
  66045. var localOptions = __assign({ useInstances: false }, options);
  66046. var shadowMap = this.getShadowMap();
  66047. if (!shadowMap) {
  66048. if (onCompiled) {
  66049. onCompiled(this);
  66050. }
  66051. return;
  66052. }
  66053. var renderList = shadowMap.renderList;
  66054. if (!renderList) {
  66055. if (onCompiled) {
  66056. onCompiled(this);
  66057. }
  66058. return;
  66059. }
  66060. var subMeshes = new Array();
  66061. for (var _i = 0, renderList_1 = renderList; _i < renderList_1.length; _i++) {
  66062. var mesh = renderList_1[_i];
  66063. subMeshes.push.apply(subMeshes, mesh.subMeshes);
  66064. }
  66065. if (subMeshes.length === 0) {
  66066. if (onCompiled) {
  66067. onCompiled(this);
  66068. }
  66069. return;
  66070. }
  66071. var currentIndex = 0;
  66072. var checkReady = function () {
  66073. if (!_this._scene || !_this._scene.getEngine()) {
  66074. return;
  66075. }
  66076. while (_this.isReady(subMeshes[currentIndex], localOptions.useInstances)) {
  66077. currentIndex++;
  66078. if (currentIndex >= subMeshes.length) {
  66079. if (onCompiled) {
  66080. onCompiled(_this);
  66081. }
  66082. return;
  66083. }
  66084. }
  66085. setTimeout(checkReady, 16);
  66086. };
  66087. checkReady();
  66088. };
  66089. /**
  66090. * Forces all the attached effect to compile to enable rendering only once ready vs. lazyly compiling effects.
  66091. * @param options Sets of optional options forcing the compilation with different modes
  66092. * @returns A promise that resolves when the compilation completes
  66093. */
  66094. ShadowGenerator.prototype.forceCompilationAsync = function (options) {
  66095. var _this = this;
  66096. return new Promise(function (resolve) {
  66097. _this.forceCompilation(function () {
  66098. resolve();
  66099. }, options);
  66100. });
  66101. };
  66102. /**
  66103. * Determine wheter the shadow generator is ready or not (mainly all effects and related post processes needs to be ready).
  66104. * @param subMesh The submesh we want to render in the shadow map
  66105. * @param useInstances Defines wether will draw in the map using instances
  66106. * @returns true if ready otherwise, false
  66107. */
  66108. ShadowGenerator.prototype.isReady = function (subMesh, useInstances) {
  66109. var defines = [];
  66110. if (this._textureType !== BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT) {
  66111. defines.push("#define FLOAT");
  66112. }
  66113. if (this.useExponentialShadowMap || this.useBlurExponentialShadowMap) {
  66114. defines.push("#define ESM");
  66115. }
  66116. else if (this.usePercentageCloserFiltering || this.useContactHardeningShadow) {
  66117. defines.push("#define DEPTHTEXTURE");
  66118. }
  66119. var attribs = [BABYLON.VertexBuffer.PositionKind];
  66120. var mesh = subMesh.getMesh();
  66121. var material = subMesh.getMaterial();
  66122. // Normal bias.
  66123. if (this.normalBias && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  66124. attribs.push(BABYLON.VertexBuffer.NormalKind);
  66125. defines.push("#define NORMAL");
  66126. if (mesh.nonUniformScaling) {
  66127. defines.push("#define NONUNIFORMSCALING");
  66128. }
  66129. if (this.getLight().getTypeID() === BABYLON.Light.LIGHTTYPEID_DIRECTIONALLIGHT) {
  66130. defines.push("#define DIRECTIONINLIGHTDATA");
  66131. }
  66132. }
  66133. // Alpha test
  66134. if (material && material.needAlphaTesting()) {
  66135. var alphaTexture = material.getAlphaTestTexture();
  66136. if (alphaTexture) {
  66137. defines.push("#define ALPHATEST");
  66138. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  66139. attribs.push(BABYLON.VertexBuffer.UVKind);
  66140. defines.push("#define UV1");
  66141. }
  66142. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  66143. if (alphaTexture.coordinatesIndex === 1) {
  66144. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  66145. defines.push("#define UV2");
  66146. }
  66147. }
  66148. }
  66149. }
  66150. // Bones
  66151. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  66152. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  66153. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  66154. if (mesh.numBoneInfluencers > 4) {
  66155. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  66156. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  66157. }
  66158. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  66159. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  66160. }
  66161. else {
  66162. defines.push("#define NUM_BONE_INFLUENCERS 0");
  66163. }
  66164. // Morph targets
  66165. var manager = mesh.morphTargetManager;
  66166. var morphInfluencers = 0;
  66167. if (manager) {
  66168. if (manager.numInfluencers > 0) {
  66169. defines.push("#define MORPHTARGETS");
  66170. morphInfluencers = manager.numInfluencers;
  66171. defines.push("#define NUM_MORPH_INFLUENCERS " + morphInfluencers);
  66172. BABYLON.MaterialHelper.PrepareAttributesForMorphTargets(attribs, mesh, { "NUM_MORPH_INFLUENCERS": morphInfluencers });
  66173. }
  66174. }
  66175. // Instances
  66176. if (useInstances) {
  66177. defines.push("#define INSTANCES");
  66178. attribs.push("world0");
  66179. attribs.push("world1");
  66180. attribs.push("world2");
  66181. attribs.push("world3");
  66182. }
  66183. // Get correct effect
  66184. var join = defines.join("\n");
  66185. if (this._cachedDefines !== join) {
  66186. this._cachedDefines = join;
  66187. this._effect = this._scene.getEngine().createEffect("shadowMap", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "lightData", "depthValues", "biasAndScale", "morphTargetInfluences"], ["diffuseSampler"], join, undefined, undefined, undefined, { maxSimultaneousMorphTargets: morphInfluencers });
  66188. }
  66189. if (!this._effect.isReady()) {
  66190. return false;
  66191. }
  66192. if (this.useBlurExponentialShadowMap || this.useBlurCloseExponentialShadowMap) {
  66193. if (!this._blurPostProcesses || !this._blurPostProcesses.length) {
  66194. this._initializeBlurRTTAndPostProcesses();
  66195. }
  66196. }
  66197. if (this._kernelBlurXPostprocess && !this._kernelBlurXPostprocess.isReady()) {
  66198. return false;
  66199. }
  66200. if (this._kernelBlurYPostprocess && !this._kernelBlurYPostprocess.isReady()) {
  66201. return false;
  66202. }
  66203. if (this._boxBlurPostprocess && !this._boxBlurPostprocess.isReady()) {
  66204. return false;
  66205. }
  66206. return true;
  66207. };
  66208. /**
  66209. * Prepare all the defines in a material relying on a shadow map at the specified light index.
  66210. * @param defines Defines of the material we want to update
  66211. * @param lightIndex Index of the light in the enabled light list of the material
  66212. */
  66213. ShadowGenerator.prototype.prepareDefines = function (defines, lightIndex) {
  66214. var scene = this._scene;
  66215. var light = this._light;
  66216. if (!scene.shadowsEnabled || !light.shadowEnabled) {
  66217. return;
  66218. }
  66219. defines["SHADOW" + lightIndex] = true;
  66220. if (this.useContactHardeningShadow) {
  66221. defines["SHADOWPCSS" + lightIndex] = true;
  66222. if (this._filteringQuality === ShadowGenerator.QUALITY_LOW) {
  66223. defines["SHADOWLOWQUALITY" + lightIndex] = true;
  66224. }
  66225. else if (this._filteringQuality === ShadowGenerator.QUALITY_MEDIUM) {
  66226. defines["SHADOWMEDIUMQUALITY" + lightIndex] = true;
  66227. }
  66228. // else default to high.
  66229. }
  66230. if (this.usePercentageCloserFiltering) {
  66231. defines["SHADOWPCF" + lightIndex] = true;
  66232. if (this._filteringQuality === ShadowGenerator.QUALITY_LOW) {
  66233. defines["SHADOWLOWQUALITY" + lightIndex] = true;
  66234. }
  66235. else if (this._filteringQuality === ShadowGenerator.QUALITY_MEDIUM) {
  66236. defines["SHADOWMEDIUMQUALITY" + lightIndex] = true;
  66237. }
  66238. // else default to high.
  66239. }
  66240. else if (this.usePoissonSampling) {
  66241. defines["SHADOWPOISSON" + lightIndex] = true;
  66242. }
  66243. else if (this.useExponentialShadowMap || this.useBlurExponentialShadowMap) {
  66244. defines["SHADOWESM" + lightIndex] = true;
  66245. }
  66246. else if (this.useCloseExponentialShadowMap || this.useBlurCloseExponentialShadowMap) {
  66247. defines["SHADOWCLOSEESM" + lightIndex] = true;
  66248. }
  66249. if (light.needCube()) {
  66250. defines["SHADOWCUBE" + lightIndex] = true;
  66251. }
  66252. };
  66253. /**
  66254. * Binds the shadow related information inside of an effect (information like near, far, darkness...
  66255. * defined in the generator but impacting the effect).
  66256. * @param lightIndex Index of the light in the enabled light list of the material owning the effect
  66257. * @param effect The effect we are binfing the information for
  66258. */
  66259. ShadowGenerator.prototype.bindShadowLight = function (lightIndex, effect) {
  66260. var light = this._light;
  66261. var scene = this._scene;
  66262. if (!scene.shadowsEnabled || !light.shadowEnabled) {
  66263. return;
  66264. }
  66265. var camera = scene.activeCamera;
  66266. if (!camera) {
  66267. return;
  66268. }
  66269. var shadowMap = this.getShadowMap();
  66270. if (!shadowMap) {
  66271. return;
  66272. }
  66273. if (!light.needCube()) {
  66274. effect.setMatrix("lightMatrix" + lightIndex, this.getTransformMatrix());
  66275. }
  66276. // Only PCF uses depth stencil texture.
  66277. if (this._filter === ShadowGenerator.FILTER_PCF) {
  66278. effect.setDepthStencilTexture("shadowSampler" + lightIndex, this.getShadowMapForRendering());
  66279. light._uniformBuffer.updateFloat4("shadowsInfo", this.getDarkness(), shadowMap.getSize().width, 1 / shadowMap.getSize().width, this.frustumEdgeFalloff, lightIndex);
  66280. }
  66281. else if (this._filter === ShadowGenerator.FILTER_PCSS) {
  66282. effect.setDepthStencilTexture("shadowSampler" + lightIndex, this.getShadowMapForRendering());
  66283. effect.setTexture("depthSampler" + lightIndex, this.getShadowMapForRendering());
  66284. light._uniformBuffer.updateFloat4("shadowsInfo", this.getDarkness(), 1 / shadowMap.getSize().width, this._contactHardeningLightSizeUVRatio * shadowMap.getSize().width, this.frustumEdgeFalloff, lightIndex);
  66285. }
  66286. else {
  66287. effect.setTexture("shadowSampler" + lightIndex, this.getShadowMapForRendering());
  66288. light._uniformBuffer.updateFloat4("shadowsInfo", this.getDarkness(), this.blurScale / shadowMap.getSize().width, this.depthScale, this.frustumEdgeFalloff, lightIndex);
  66289. }
  66290. light._uniformBuffer.updateFloat2("depthValues", this.getLight().getDepthMinZ(camera), this.getLight().getDepthMinZ(camera) + this.getLight().getDepthMaxZ(camera), lightIndex);
  66291. };
  66292. /**
  66293. * Gets the transformation matrix used to project the meshes into the map from the light point of view.
  66294. * (eq to shadow prjection matrix * light transform matrix)
  66295. * @returns The transform matrix used to create the shadow map
  66296. */
  66297. ShadowGenerator.prototype.getTransformMatrix = function () {
  66298. var scene = this._scene;
  66299. if (this._currentRenderID === scene.getRenderId() && this._currentFaceIndexCache === this._currentFaceIndex) {
  66300. return this._transformMatrix;
  66301. }
  66302. this._currentRenderID = scene.getRenderId();
  66303. this._currentFaceIndexCache = this._currentFaceIndex;
  66304. var lightPosition = this._light.position;
  66305. if (this._light.computeTransformedInformation()) {
  66306. lightPosition = this._light.transformedPosition;
  66307. }
  66308. BABYLON.Vector3.NormalizeToRef(this._light.getShadowDirection(this._currentFaceIndex), this._lightDirection);
  66309. if (Math.abs(BABYLON.Vector3.Dot(this._lightDirection, BABYLON.Vector3.Up())) === 1.0) {
  66310. this._lightDirection.z = 0.0000000000001; // Required to avoid perfectly perpendicular light
  66311. }
  66312. if (this._light.needProjectionMatrixCompute() || !this._cachedPosition || !this._cachedDirection || !lightPosition.equals(this._cachedPosition) || !this._lightDirection.equals(this._cachedDirection)) {
  66313. this._cachedPosition.copyFrom(lightPosition);
  66314. this._cachedDirection.copyFrom(this._lightDirection);
  66315. BABYLON.Matrix.LookAtLHToRef(lightPosition, lightPosition.add(this._lightDirection), BABYLON.Vector3.Up(), this._viewMatrix);
  66316. var shadowMap = this.getShadowMap();
  66317. if (shadowMap) {
  66318. var renderList = shadowMap.renderList;
  66319. if (renderList) {
  66320. this._light.setShadowProjectionMatrix(this._projectionMatrix, this._viewMatrix, renderList);
  66321. }
  66322. }
  66323. this._viewMatrix.multiplyToRef(this._projectionMatrix, this._transformMatrix);
  66324. }
  66325. return this._transformMatrix;
  66326. };
  66327. /**
  66328. * Recreates the shadow map dependencies like RTT and post processes. This can be used during the switch between
  66329. * Cube and 2D textures for instance.
  66330. */
  66331. ShadowGenerator.prototype.recreateShadowMap = function () {
  66332. var shadowMap = this._shadowMap;
  66333. if (!shadowMap) {
  66334. return;
  66335. }
  66336. // Track render list.
  66337. var renderList = shadowMap.renderList;
  66338. // Clean up existing data.
  66339. this._disposeRTTandPostProcesses();
  66340. // Reinitializes.
  66341. this._initializeGenerator();
  66342. // Reaffect the filter to ensure a correct fallback if necessary.
  66343. this.filter = this.filter;
  66344. // Reaffect the filter.
  66345. this._applyFilterValues();
  66346. // Reaffect Render List.
  66347. this._shadowMap.renderList = renderList;
  66348. };
  66349. ShadowGenerator.prototype._disposeBlurPostProcesses = function () {
  66350. if (this._shadowMap2) {
  66351. this._shadowMap2.dispose();
  66352. this._shadowMap2 = null;
  66353. }
  66354. if (this._boxBlurPostprocess) {
  66355. this._boxBlurPostprocess.dispose();
  66356. this._boxBlurPostprocess = null;
  66357. }
  66358. if (this._kernelBlurXPostprocess) {
  66359. this._kernelBlurXPostprocess.dispose();
  66360. this._kernelBlurXPostprocess = null;
  66361. }
  66362. if (this._kernelBlurYPostprocess) {
  66363. this._kernelBlurYPostprocess.dispose();
  66364. this._kernelBlurYPostprocess = null;
  66365. }
  66366. this._blurPostProcesses = [];
  66367. };
  66368. ShadowGenerator.prototype._disposeRTTandPostProcesses = function () {
  66369. if (this._shadowMap) {
  66370. this._shadowMap.dispose();
  66371. this._shadowMap = null;
  66372. }
  66373. this._disposeBlurPostProcesses();
  66374. };
  66375. /**
  66376. * Disposes the ShadowGenerator.
  66377. * Returns nothing.
  66378. */
  66379. ShadowGenerator.prototype.dispose = function () {
  66380. this._disposeRTTandPostProcesses();
  66381. if (this._light) {
  66382. this._light._shadowGenerator = null;
  66383. this._light._markMeshesAsLightDirty();
  66384. }
  66385. };
  66386. /**
  66387. * Serializes the shadow generator setup to a json object.
  66388. * @returns The serialized JSON object
  66389. */
  66390. ShadowGenerator.prototype.serialize = function () {
  66391. var serializationObject = {};
  66392. var shadowMap = this.getShadowMap();
  66393. if (!shadowMap) {
  66394. return serializationObject;
  66395. }
  66396. serializationObject.lightId = this._light.id;
  66397. serializationObject.mapSize = shadowMap.getRenderSize();
  66398. serializationObject.useExponentialShadowMap = this.useExponentialShadowMap;
  66399. serializationObject.useBlurExponentialShadowMap = this.useBlurExponentialShadowMap;
  66400. serializationObject.useCloseExponentialShadowMap = this.useBlurExponentialShadowMap;
  66401. serializationObject.useBlurCloseExponentialShadowMap = this.useBlurExponentialShadowMap;
  66402. serializationObject.usePoissonSampling = this.usePoissonSampling;
  66403. serializationObject.forceBackFacesOnly = this.forceBackFacesOnly;
  66404. serializationObject.depthScale = this.depthScale;
  66405. serializationObject.darkness = this.getDarkness();
  66406. serializationObject.blurBoxOffset = this.blurBoxOffset;
  66407. serializationObject.blurKernel = this.blurKernel;
  66408. serializationObject.blurScale = this.blurScale;
  66409. serializationObject.useKernelBlur = this.useKernelBlur;
  66410. serializationObject.transparencyShadow = this._transparencyShadow;
  66411. serializationObject.bias = this.bias;
  66412. serializationObject.normalBias = this.normalBias;
  66413. serializationObject.usePercentageCloserFiltering = this.usePercentageCloserFiltering;
  66414. serializationObject.useContactHardeningShadow = this.useContactHardeningShadow;
  66415. serializationObject.filteringQuality = this.filteringQuality;
  66416. serializationObject.contactHardeningLightSizeUVRatio = this.contactHardeningLightSizeUVRatio;
  66417. serializationObject.renderList = [];
  66418. if (shadowMap.renderList) {
  66419. for (var meshIndex = 0; meshIndex < shadowMap.renderList.length; meshIndex++) {
  66420. var mesh = shadowMap.renderList[meshIndex];
  66421. serializationObject.renderList.push(mesh.id);
  66422. }
  66423. }
  66424. return serializationObject;
  66425. };
  66426. /**
  66427. * Parses a serialized ShadowGenerator and returns a new ShadowGenerator.
  66428. * @param parsedShadowGenerator The JSON object to parse
  66429. * @param scene The scene to create the shadow map for
  66430. * @returns The parsed shadow generator
  66431. */
  66432. ShadowGenerator.Parse = function (parsedShadowGenerator, scene) {
  66433. //casting to point light, as light is missing the position attr and typescript complains.
  66434. var light = scene.getLightByID(parsedShadowGenerator.lightId);
  66435. var shadowGenerator = new ShadowGenerator(parsedShadowGenerator.mapSize, light);
  66436. var shadowMap = shadowGenerator.getShadowMap();
  66437. for (var meshIndex = 0; meshIndex < parsedShadowGenerator.renderList.length; meshIndex++) {
  66438. var meshes = scene.getMeshesByID(parsedShadowGenerator.renderList[meshIndex]);
  66439. meshes.forEach(function (mesh) {
  66440. if (!shadowMap) {
  66441. return;
  66442. }
  66443. if (!shadowMap.renderList) {
  66444. shadowMap.renderList = [];
  66445. }
  66446. shadowMap.renderList.push(mesh);
  66447. });
  66448. }
  66449. if (parsedShadowGenerator.usePoissonSampling) {
  66450. shadowGenerator.usePoissonSampling = true;
  66451. }
  66452. else if (parsedShadowGenerator.useExponentialShadowMap) {
  66453. shadowGenerator.useExponentialShadowMap = true;
  66454. }
  66455. else if (parsedShadowGenerator.useBlurExponentialShadowMap) {
  66456. shadowGenerator.useBlurExponentialShadowMap = true;
  66457. }
  66458. else if (parsedShadowGenerator.useCloseExponentialShadowMap) {
  66459. shadowGenerator.useCloseExponentialShadowMap = true;
  66460. }
  66461. else if (parsedShadowGenerator.useBlurCloseExponentialShadowMap) {
  66462. shadowGenerator.useBlurCloseExponentialShadowMap = true;
  66463. }
  66464. else if (parsedShadowGenerator.usePercentageCloserFiltering) {
  66465. shadowGenerator.usePercentageCloserFiltering = true;
  66466. }
  66467. else if (parsedShadowGenerator.useContactHardeningShadow) {
  66468. shadowGenerator.useContactHardeningShadow = true;
  66469. }
  66470. if (parsedShadowGenerator.filteringQuality) {
  66471. shadowGenerator.filteringQuality = parsedShadowGenerator.filteringQuality;
  66472. }
  66473. if (parsedShadowGenerator.contactHardeningLightSizeUVRatio) {
  66474. shadowGenerator.contactHardeningLightSizeUVRatio = parsedShadowGenerator.contactHardeningLightSizeUVRatio;
  66475. }
  66476. // Backward compat
  66477. else if (parsedShadowGenerator.useVarianceShadowMap) {
  66478. shadowGenerator.useExponentialShadowMap = true;
  66479. }
  66480. else if (parsedShadowGenerator.useBlurVarianceShadowMap) {
  66481. shadowGenerator.useBlurExponentialShadowMap = true;
  66482. }
  66483. if (parsedShadowGenerator.depthScale) {
  66484. shadowGenerator.depthScale = parsedShadowGenerator.depthScale;
  66485. }
  66486. if (parsedShadowGenerator.blurScale) {
  66487. shadowGenerator.blurScale = parsedShadowGenerator.blurScale;
  66488. }
  66489. if (parsedShadowGenerator.blurBoxOffset) {
  66490. shadowGenerator.blurBoxOffset = parsedShadowGenerator.blurBoxOffset;
  66491. }
  66492. if (parsedShadowGenerator.useKernelBlur) {
  66493. shadowGenerator.useKernelBlur = parsedShadowGenerator.useKernelBlur;
  66494. }
  66495. if (parsedShadowGenerator.blurKernel) {
  66496. shadowGenerator.blurKernel = parsedShadowGenerator.blurKernel;
  66497. }
  66498. if (parsedShadowGenerator.bias !== undefined) {
  66499. shadowGenerator.bias = parsedShadowGenerator.bias;
  66500. }
  66501. if (parsedShadowGenerator.normalBias !== undefined) {
  66502. shadowGenerator.normalBias = parsedShadowGenerator.normalBias;
  66503. }
  66504. if (parsedShadowGenerator.darkness) {
  66505. shadowGenerator.setDarkness(parsedShadowGenerator.darkness);
  66506. }
  66507. if (parsedShadowGenerator.transparencyShadow) {
  66508. shadowGenerator.setTransparencyShadow(true);
  66509. }
  66510. shadowGenerator.forceBackFacesOnly = parsedShadowGenerator.forceBackFacesOnly;
  66511. return shadowGenerator;
  66512. };
  66513. /**
  66514. * Shadow generator mode None: no filtering applied.
  66515. */
  66516. ShadowGenerator.FILTER_NONE = 0;
  66517. /**
  66518. * Shadow generator mode ESM: Exponential Shadow Mapping.
  66519. * (http://developer.download.nvidia.com/presentations/2008/GDC/GDC08_SoftShadowMapping.pdf)
  66520. */
  66521. ShadowGenerator.FILTER_EXPONENTIALSHADOWMAP = 1;
  66522. /**
  66523. * Shadow generator mode Poisson Sampling: Percentage Closer Filtering.
  66524. * (Multiple Tap around evenly distributed around the pixel are used to evaluate the shadow strength)
  66525. */
  66526. ShadowGenerator.FILTER_POISSONSAMPLING = 2;
  66527. /**
  66528. * Shadow generator mode ESM: Blurred Exponential Shadow Mapping.
  66529. * (http://developer.download.nvidia.com/presentations/2008/GDC/GDC08_SoftShadowMapping.pdf)
  66530. */
  66531. ShadowGenerator.FILTER_BLUREXPONENTIALSHADOWMAP = 3;
  66532. /**
  66533. * Shadow generator mode ESM: Exponential Shadow Mapping using the inverse of the exponential preventing
  66534. * edge artifacts on steep falloff.
  66535. * (http://developer.download.nvidia.com/presentations/2008/GDC/GDC08_SoftShadowMapping.pdf)
  66536. */
  66537. ShadowGenerator.FILTER_CLOSEEXPONENTIALSHADOWMAP = 4;
  66538. /**
  66539. * Shadow generator mode ESM: Blurred Exponential Shadow Mapping using the inverse of the exponential preventing
  66540. * edge artifacts on steep falloff.
  66541. * (http://developer.download.nvidia.com/presentations/2008/GDC/GDC08_SoftShadowMapping.pdf)
  66542. */
  66543. ShadowGenerator.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP = 5;
  66544. /**
  66545. * Shadow generator mode PCF: Percentage Closer Filtering
  66546. * benefits from Webgl 2 shadow samplers. Fallback to Poisson Sampling in Webgl 1
  66547. * (https://developer.nvidia.com/gpugems/GPUGems/gpugems_ch11.html)
  66548. */
  66549. ShadowGenerator.FILTER_PCF = 6;
  66550. /**
  66551. * Shadow generator mode PCSS: Percentage Closering Soft Shadow.
  66552. * benefits from Webgl 2 shadow samplers. Fallback to Poisson Sampling in Webgl 1
  66553. * Contact Hardening
  66554. */
  66555. ShadowGenerator.FILTER_PCSS = 7;
  66556. /**
  66557. * Reserved for PCF and PCSS
  66558. * Highest Quality.
  66559. *
  66560. * Execute PCF on a 5*5 kernel improving a lot the shadow aliasing artifacts.
  66561. *
  66562. * Execute PCSS with 32 taps blocker search and 64 taps PCF.
  66563. */
  66564. ShadowGenerator.QUALITY_HIGH = 0;
  66565. /**
  66566. * Reserved for PCF and PCSS
  66567. * Good tradeoff for quality/perf cross devices
  66568. *
  66569. * Execute PCF on a 3*3 kernel.
  66570. *
  66571. * Execute PCSS with 16 taps blocker search and 32 taps PCF.
  66572. */
  66573. ShadowGenerator.QUALITY_MEDIUM = 1;
  66574. /**
  66575. * Reserved for PCF and PCSS
  66576. * The lowest quality but the fastest.
  66577. *
  66578. * Execute PCF on a 1*1 kernel.
  66579. *
  66580. * Execute PCSS with 16 taps blocker search and 16 taps PCF.
  66581. */
  66582. ShadowGenerator.QUALITY_LOW = 2;
  66583. return ShadowGenerator;
  66584. }());
  66585. BABYLON.ShadowGenerator = ShadowGenerator;
  66586. })(BABYLON || (BABYLON = {}));
  66587. //# sourceMappingURL=babylon.shadowGenerator.js.map
  66588. var BABYLON;
  66589. (function (BABYLON) {
  66590. var DefaultLoadingScreen = /** @class */ (function () {
  66591. function DefaultLoadingScreen(_renderingCanvas, _loadingText, _loadingDivBackgroundColor) {
  66592. if (_loadingText === void 0) { _loadingText = ""; }
  66593. if (_loadingDivBackgroundColor === void 0) { _loadingDivBackgroundColor = "black"; }
  66594. var _this = this;
  66595. this._renderingCanvas = _renderingCanvas;
  66596. this._loadingText = _loadingText;
  66597. this._loadingDivBackgroundColor = _loadingDivBackgroundColor;
  66598. // Resize
  66599. this._resizeLoadingUI = function () {
  66600. var canvasRect = _this._renderingCanvas.getBoundingClientRect();
  66601. var canvasPositioning = window.getComputedStyle(_this._renderingCanvas).position;
  66602. if (!_this._loadingDiv) {
  66603. return;
  66604. }
  66605. _this._loadingDiv.style.position = (canvasPositioning === "fixed") ? "fixed" : "absolute";
  66606. _this._loadingDiv.style.left = canvasRect.left + "px";
  66607. _this._loadingDiv.style.top = canvasRect.top + "px";
  66608. _this._loadingDiv.style.width = canvasRect.width + "px";
  66609. _this._loadingDiv.style.height = canvasRect.height + "px";
  66610. };
  66611. }
  66612. DefaultLoadingScreen.prototype.displayLoadingUI = function () {
  66613. if (this._loadingDiv) {
  66614. // Do not add a loading screen if there is already one
  66615. return;
  66616. }
  66617. this._loadingDiv = document.createElement("div");
  66618. this._loadingDiv.id = "babylonjsLoadingDiv";
  66619. this._loadingDiv.style.opacity = "0";
  66620. this._loadingDiv.style.transition = "opacity 1.5s ease";
  66621. this._loadingDiv.style.pointerEvents = "none";
  66622. // Loading text
  66623. this._loadingTextDiv = document.createElement("div");
  66624. this._loadingTextDiv.style.position = "absolute";
  66625. this._loadingTextDiv.style.left = "0";
  66626. this._loadingTextDiv.style.top = "50%";
  66627. this._loadingTextDiv.style.marginTop = "80px";
  66628. this._loadingTextDiv.style.width = "100%";
  66629. this._loadingTextDiv.style.height = "20px";
  66630. this._loadingTextDiv.style.fontFamily = "Arial";
  66631. this._loadingTextDiv.style.fontSize = "14px";
  66632. this._loadingTextDiv.style.color = "white";
  66633. this._loadingTextDiv.style.textAlign = "center";
  66634. this._loadingTextDiv.innerHTML = "Loading";
  66635. this._loadingDiv.appendChild(this._loadingTextDiv);
  66636. //set the predefined text
  66637. this._loadingTextDiv.innerHTML = this._loadingText;
  66638. // Generating keyframes
  66639. var style = document.createElement('style');
  66640. style.type = 'text/css';
  66641. 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 }";
  66642. style.innerHTML = keyFrames;
  66643. document.getElementsByTagName('head')[0].appendChild(style);
  66644. // Loading img
  66645. var imgBack = new Image();
  66646. 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";
  66647. imgBack.style.position = "absolute";
  66648. imgBack.style.left = "50%";
  66649. imgBack.style.top = "50%";
  66650. imgBack.style.marginLeft = "-60px";
  66651. imgBack.style.marginTop = "-60px";
  66652. imgBack.style.animation = "spin1 2s infinite ease-in-out";
  66653. imgBack.style.webkitAnimation = "spin1 2s infinite ease-in-out";
  66654. imgBack.style.transformOrigin = "50% 50%";
  66655. imgBack.style.webkitTransformOrigin = "50% 50%";
  66656. this._loadingDiv.appendChild(imgBack);
  66657. this._resizeLoadingUI();
  66658. window.addEventListener("resize", this._resizeLoadingUI);
  66659. this._loadingDiv.style.backgroundColor = this._loadingDivBackgroundColor;
  66660. document.body.appendChild(this._loadingDiv);
  66661. this._loadingDiv.style.opacity = "1";
  66662. };
  66663. DefaultLoadingScreen.prototype.hideLoadingUI = function () {
  66664. var _this = this;
  66665. if (!this._loadingDiv) {
  66666. return;
  66667. }
  66668. var onTransitionEnd = function () {
  66669. if (!_this._loadingDiv) {
  66670. return;
  66671. }
  66672. document.body.removeChild(_this._loadingDiv);
  66673. window.removeEventListener("resize", _this._resizeLoadingUI);
  66674. _this._loadingDiv = null;
  66675. };
  66676. this._loadingDiv.style.opacity = "0";
  66677. this._loadingDiv.addEventListener("transitionend", onTransitionEnd);
  66678. };
  66679. Object.defineProperty(DefaultLoadingScreen.prototype, "loadingUIText", {
  66680. set: function (text) {
  66681. this._loadingText = text;
  66682. if (this._loadingTextDiv) {
  66683. this._loadingTextDiv.innerHTML = this._loadingText;
  66684. }
  66685. },
  66686. enumerable: true,
  66687. configurable: true
  66688. });
  66689. Object.defineProperty(DefaultLoadingScreen.prototype, "loadingUIBackgroundColor", {
  66690. get: function () {
  66691. return this._loadingDivBackgroundColor;
  66692. },
  66693. set: function (color) {
  66694. this._loadingDivBackgroundColor = color;
  66695. if (!this._loadingDiv) {
  66696. return;
  66697. }
  66698. this._loadingDiv.style.backgroundColor = this._loadingDivBackgroundColor;
  66699. },
  66700. enumerable: true,
  66701. configurable: true
  66702. });
  66703. return DefaultLoadingScreen;
  66704. }());
  66705. BABYLON.DefaultLoadingScreen = DefaultLoadingScreen;
  66706. })(BABYLON || (BABYLON = {}));
  66707. //# sourceMappingURL=babylon.loadingScreen.js.map
  66708. var BABYLON;
  66709. (function (BABYLON) {
  66710. var SceneLoaderProgressEvent = /** @class */ (function () {
  66711. function SceneLoaderProgressEvent(lengthComputable, loaded, total) {
  66712. this.lengthComputable = lengthComputable;
  66713. this.loaded = loaded;
  66714. this.total = total;
  66715. }
  66716. SceneLoaderProgressEvent.FromProgressEvent = function (event) {
  66717. return new SceneLoaderProgressEvent(event.lengthComputable, event.loaded, event.total);
  66718. };
  66719. return SceneLoaderProgressEvent;
  66720. }());
  66721. BABYLON.SceneLoaderProgressEvent = SceneLoaderProgressEvent;
  66722. var SceneLoader = /** @class */ (function () {
  66723. function SceneLoader() {
  66724. }
  66725. Object.defineProperty(SceneLoader, "NO_LOGGING", {
  66726. get: function () {
  66727. return 0;
  66728. },
  66729. enumerable: true,
  66730. configurable: true
  66731. });
  66732. Object.defineProperty(SceneLoader, "MINIMAL_LOGGING", {
  66733. get: function () {
  66734. return 1;
  66735. },
  66736. enumerable: true,
  66737. configurable: true
  66738. });
  66739. Object.defineProperty(SceneLoader, "SUMMARY_LOGGING", {
  66740. get: function () {
  66741. return 2;
  66742. },
  66743. enumerable: true,
  66744. configurable: true
  66745. });
  66746. Object.defineProperty(SceneLoader, "DETAILED_LOGGING", {
  66747. get: function () {
  66748. return 3;
  66749. },
  66750. enumerable: true,
  66751. configurable: true
  66752. });
  66753. Object.defineProperty(SceneLoader, "ForceFullSceneLoadingForIncremental", {
  66754. get: function () {
  66755. return SceneLoader._ForceFullSceneLoadingForIncremental;
  66756. },
  66757. set: function (value) {
  66758. SceneLoader._ForceFullSceneLoadingForIncremental = value;
  66759. },
  66760. enumerable: true,
  66761. configurable: true
  66762. });
  66763. Object.defineProperty(SceneLoader, "ShowLoadingScreen", {
  66764. get: function () {
  66765. return SceneLoader._ShowLoadingScreen;
  66766. },
  66767. set: function (value) {
  66768. SceneLoader._ShowLoadingScreen = value;
  66769. },
  66770. enumerable: true,
  66771. configurable: true
  66772. });
  66773. Object.defineProperty(SceneLoader, "loggingLevel", {
  66774. get: function () {
  66775. return SceneLoader._loggingLevel;
  66776. },
  66777. set: function (value) {
  66778. SceneLoader._loggingLevel = value;
  66779. },
  66780. enumerable: true,
  66781. configurable: true
  66782. });
  66783. Object.defineProperty(SceneLoader, "CleanBoneMatrixWeights", {
  66784. get: function () {
  66785. return SceneLoader._CleanBoneMatrixWeights;
  66786. },
  66787. set: function (value) {
  66788. SceneLoader._CleanBoneMatrixWeights = value;
  66789. },
  66790. enumerable: true,
  66791. configurable: true
  66792. });
  66793. SceneLoader._getDefaultPlugin = function () {
  66794. return SceneLoader._registeredPlugins[".babylon"];
  66795. };
  66796. SceneLoader._getPluginForExtension = function (extension) {
  66797. var registeredPlugin = SceneLoader._registeredPlugins[extension];
  66798. if (registeredPlugin) {
  66799. return registeredPlugin;
  66800. }
  66801. BABYLON.Tools.Warn("Unable to find a plugin to load " + extension + " files. Trying to use .babylon default plugin.");
  66802. return SceneLoader._getDefaultPlugin();
  66803. };
  66804. SceneLoader._getPluginForDirectLoad = function (data) {
  66805. for (var extension in SceneLoader._registeredPlugins) {
  66806. var plugin = SceneLoader._registeredPlugins[extension].plugin;
  66807. if (plugin.canDirectLoad && plugin.canDirectLoad(data)) {
  66808. return SceneLoader._registeredPlugins[extension];
  66809. }
  66810. }
  66811. return SceneLoader._getDefaultPlugin();
  66812. };
  66813. SceneLoader._getPluginForFilename = function (sceneFilename) {
  66814. if (sceneFilename.name) {
  66815. sceneFilename = sceneFilename.name;
  66816. }
  66817. var queryStringPosition = sceneFilename.indexOf("?");
  66818. if (queryStringPosition !== -1) {
  66819. sceneFilename = sceneFilename.substring(0, queryStringPosition);
  66820. }
  66821. var dotPosition = sceneFilename.lastIndexOf(".");
  66822. var extension = sceneFilename.substring(dotPosition, sceneFilename.length).toLowerCase();
  66823. return SceneLoader._getPluginForExtension(extension);
  66824. };
  66825. // use babylon file loader directly if sceneFilename is prefixed with "data:"
  66826. SceneLoader._getDirectLoad = function (sceneFilename) {
  66827. if (sceneFilename.substr && sceneFilename.substr(0, 5) === "data:") {
  66828. return sceneFilename.substr(5);
  66829. }
  66830. return null;
  66831. };
  66832. SceneLoader._loadData = function (rootUrl, sceneFilename, scene, onSuccess, onProgress, onError, onDispose, pluginExtension) {
  66833. var directLoad = SceneLoader._getDirectLoad(sceneFilename);
  66834. var registeredPlugin = pluginExtension ? SceneLoader._getPluginForExtension(pluginExtension) : (directLoad ? SceneLoader._getPluginForDirectLoad(sceneFilename) : SceneLoader._getPluginForFilename(sceneFilename));
  66835. var plugin;
  66836. if (registeredPlugin.plugin.createPlugin) {
  66837. plugin = registeredPlugin.plugin.createPlugin();
  66838. }
  66839. else {
  66840. plugin = registeredPlugin.plugin;
  66841. }
  66842. var useArrayBuffer = registeredPlugin.isBinary;
  66843. var database;
  66844. SceneLoader.OnPluginActivatedObservable.notifyObservers(plugin);
  66845. var dataCallback = function (data, responseURL) {
  66846. if (scene.isDisposed) {
  66847. onError("Scene has been disposed");
  66848. return;
  66849. }
  66850. scene.database = database;
  66851. onSuccess(plugin, data, responseURL);
  66852. };
  66853. var request = null;
  66854. var pluginDisposed = false;
  66855. var onDisposeObservable = plugin.onDisposeObservable;
  66856. if (onDisposeObservable) {
  66857. onDisposeObservable.add(function () {
  66858. pluginDisposed = true;
  66859. if (request) {
  66860. request.abort();
  66861. request = null;
  66862. }
  66863. onDispose();
  66864. });
  66865. }
  66866. var manifestChecked = function () {
  66867. if (pluginDisposed) {
  66868. return;
  66869. }
  66870. var url = rootUrl + sceneFilename;
  66871. request = BABYLON.Tools.LoadFile(url, dataCallback, onProgress ? function (event) {
  66872. onProgress(SceneLoaderProgressEvent.FromProgressEvent(event));
  66873. } : undefined, database, useArrayBuffer, function (request, exception) {
  66874. onError("Failed to load scene." + (exception ? "" : " " + exception.message), exception);
  66875. });
  66876. };
  66877. if (directLoad) {
  66878. dataCallback(directLoad);
  66879. return plugin;
  66880. }
  66881. if (rootUrl.indexOf("file:") === -1) {
  66882. var engine = scene.getEngine();
  66883. var canUseOfflineSupport = engine.enableOfflineSupport;
  66884. if (canUseOfflineSupport) {
  66885. // Also check for exceptions
  66886. var exceptionFound = false;
  66887. for (var _i = 0, _a = scene.disableOfflineSupportExceptionRules; _i < _a.length; _i++) {
  66888. var regex = _a[_i];
  66889. if (regex.test(rootUrl + sceneFilename)) {
  66890. exceptionFound = true;
  66891. break;
  66892. }
  66893. }
  66894. canUseOfflineSupport = !exceptionFound;
  66895. }
  66896. if (canUseOfflineSupport) {
  66897. // Checking if a manifest file has been set for this scene and if offline mode has been requested
  66898. database = new BABYLON.Database(rootUrl + sceneFilename, manifestChecked, engine.disableManifestCheck);
  66899. }
  66900. else {
  66901. manifestChecked();
  66902. }
  66903. }
  66904. // Loading file from disk via input file or drag'n'drop
  66905. else {
  66906. var fileOrString = sceneFilename;
  66907. if (fileOrString.name) { // File
  66908. request = BABYLON.Tools.ReadFile(fileOrString, dataCallback, onProgress, useArrayBuffer);
  66909. }
  66910. else if (BABYLON.FilesInput.FilesToLoad[sceneFilename]) {
  66911. request = BABYLON.Tools.ReadFile(BABYLON.FilesInput.FilesToLoad[sceneFilename], dataCallback, onProgress, useArrayBuffer);
  66912. }
  66913. else {
  66914. onError("Unable to find file named " + sceneFilename);
  66915. }
  66916. }
  66917. return plugin;
  66918. };
  66919. // Public functions
  66920. SceneLoader.GetPluginForExtension = function (extension) {
  66921. return SceneLoader._getPluginForExtension(extension).plugin;
  66922. };
  66923. SceneLoader.IsPluginForExtensionAvailable = function (extension) {
  66924. return !!SceneLoader._registeredPlugins[extension];
  66925. };
  66926. SceneLoader.RegisterPlugin = function (plugin) {
  66927. if (typeof plugin.extensions === "string") {
  66928. var extension = plugin.extensions;
  66929. SceneLoader._registeredPlugins[extension.toLowerCase()] = {
  66930. plugin: plugin,
  66931. isBinary: false
  66932. };
  66933. }
  66934. else {
  66935. var extensions = plugin.extensions;
  66936. Object.keys(extensions).forEach(function (extension) {
  66937. SceneLoader._registeredPlugins[extension.toLowerCase()] = {
  66938. plugin: plugin,
  66939. isBinary: extensions[extension].isBinary
  66940. };
  66941. });
  66942. }
  66943. };
  66944. /**
  66945. * Import meshes into a scene
  66946. * @param meshNames an array of mesh names, a single mesh name, or empty string for all meshes that filter what meshes are imported
  66947. * @param rootUrl a string that defines the root url for scene and resources
  66948. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  66949. * @param scene the instance of BABYLON.Scene to append to
  66950. * @param onSuccess a callback with a list of imported meshes, particleSystems, and skeletons when import succeeds
  66951. * @param onProgress a callback with a progress event for each file being loaded
  66952. * @param onError a callback with the scene, a message, and possibly an exception when import fails
  66953. * @param pluginExtension the extension used to determine the plugin
  66954. * @returns The loaded plugin
  66955. */
  66956. SceneLoader.ImportMesh = function (meshNames, rootUrl, sceneFilename, scene, onSuccess, onProgress, onError, pluginExtension) {
  66957. if (onSuccess === void 0) { onSuccess = null; }
  66958. if (onProgress === void 0) { onProgress = null; }
  66959. if (onError === void 0) { onError = null; }
  66960. if (pluginExtension === void 0) { pluginExtension = null; }
  66961. if (sceneFilename.substr && sceneFilename.substr(0, 1) === "/") {
  66962. BABYLON.Tools.Error("Wrong sceneFilename parameter");
  66963. return null;
  66964. }
  66965. var loadingToken = {};
  66966. scene._addPendingData(loadingToken);
  66967. var disposeHandler = function () {
  66968. scene._removePendingData(loadingToken);
  66969. };
  66970. var errorHandler = function (message, exception) {
  66971. var errorMessage = "Unable to import meshes from " + rootUrl + sceneFilename + ": " + message;
  66972. if (onError) {
  66973. onError(scene, errorMessage, exception);
  66974. }
  66975. else {
  66976. BABYLON.Tools.Error(errorMessage);
  66977. // should the exception be thrown?
  66978. }
  66979. disposeHandler();
  66980. };
  66981. var progressHandler = onProgress ? function (event) {
  66982. try {
  66983. onProgress(event);
  66984. }
  66985. catch (e) {
  66986. errorHandler("Error in onProgress callback", e);
  66987. }
  66988. } : undefined;
  66989. var successHandler = function (meshes, particleSystems, skeletons, animationGroups) {
  66990. scene.importedMeshesFiles.push(rootUrl + sceneFilename);
  66991. if (onSuccess) {
  66992. try {
  66993. onSuccess(meshes, particleSystems, skeletons, animationGroups);
  66994. }
  66995. catch (e) {
  66996. errorHandler("Error in onSuccess callback", e);
  66997. }
  66998. }
  66999. scene._removePendingData(loadingToken);
  67000. };
  67001. return SceneLoader._loadData(rootUrl, sceneFilename, scene, function (plugin, data, responseURL) {
  67002. if (plugin.rewriteRootURL) {
  67003. rootUrl = plugin.rewriteRootURL(rootUrl, responseURL);
  67004. }
  67005. if (sceneFilename === "") {
  67006. if (sceneFilename === "") {
  67007. rootUrl = BABYLON.Tools.GetFolderPath(rootUrl, true);
  67008. }
  67009. }
  67010. if (plugin.importMesh) {
  67011. var syncedPlugin = plugin;
  67012. var meshes = new Array();
  67013. var particleSystems = new Array();
  67014. var skeletons = new Array();
  67015. if (!syncedPlugin.importMesh(meshNames, scene, data, rootUrl, meshes, particleSystems, skeletons, errorHandler)) {
  67016. return;
  67017. }
  67018. scene.loadingPluginName = plugin.name;
  67019. successHandler(meshes, particleSystems, skeletons, []);
  67020. }
  67021. else {
  67022. var asyncedPlugin = plugin;
  67023. asyncedPlugin.importMeshAsync(meshNames, scene, data, rootUrl, progressHandler).then(function (result) {
  67024. scene.loadingPluginName = plugin.name;
  67025. successHandler(result.meshes, result.particleSystems, result.skeletons, result.animationGroups);
  67026. }).catch(function (error) {
  67027. errorHandler(error.message, error);
  67028. });
  67029. }
  67030. }, progressHandler, errorHandler, disposeHandler, pluginExtension);
  67031. };
  67032. /**
  67033. * Import meshes into a scene
  67034. * @param meshNames an array of mesh names, a single mesh name, or empty string for all meshes that filter what meshes are imported
  67035. * @param rootUrl a string that defines the root url for scene and resources
  67036. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  67037. * @param scene the instance of BABYLON.Scene to append to
  67038. * @param onProgress a callback with a progress event for each file being loaded
  67039. * @param pluginExtension the extension used to determine the plugin
  67040. * @returns The loaded list of imported meshes, particle systems, skeletons, and animation groups
  67041. */
  67042. SceneLoader.ImportMeshAsync = function (meshNames, rootUrl, sceneFilename, scene, onProgress, pluginExtension) {
  67043. if (onProgress === void 0) { onProgress = null; }
  67044. if (pluginExtension === void 0) { pluginExtension = null; }
  67045. return new Promise(function (resolve, reject) {
  67046. SceneLoader.ImportMesh(meshNames, rootUrl, sceneFilename, scene, function (meshes, particleSystems, skeletons, animationGroups) {
  67047. resolve({
  67048. meshes: meshes,
  67049. particleSystems: particleSystems,
  67050. skeletons: skeletons,
  67051. animationGroups: animationGroups
  67052. });
  67053. }, onProgress, function (scene, message, exception) {
  67054. reject(exception || new Error(message));
  67055. });
  67056. });
  67057. };
  67058. /**
  67059. * Load a scene
  67060. * @param rootUrl a string that defines the root url for scene and resources
  67061. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  67062. * @param engine is the instance of BABYLON.Engine to use to create the scene
  67063. * @param onSuccess a callback with the scene when import succeeds
  67064. * @param onProgress a callback with a progress event for each file being loaded
  67065. * @param onError a callback with the scene, a message, and possibly an exception when import fails
  67066. * @param pluginExtension the extension used to determine the plugin
  67067. * @returns The loaded plugin
  67068. */
  67069. SceneLoader.Load = function (rootUrl, sceneFilename, engine, onSuccess, onProgress, onError, pluginExtension) {
  67070. if (onSuccess === void 0) { onSuccess = null; }
  67071. if (onProgress === void 0) { onProgress = null; }
  67072. if (onError === void 0) { onError = null; }
  67073. if (pluginExtension === void 0) { pluginExtension = null; }
  67074. return SceneLoader.Append(rootUrl, sceneFilename, new BABYLON.Scene(engine), onSuccess, onProgress, onError, pluginExtension);
  67075. };
  67076. /**
  67077. * Load a scene
  67078. * @param rootUrl a string that defines the root url for scene and resources
  67079. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  67080. * @param engine is the instance of BABYLON.Engine to use to create the scene
  67081. * @param onProgress a callback with a progress event for each file being loaded
  67082. * @param pluginExtension the extension used to determine the plugin
  67083. * @returns The loaded scene
  67084. */
  67085. SceneLoader.LoadAsync = function (rootUrl, sceneFilename, engine, onProgress, pluginExtension) {
  67086. if (onProgress === void 0) { onProgress = null; }
  67087. if (pluginExtension === void 0) { pluginExtension = null; }
  67088. return new Promise(function (resolve, reject) {
  67089. SceneLoader.Load(rootUrl, sceneFilename, engine, function (scene) {
  67090. resolve(scene);
  67091. }, onProgress, function (scene, message, exception) {
  67092. reject(exception || new Error(message));
  67093. }, pluginExtension);
  67094. });
  67095. };
  67096. /**
  67097. * Append a scene
  67098. * @param rootUrl a string that defines the root url for scene and resources
  67099. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  67100. * @param scene is the instance of BABYLON.Scene to append to
  67101. * @param onSuccess a callback with the scene when import succeeds
  67102. * @param onProgress a callback with a progress event for each file being loaded
  67103. * @param onError a callback with the scene, a message, and possibly an exception when import fails
  67104. * @param pluginExtension the extension used to determine the plugin
  67105. * @returns The loaded plugin
  67106. */
  67107. SceneLoader.Append = function (rootUrl, sceneFilename, scene, onSuccess, onProgress, onError, pluginExtension) {
  67108. if (onSuccess === void 0) { onSuccess = null; }
  67109. if (onProgress === void 0) { onProgress = null; }
  67110. if (onError === void 0) { onError = null; }
  67111. if (pluginExtension === void 0) { pluginExtension = null; }
  67112. if (sceneFilename.substr && sceneFilename.substr(0, 1) === "/") {
  67113. BABYLON.Tools.Error("Wrong sceneFilename parameter");
  67114. return null;
  67115. }
  67116. if (SceneLoader.ShowLoadingScreen) {
  67117. scene.getEngine().displayLoadingUI();
  67118. }
  67119. var loadingToken = {};
  67120. scene._addPendingData(loadingToken);
  67121. var disposeHandler = function () {
  67122. scene._removePendingData(loadingToken);
  67123. scene.getEngine().hideLoadingUI();
  67124. };
  67125. var errorHandler = function (message, exception) {
  67126. var errorMessage = "Unable to load from " + rootUrl + sceneFilename + (message ? ": " + message : "");
  67127. if (onError) {
  67128. onError(scene, errorMessage, exception);
  67129. }
  67130. else {
  67131. BABYLON.Tools.Error(errorMessage);
  67132. // should the exception be thrown?
  67133. }
  67134. disposeHandler();
  67135. };
  67136. var progressHandler = onProgress ? function (event) {
  67137. try {
  67138. onProgress(event);
  67139. }
  67140. catch (e) {
  67141. errorHandler("Error in onProgress callback", e);
  67142. }
  67143. } : undefined;
  67144. var successHandler = function () {
  67145. if (onSuccess) {
  67146. try {
  67147. onSuccess(scene);
  67148. }
  67149. catch (e) {
  67150. errorHandler("Error in onSuccess callback", e);
  67151. }
  67152. }
  67153. scene._removePendingData(loadingToken);
  67154. };
  67155. return SceneLoader._loadData(rootUrl, sceneFilename, scene, function (plugin, data, responseURL) {
  67156. if (sceneFilename === "") {
  67157. rootUrl = BABYLON.Tools.GetFolderPath(rootUrl, true);
  67158. }
  67159. if (plugin.load) {
  67160. var syncedPlugin = plugin;
  67161. if (!syncedPlugin.load(scene, data, rootUrl, errorHandler)) {
  67162. return;
  67163. }
  67164. scene.loadingPluginName = plugin.name;
  67165. successHandler();
  67166. }
  67167. else {
  67168. var asyncedPlugin = plugin;
  67169. asyncedPlugin.loadAsync(scene, data, rootUrl, progressHandler).then(function () {
  67170. scene.loadingPluginName = plugin.name;
  67171. successHandler();
  67172. }).catch(function (error) {
  67173. errorHandler(error.message, error);
  67174. });
  67175. }
  67176. if (SceneLoader.ShowLoadingScreen) {
  67177. scene.executeWhenReady(function () {
  67178. scene.getEngine().hideLoadingUI();
  67179. });
  67180. }
  67181. }, progressHandler, errorHandler, disposeHandler, pluginExtension);
  67182. };
  67183. /**
  67184. * Append a scene
  67185. * @param rootUrl a string that defines the root url for scene and resources
  67186. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  67187. * @param scene is the instance of BABYLON.Scene to append to
  67188. * @param onProgress a callback with a progress event for each file being loaded
  67189. * @param pluginExtension the extension used to determine the plugin
  67190. * @returns The given scene
  67191. */
  67192. SceneLoader.AppendAsync = function (rootUrl, sceneFilename, scene, onProgress, pluginExtension) {
  67193. if (onProgress === void 0) { onProgress = null; }
  67194. if (pluginExtension === void 0) { pluginExtension = null; }
  67195. return new Promise(function (resolve, reject) {
  67196. SceneLoader.Append(rootUrl, sceneFilename, scene, function (scene) {
  67197. resolve(scene);
  67198. }, onProgress, function (scene, message, exception) {
  67199. reject(exception || new Error(message));
  67200. }, pluginExtension);
  67201. });
  67202. };
  67203. /**
  67204. * Load a scene into an asset container
  67205. * @param rootUrl a string that defines the root url for scene and resources
  67206. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  67207. * @param scene is the instance of BABYLON.Scene to append to
  67208. * @param onSuccess a callback with the scene when import succeeds
  67209. * @param onProgress a callback with a progress event for each file being loaded
  67210. * @param onError a callback with the scene, a message, and possibly an exception when import fails
  67211. * @param pluginExtension the extension used to determine the plugin
  67212. * @returns The loaded plugin
  67213. */
  67214. SceneLoader.LoadAssetContainer = function (rootUrl, sceneFilename, scene, onSuccess, onProgress, onError, pluginExtension) {
  67215. if (onSuccess === void 0) { onSuccess = null; }
  67216. if (onProgress === void 0) { onProgress = null; }
  67217. if (onError === void 0) { onError = null; }
  67218. if (pluginExtension === void 0) { pluginExtension = null; }
  67219. if (sceneFilename.substr && sceneFilename.substr(0, 1) === "/") {
  67220. BABYLON.Tools.Error("Wrong sceneFilename parameter");
  67221. return null;
  67222. }
  67223. var loadingToken = {};
  67224. scene._addPendingData(loadingToken);
  67225. var disposeHandler = function () {
  67226. scene._removePendingData(loadingToken);
  67227. };
  67228. var errorHandler = function (message, exception) {
  67229. var errorMessage = "Unable to load assets from " + rootUrl + sceneFilename + (message ? ": " + message : "");
  67230. if (onError) {
  67231. onError(scene, errorMessage, exception);
  67232. }
  67233. else {
  67234. BABYLON.Tools.Error(errorMessage);
  67235. // should the exception be thrown?
  67236. }
  67237. disposeHandler();
  67238. };
  67239. var progressHandler = onProgress ? function (event) {
  67240. try {
  67241. onProgress(event);
  67242. }
  67243. catch (e) {
  67244. errorHandler("Error in onProgress callback", e);
  67245. }
  67246. } : undefined;
  67247. var successHandler = function (assets) {
  67248. if (onSuccess) {
  67249. try {
  67250. onSuccess(assets);
  67251. }
  67252. catch (e) {
  67253. errorHandler("Error in onSuccess callback", e);
  67254. }
  67255. }
  67256. scene._removePendingData(loadingToken);
  67257. };
  67258. return SceneLoader._loadData(rootUrl, sceneFilename, scene, function (plugin, data, responseURL) {
  67259. if (plugin.loadAssetContainer) {
  67260. var syncedPlugin = plugin;
  67261. var assetContainer = syncedPlugin.loadAssetContainer(scene, data, rootUrl, errorHandler);
  67262. if (!assetContainer) {
  67263. return;
  67264. }
  67265. scene.loadingPluginName = plugin.name;
  67266. successHandler(assetContainer);
  67267. }
  67268. else if (plugin.loadAssetContainerAsync) {
  67269. var asyncedPlugin = plugin;
  67270. asyncedPlugin.loadAssetContainerAsync(scene, data, rootUrl, progressHandler).then(function (assetContainer) {
  67271. scene.loadingPluginName = plugin.name;
  67272. successHandler(assetContainer);
  67273. }).catch(function (error) {
  67274. errorHandler(error.message, error);
  67275. });
  67276. }
  67277. else {
  67278. errorHandler("LoadAssetContainer is not supported by this plugin. Plugin did not provide a loadAssetContainer or loadAssetContainerAsync method.");
  67279. }
  67280. if (SceneLoader.ShowLoadingScreen) {
  67281. scene.executeWhenReady(function () {
  67282. scene.getEngine().hideLoadingUI();
  67283. });
  67284. }
  67285. }, progressHandler, errorHandler, disposeHandler, pluginExtension);
  67286. };
  67287. /**
  67288. * Load a scene into an asset container
  67289. * @param rootUrl a string that defines the root url for scene and resources
  67290. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  67291. * @param scene is the instance of BABYLON.Scene to append to
  67292. * @param onProgress a callback with a progress event for each file being loaded
  67293. * @param pluginExtension the extension used to determine the plugin
  67294. * @returns The loaded asset container
  67295. */
  67296. SceneLoader.LoadAssetContainerAsync = function (rootUrl, sceneFilename, scene, onProgress, pluginExtension) {
  67297. if (onProgress === void 0) { onProgress = null; }
  67298. if (pluginExtension === void 0) { pluginExtension = null; }
  67299. return new Promise(function (resolve, reject) {
  67300. SceneLoader.LoadAssetContainer(rootUrl, sceneFilename, scene, function (assetContainer) {
  67301. resolve(assetContainer);
  67302. }, onProgress, function (scene, message, exception) {
  67303. reject(exception || new Error(message));
  67304. }, pluginExtension);
  67305. });
  67306. };
  67307. // Flags
  67308. SceneLoader._ForceFullSceneLoadingForIncremental = false;
  67309. SceneLoader._ShowLoadingScreen = true;
  67310. SceneLoader._CleanBoneMatrixWeights = false;
  67311. SceneLoader._loggingLevel = SceneLoader.NO_LOGGING;
  67312. // Members
  67313. SceneLoader.OnPluginActivatedObservable = new BABYLON.Observable();
  67314. SceneLoader._registeredPlugins = {};
  67315. return SceneLoader;
  67316. }());
  67317. BABYLON.SceneLoader = SceneLoader;
  67318. ;
  67319. })(BABYLON || (BABYLON = {}));
  67320. //# sourceMappingURL=babylon.sceneLoader.js.map
  67321. var BABYLON;
  67322. (function (BABYLON) {
  67323. var parseMaterialById = function (id, parsedData, scene, rootUrl) {
  67324. for (var index = 0, cache = parsedData.materials.length; index < cache; index++) {
  67325. var parsedMaterial = parsedData.materials[index];
  67326. if (parsedMaterial.id === id) {
  67327. return BABYLON.Material.Parse(parsedMaterial, scene, rootUrl);
  67328. }
  67329. }
  67330. return null;
  67331. };
  67332. var isDescendantOf = function (mesh, names, hierarchyIds) {
  67333. for (var i in names) {
  67334. if (mesh.name === names[i]) {
  67335. hierarchyIds.push(mesh.id);
  67336. return true;
  67337. }
  67338. }
  67339. if (mesh.parentId && hierarchyIds.indexOf(mesh.parentId) !== -1) {
  67340. hierarchyIds.push(mesh.id);
  67341. return true;
  67342. }
  67343. return false;
  67344. };
  67345. var logOperation = function (operation, producer) {
  67346. return operation + " of " + (producer ? producer.file + " from " + producer.name + " version: " + producer.version + ", exporter version: " + producer.exporter_version : "unknown");
  67347. };
  67348. var loadAssetContainer = function (scene, data, rootUrl, onError, addToScene) {
  67349. if (addToScene === void 0) { addToScene = false; }
  67350. var container = new BABYLON.AssetContainer(scene);
  67351. // Entire method running in try block, so ALWAYS logs as far as it got, only actually writes details
  67352. // when SceneLoader.debugLogging = true (default), or exception encountered.
  67353. // Everything stored in var log instead of writing separate lines to support only writing in exception,
  67354. // and avoid problems with multiple concurrent .babylon loads.
  67355. var log = "importScene has failed JSON parse";
  67356. try {
  67357. var parsedData = JSON.parse(data);
  67358. log = "";
  67359. var fullDetails = BABYLON.SceneLoader.loggingLevel === BABYLON.SceneLoader.DETAILED_LOGGING;
  67360. var index;
  67361. var cache;
  67362. // Lights
  67363. if (parsedData.lights !== undefined && parsedData.lights !== null) {
  67364. for (index = 0, cache = parsedData.lights.length; index < cache; index++) {
  67365. var parsedLight = parsedData.lights[index];
  67366. var light = BABYLON.Light.Parse(parsedLight, scene);
  67367. if (light) {
  67368. container.lights.push(light);
  67369. log += (index === 0 ? "\n\tLights:" : "");
  67370. log += "\n\t\t" + light.toString(fullDetails);
  67371. }
  67372. }
  67373. }
  67374. // Animations
  67375. if (parsedData.animations !== undefined && parsedData.animations !== null) {
  67376. for (index = 0, cache = parsedData.animations.length; index < cache; index++) {
  67377. var parsedAnimation = parsedData.animations[index];
  67378. var animation = BABYLON.Animation.Parse(parsedAnimation);
  67379. scene.animations.push(animation);
  67380. container.animations.push(animation);
  67381. log += (index === 0 ? "\n\tAnimations:" : "");
  67382. log += "\n\t\t" + animation.toString(fullDetails);
  67383. }
  67384. }
  67385. // Materials
  67386. if (parsedData.materials !== undefined && parsedData.materials !== null) {
  67387. for (index = 0, cache = parsedData.materials.length; index < cache; index++) {
  67388. var parsedMaterial = parsedData.materials[index];
  67389. var mat = BABYLON.Material.Parse(parsedMaterial, scene, rootUrl);
  67390. container.materials.push(mat);
  67391. log += (index === 0 ? "\n\tMaterials:" : "");
  67392. log += "\n\t\t" + mat.toString(fullDetails);
  67393. }
  67394. }
  67395. if (parsedData.multiMaterials !== undefined && parsedData.multiMaterials !== null) {
  67396. for (index = 0, cache = parsedData.multiMaterials.length; index < cache; index++) {
  67397. var parsedMultiMaterial = parsedData.multiMaterials[index];
  67398. var mmat = BABYLON.Material.ParseMultiMaterial(parsedMultiMaterial, scene);
  67399. container.multiMaterials.push(mmat);
  67400. log += (index === 0 ? "\n\tMultiMaterials:" : "");
  67401. log += "\n\t\t" + mmat.toString(fullDetails);
  67402. }
  67403. }
  67404. // Morph targets
  67405. if (parsedData.morphTargetManagers !== undefined && parsedData.morphTargetManagers !== null) {
  67406. for (var _i = 0, _a = parsedData.morphTargetManagers; _i < _a.length; _i++) {
  67407. var managerData = _a[_i];
  67408. container.morphTargetManagers.push(BABYLON.MorphTargetManager.Parse(managerData, scene));
  67409. }
  67410. }
  67411. // Skeletons
  67412. if (parsedData.skeletons !== undefined && parsedData.skeletons !== null) {
  67413. for (index = 0, cache = parsedData.skeletons.length; index < cache; index++) {
  67414. var parsedSkeleton = parsedData.skeletons[index];
  67415. var skeleton = BABYLON.Skeleton.Parse(parsedSkeleton, scene);
  67416. container.skeletons.push(skeleton);
  67417. log += (index === 0 ? "\n\tSkeletons:" : "");
  67418. log += "\n\t\t" + skeleton.toString(fullDetails);
  67419. }
  67420. }
  67421. // Geometries
  67422. var geometries = parsedData.geometries;
  67423. if (geometries !== undefined && geometries !== null) {
  67424. var addedGeometry = new Array();
  67425. // Boxes
  67426. var boxes = geometries.boxes;
  67427. if (boxes !== undefined && boxes !== null) {
  67428. for (index = 0, cache = boxes.length; index < cache; index++) {
  67429. var parsedBox = boxes[index];
  67430. addedGeometry.push(BABYLON.BoxGeometry.Parse(parsedBox, scene));
  67431. }
  67432. }
  67433. // Spheres
  67434. var spheres = geometries.spheres;
  67435. if (spheres !== undefined && spheres !== null) {
  67436. for (index = 0, cache = spheres.length; index < cache; index++) {
  67437. var parsedSphere = spheres[index];
  67438. addedGeometry.push(BABYLON.SphereGeometry.Parse(parsedSphere, scene));
  67439. }
  67440. }
  67441. // Cylinders
  67442. var cylinders = geometries.cylinders;
  67443. if (cylinders !== undefined && cylinders !== null) {
  67444. for (index = 0, cache = cylinders.length; index < cache; index++) {
  67445. var parsedCylinder = cylinders[index];
  67446. addedGeometry.push(BABYLON.CylinderGeometry.Parse(parsedCylinder, scene));
  67447. }
  67448. }
  67449. // Toruses
  67450. var toruses = geometries.toruses;
  67451. if (toruses !== undefined && toruses !== null) {
  67452. for (index = 0, cache = toruses.length; index < cache; index++) {
  67453. var parsedTorus = toruses[index];
  67454. addedGeometry.push(BABYLON.TorusGeometry.Parse(parsedTorus, scene));
  67455. }
  67456. }
  67457. // Grounds
  67458. var grounds = geometries.grounds;
  67459. if (grounds !== undefined && grounds !== null) {
  67460. for (index = 0, cache = grounds.length; index < cache; index++) {
  67461. var parsedGround = grounds[index];
  67462. addedGeometry.push(BABYLON.GroundGeometry.Parse(parsedGround, scene));
  67463. }
  67464. }
  67465. // Planes
  67466. var planes = geometries.planes;
  67467. if (planes !== undefined && planes !== null) {
  67468. for (index = 0, cache = planes.length; index < cache; index++) {
  67469. var parsedPlane = planes[index];
  67470. addedGeometry.push(BABYLON.PlaneGeometry.Parse(parsedPlane, scene));
  67471. }
  67472. }
  67473. // TorusKnots
  67474. var torusKnots = geometries.torusKnots;
  67475. if (torusKnots !== undefined && torusKnots !== null) {
  67476. for (index = 0, cache = torusKnots.length; index < cache; index++) {
  67477. var parsedTorusKnot = torusKnots[index];
  67478. addedGeometry.push(BABYLON.TorusKnotGeometry.Parse(parsedTorusKnot, scene));
  67479. }
  67480. }
  67481. // VertexData
  67482. var vertexData = geometries.vertexData;
  67483. if (vertexData !== undefined && vertexData !== null) {
  67484. for (index = 0, cache = vertexData.length; index < cache; index++) {
  67485. var parsedVertexData = vertexData[index];
  67486. addedGeometry.push(BABYLON.Geometry.Parse(parsedVertexData, scene, rootUrl));
  67487. }
  67488. }
  67489. addedGeometry.forEach(function (g) {
  67490. if (g) {
  67491. container.geometries.push(g);
  67492. }
  67493. });
  67494. }
  67495. // Transform nodes
  67496. if (parsedData.transformNodes !== undefined && parsedData.transformNodes !== null) {
  67497. for (index = 0, cache = parsedData.transformNodes.length; index < cache; index++) {
  67498. var parsedTransformNode = parsedData.transformNodes[index];
  67499. var node = BABYLON.TransformNode.Parse(parsedTransformNode, scene, rootUrl);
  67500. container.transformNodes.push(node);
  67501. }
  67502. }
  67503. // Meshes
  67504. if (parsedData.meshes !== undefined && parsedData.meshes !== null) {
  67505. for (index = 0, cache = parsedData.meshes.length; index < cache; index++) {
  67506. var parsedMesh = parsedData.meshes[index];
  67507. var mesh = BABYLON.Mesh.Parse(parsedMesh, scene, rootUrl);
  67508. container.meshes.push(mesh);
  67509. log += (index === 0 ? "\n\tMeshes:" : "");
  67510. log += "\n\t\t" + mesh.toString(fullDetails);
  67511. }
  67512. }
  67513. // Cameras
  67514. if (parsedData.cameras !== undefined && parsedData.cameras !== null) {
  67515. for (index = 0, cache = parsedData.cameras.length; index < cache; index++) {
  67516. var parsedCamera = parsedData.cameras[index];
  67517. var camera = BABYLON.Camera.Parse(parsedCamera, scene);
  67518. container.cameras.push(camera);
  67519. log += (index === 0 ? "\n\tCameras:" : "");
  67520. log += "\n\t\t" + camera.toString(fullDetails);
  67521. }
  67522. }
  67523. // Browsing all the graph to connect the dots
  67524. for (index = 0, cache = scene.cameras.length; index < cache; index++) {
  67525. var camera = scene.cameras[index];
  67526. if (camera._waitingParentId) {
  67527. camera.parent = scene.getLastEntryByID(camera._waitingParentId);
  67528. camera._waitingParentId = null;
  67529. }
  67530. }
  67531. for (index = 0, cache = scene.lights.length; index < cache; index++) {
  67532. var light_1 = scene.lights[index];
  67533. if (light_1 && light_1._waitingParentId) {
  67534. light_1.parent = scene.getLastEntryByID(light_1._waitingParentId);
  67535. light_1._waitingParentId = null;
  67536. }
  67537. }
  67538. // Sounds
  67539. // TODO: add sound
  67540. var loadedSounds = [];
  67541. var loadedSound;
  67542. if (BABYLON.AudioEngine && parsedData.sounds !== undefined && parsedData.sounds !== null) {
  67543. for (index = 0, cache = parsedData.sounds.length; index < cache; index++) {
  67544. var parsedSound = parsedData.sounds[index];
  67545. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  67546. if (!parsedSound.url)
  67547. parsedSound.url = parsedSound.name;
  67548. if (!loadedSounds[parsedSound.url]) {
  67549. loadedSound = BABYLON.Sound.Parse(parsedSound, scene, rootUrl);
  67550. loadedSounds[parsedSound.url] = loadedSound;
  67551. container.sounds.push(loadedSound);
  67552. }
  67553. else {
  67554. container.sounds.push(BABYLON.Sound.Parse(parsedSound, scene, rootUrl, loadedSounds[parsedSound.url]));
  67555. }
  67556. }
  67557. else {
  67558. container.sounds.push(new BABYLON.Sound(parsedSound.name, null, scene));
  67559. }
  67560. }
  67561. }
  67562. loadedSounds = [];
  67563. // Connect parents & children and parse actions
  67564. for (index = 0, cache = scene.transformNodes.length; index < cache; index++) {
  67565. var transformNode = scene.transformNodes[index];
  67566. if (transformNode._waitingParentId) {
  67567. transformNode.parent = scene.getLastEntryByID(transformNode._waitingParentId);
  67568. transformNode._waitingParentId = null;
  67569. }
  67570. }
  67571. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  67572. var mesh = scene.meshes[index];
  67573. if (mesh._waitingParentId) {
  67574. mesh.parent = scene.getLastEntryByID(mesh._waitingParentId);
  67575. mesh._waitingParentId = null;
  67576. }
  67577. if (mesh._waitingActions) {
  67578. BABYLON.ActionManager.Parse(mesh._waitingActions, mesh, scene);
  67579. mesh._waitingActions = null;
  67580. }
  67581. }
  67582. // freeze world matrix application
  67583. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  67584. var currentMesh = scene.meshes[index];
  67585. if (currentMesh._waitingFreezeWorldMatrix) {
  67586. currentMesh.freezeWorldMatrix();
  67587. currentMesh._waitingFreezeWorldMatrix = null;
  67588. }
  67589. else {
  67590. currentMesh.computeWorldMatrix(true);
  67591. }
  67592. }
  67593. // Particles Systems
  67594. if (parsedData.particleSystems !== undefined && parsedData.particleSystems !== null) {
  67595. for (index = 0, cache = parsedData.particleSystems.length; index < cache; index++) {
  67596. var parsedParticleSystem = parsedData.particleSystems[index];
  67597. if (parsedParticleSystem.activeParticleCount) {
  67598. var ps = BABYLON.GPUParticleSystem.Parse(parsedParticleSystem, scene, rootUrl);
  67599. container.particleSystems.push(ps);
  67600. }
  67601. else {
  67602. var ps = BABYLON.ParticleSystem.Parse(parsedParticleSystem, scene, rootUrl);
  67603. container.particleSystems.push(ps);
  67604. }
  67605. }
  67606. }
  67607. // Lens flares
  67608. if (parsedData.lensFlareSystems !== undefined && parsedData.lensFlareSystems !== null) {
  67609. for (index = 0, cache = parsedData.lensFlareSystems.length; index < cache; index++) {
  67610. var parsedLensFlareSystem = parsedData.lensFlareSystems[index];
  67611. var lf = BABYLON.LensFlareSystem.Parse(parsedLensFlareSystem, scene, rootUrl);
  67612. container.lensFlareSystems.push(lf);
  67613. }
  67614. }
  67615. // Shadows
  67616. if (parsedData.shadowGenerators !== undefined && parsedData.shadowGenerators !== null) {
  67617. for (index = 0, cache = parsedData.shadowGenerators.length; index < cache; index++) {
  67618. var parsedShadowGenerator = parsedData.shadowGenerators[index];
  67619. var sg = BABYLON.ShadowGenerator.Parse(parsedShadowGenerator, scene);
  67620. container.shadowGenerators.push(sg);
  67621. }
  67622. }
  67623. // Lights exclusions / inclusions
  67624. for (index = 0, cache = scene.lights.length; index < cache; index++) {
  67625. var light_2 = scene.lights[index];
  67626. // Excluded check
  67627. if (light_2._excludedMeshesIds.length > 0) {
  67628. for (var excludedIndex = 0; excludedIndex < light_2._excludedMeshesIds.length; excludedIndex++) {
  67629. var excludedMesh = scene.getMeshByID(light_2._excludedMeshesIds[excludedIndex]);
  67630. if (excludedMesh) {
  67631. light_2.excludedMeshes.push(excludedMesh);
  67632. }
  67633. }
  67634. light_2._excludedMeshesIds = [];
  67635. }
  67636. // Included check
  67637. if (light_2._includedOnlyMeshesIds.length > 0) {
  67638. for (var includedOnlyIndex = 0; includedOnlyIndex < light_2._includedOnlyMeshesIds.length; includedOnlyIndex++) {
  67639. var includedOnlyMesh = scene.getMeshByID(light_2._includedOnlyMeshesIds[includedOnlyIndex]);
  67640. if (includedOnlyMesh) {
  67641. light_2.includedOnlyMeshes.push(includedOnlyMesh);
  67642. }
  67643. }
  67644. light_2._includedOnlyMeshesIds = [];
  67645. }
  67646. }
  67647. // Effect layers
  67648. if (parsedData.effectLayers) {
  67649. for (index = 0; index < parsedData.effectLayers.length; index++) {
  67650. var effectLayer = BABYLON.EffectLayer.Parse(parsedData.effectLayers[index], scene, rootUrl);
  67651. container.effectLayers.push(effectLayer);
  67652. }
  67653. }
  67654. // Actions (scene)
  67655. if (parsedData.actions !== undefined && parsedData.actions !== null) {
  67656. BABYLON.ActionManager.Parse(parsedData.actions, null, scene);
  67657. }
  67658. if (!addToScene) {
  67659. container.removeAllFromScene();
  67660. }
  67661. }
  67662. catch (err) {
  67663. var msg = logOperation("loadAssts", parsedData ? parsedData.producer : "Unknown") + log;
  67664. if (onError) {
  67665. onError(msg, err);
  67666. }
  67667. else {
  67668. BABYLON.Tools.Log(msg);
  67669. throw err;
  67670. }
  67671. }
  67672. finally {
  67673. if (log !== null && BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.NO_LOGGING) {
  67674. BABYLON.Tools.Log(logOperation("loadAssts", parsedData ? parsedData.producer : "Unknown") + (BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.MINIMAL_LOGGING ? log : ""));
  67675. }
  67676. }
  67677. return container;
  67678. };
  67679. BABYLON.SceneLoader.RegisterPlugin({
  67680. name: "babylon.js",
  67681. extensions: ".babylon",
  67682. canDirectLoad: function (data) {
  67683. if (data.indexOf("babylon") !== -1) { // We consider that the producer string is filled
  67684. return true;
  67685. }
  67686. return false;
  67687. },
  67688. importMesh: function (meshesNames, scene, data, rootUrl, meshes, particleSystems, skeletons, onError) {
  67689. // Entire method running in try block, so ALWAYS logs as far as it got, only actually writes details
  67690. // when SceneLoader.debugLogging = true (default), or exception encountered.
  67691. // Everything stored in var log instead of writing separate lines to support only writing in exception,
  67692. // and avoid problems with multiple concurrent .babylon loads.
  67693. var log = "importMesh has failed JSON parse";
  67694. try {
  67695. var parsedData = JSON.parse(data);
  67696. log = "";
  67697. var fullDetails = BABYLON.SceneLoader.loggingLevel === BABYLON.SceneLoader.DETAILED_LOGGING;
  67698. if (!meshesNames) {
  67699. meshesNames = null;
  67700. }
  67701. else if (!Array.isArray(meshesNames)) {
  67702. meshesNames = [meshesNames];
  67703. }
  67704. var hierarchyIds = new Array();
  67705. if (parsedData.meshes !== undefined && parsedData.meshes !== null) {
  67706. var loadedSkeletonsIds = [];
  67707. var loadedMaterialsIds = [];
  67708. var index;
  67709. var cache;
  67710. for (index = 0, cache = parsedData.meshes.length; index < cache; index++) {
  67711. var parsedMesh = parsedData.meshes[index];
  67712. if (meshesNames === null || isDescendantOf(parsedMesh, meshesNames, hierarchyIds)) {
  67713. if (meshesNames !== null) {
  67714. // Remove found mesh name from list.
  67715. delete meshesNames[meshesNames.indexOf(parsedMesh.name)];
  67716. }
  67717. //Geometry?
  67718. if (parsedMesh.geometryId !== undefined && parsedMesh.geometryId !== null) {
  67719. //does the file contain geometries?
  67720. if (parsedData.geometries !== undefined && parsedData.geometries !== null) {
  67721. //find the correct geometry and add it to the scene
  67722. var found = false;
  67723. ["boxes", "spheres", "cylinders", "toruses", "grounds", "planes", "torusKnots", "vertexData"].forEach(function (geometryType) {
  67724. if (found === true || !parsedData.geometries[geometryType] || !(Array.isArray(parsedData.geometries[geometryType]))) {
  67725. return;
  67726. }
  67727. else {
  67728. parsedData.geometries[geometryType].forEach(function (parsedGeometryData) {
  67729. if (parsedGeometryData.id === parsedMesh.geometryId) {
  67730. switch (geometryType) {
  67731. case "boxes":
  67732. BABYLON.BoxGeometry.Parse(parsedGeometryData, scene);
  67733. break;
  67734. case "spheres":
  67735. BABYLON.SphereGeometry.Parse(parsedGeometryData, scene);
  67736. break;
  67737. case "cylinders":
  67738. BABYLON.CylinderGeometry.Parse(parsedGeometryData, scene);
  67739. break;
  67740. case "toruses":
  67741. BABYLON.TorusGeometry.Parse(parsedGeometryData, scene);
  67742. break;
  67743. case "grounds":
  67744. BABYLON.GroundGeometry.Parse(parsedGeometryData, scene);
  67745. break;
  67746. case "planes":
  67747. BABYLON.PlaneGeometry.Parse(parsedGeometryData, scene);
  67748. break;
  67749. case "torusKnots":
  67750. BABYLON.TorusKnotGeometry.Parse(parsedGeometryData, scene);
  67751. break;
  67752. case "vertexData":
  67753. BABYLON.Geometry.Parse(parsedGeometryData, scene, rootUrl);
  67754. break;
  67755. }
  67756. found = true;
  67757. }
  67758. });
  67759. }
  67760. });
  67761. if (found === false) {
  67762. BABYLON.Tools.Warn("Geometry not found for mesh " + parsedMesh.id);
  67763. }
  67764. }
  67765. }
  67766. // Material ?
  67767. if (parsedMesh.materialId) {
  67768. var materialFound = (loadedMaterialsIds.indexOf(parsedMesh.materialId) !== -1);
  67769. if (materialFound === false && parsedData.multiMaterials !== undefined && parsedData.multiMaterials !== null) {
  67770. for (var multimatIndex = 0, multimatCache = parsedData.multiMaterials.length; multimatIndex < multimatCache; multimatIndex++) {
  67771. var parsedMultiMaterial = parsedData.multiMaterials[multimatIndex];
  67772. if (parsedMultiMaterial.id === parsedMesh.materialId) {
  67773. for (var matIndex = 0, matCache = parsedMultiMaterial.materials.length; matIndex < matCache; matIndex++) {
  67774. var subMatId = parsedMultiMaterial.materials[matIndex];
  67775. loadedMaterialsIds.push(subMatId);
  67776. var mat = parseMaterialById(subMatId, parsedData, scene, rootUrl);
  67777. if (mat) {
  67778. log += "\n\tMaterial " + mat.toString(fullDetails);
  67779. }
  67780. }
  67781. loadedMaterialsIds.push(parsedMultiMaterial.id);
  67782. var mmat = BABYLON.Material.ParseMultiMaterial(parsedMultiMaterial, scene);
  67783. if (mmat) {
  67784. materialFound = true;
  67785. log += "\n\tMulti-Material " + mmat.toString(fullDetails);
  67786. }
  67787. break;
  67788. }
  67789. }
  67790. }
  67791. if (materialFound === false) {
  67792. loadedMaterialsIds.push(parsedMesh.materialId);
  67793. var mat = parseMaterialById(parsedMesh.materialId, parsedData, scene, rootUrl);
  67794. if (!mat) {
  67795. BABYLON.Tools.Warn("Material not found for mesh " + parsedMesh.id);
  67796. }
  67797. else {
  67798. log += "\n\tMaterial " + mat.toString(fullDetails);
  67799. }
  67800. }
  67801. }
  67802. // Skeleton ?
  67803. if (parsedMesh.skeletonId > -1 && parsedData.skeletons !== undefined && parsedData.skeletons !== null) {
  67804. var skeletonAlreadyLoaded = (loadedSkeletonsIds.indexOf(parsedMesh.skeletonId) > -1);
  67805. if (skeletonAlreadyLoaded === false) {
  67806. for (var skeletonIndex = 0, skeletonCache = parsedData.skeletons.length; skeletonIndex < skeletonCache; skeletonIndex++) {
  67807. var parsedSkeleton = parsedData.skeletons[skeletonIndex];
  67808. if (parsedSkeleton.id === parsedMesh.skeletonId) {
  67809. var skeleton = BABYLON.Skeleton.Parse(parsedSkeleton, scene);
  67810. skeletons.push(skeleton);
  67811. loadedSkeletonsIds.push(parsedSkeleton.id);
  67812. log += "\n\tSkeleton " + skeleton.toString(fullDetails);
  67813. }
  67814. }
  67815. }
  67816. }
  67817. // Morph targets ?
  67818. if (parsedData.morphTargetManagers !== undefined && parsedData.morphTargetManagers !== null) {
  67819. for (var _i = 0, _a = parsedData.morphTargetManagers; _i < _a.length; _i++) {
  67820. var managerData = _a[_i];
  67821. BABYLON.MorphTargetManager.Parse(managerData, scene);
  67822. }
  67823. }
  67824. var mesh = BABYLON.Mesh.Parse(parsedMesh, scene, rootUrl);
  67825. meshes.push(mesh);
  67826. log += "\n\tMesh " + mesh.toString(fullDetails);
  67827. }
  67828. }
  67829. // Connecting parents
  67830. var currentMesh;
  67831. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  67832. currentMesh = scene.meshes[index];
  67833. if (currentMesh._waitingParentId) {
  67834. currentMesh.parent = scene.getLastEntryByID(currentMesh._waitingParentId);
  67835. currentMesh._waitingParentId = null;
  67836. }
  67837. }
  67838. // freeze and compute world matrix application
  67839. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  67840. currentMesh = scene.meshes[index];
  67841. if (currentMesh._waitingFreezeWorldMatrix) {
  67842. currentMesh.freezeWorldMatrix();
  67843. currentMesh._waitingFreezeWorldMatrix = null;
  67844. }
  67845. else {
  67846. currentMesh.computeWorldMatrix(true);
  67847. }
  67848. }
  67849. }
  67850. // Particles
  67851. if (parsedData.particleSystems !== undefined && parsedData.particleSystems !== null) {
  67852. for (index = 0, cache = parsedData.particleSystems.length; index < cache; index++) {
  67853. var parsedParticleSystem = parsedData.particleSystems[index];
  67854. if (hierarchyIds.indexOf(parsedParticleSystem.emitterId) !== -1) {
  67855. particleSystems.push(BABYLON.ParticleSystem.Parse(parsedParticleSystem, scene, rootUrl));
  67856. }
  67857. }
  67858. }
  67859. return true;
  67860. }
  67861. catch (err) {
  67862. var msg = logOperation("importMesh", parsedData ? parsedData.producer : "Unknown") + log;
  67863. if (onError) {
  67864. onError(msg, err);
  67865. }
  67866. else {
  67867. BABYLON.Tools.Log(msg);
  67868. throw err;
  67869. }
  67870. }
  67871. finally {
  67872. if (log !== null && BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.NO_LOGGING) {
  67873. BABYLON.Tools.Log(logOperation("importMesh", parsedData ? parsedData.producer : "Unknown") + (BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.MINIMAL_LOGGING ? log : ""));
  67874. }
  67875. }
  67876. return false;
  67877. },
  67878. load: function (scene, data, rootUrl, onError) {
  67879. // Entire method running in try block, so ALWAYS logs as far as it got, only actually writes details
  67880. // when SceneLoader.debugLogging = true (default), or exception encountered.
  67881. // Everything stored in var log instead of writing separate lines to support only writing in exception,
  67882. // and avoid problems with multiple concurrent .babylon loads.
  67883. var log = "importScene has failed JSON parse";
  67884. try {
  67885. var parsedData = JSON.parse(data);
  67886. log = "";
  67887. // Scene
  67888. if (parsedData.useDelayedTextureLoading !== undefined && parsedData.useDelayedTextureLoading !== null) {
  67889. scene.useDelayedTextureLoading = parsedData.useDelayedTextureLoading && !BABYLON.SceneLoader.ForceFullSceneLoadingForIncremental;
  67890. }
  67891. if (parsedData.autoClear !== undefined && parsedData.autoClear !== null) {
  67892. scene.autoClear = parsedData.autoClear;
  67893. }
  67894. if (parsedData.clearColor !== undefined && parsedData.clearColor !== null) {
  67895. scene.clearColor = BABYLON.Color4.FromArray(parsedData.clearColor);
  67896. }
  67897. if (parsedData.ambientColor !== undefined && parsedData.ambientColor !== null) {
  67898. scene.ambientColor = BABYLON.Color3.FromArray(parsedData.ambientColor);
  67899. }
  67900. if (parsedData.gravity !== undefined && parsedData.gravity !== null) {
  67901. scene.gravity = BABYLON.Vector3.FromArray(parsedData.gravity);
  67902. }
  67903. // Fog
  67904. if (parsedData.fogMode && parsedData.fogMode !== 0) {
  67905. scene.fogMode = parsedData.fogMode;
  67906. scene.fogColor = BABYLON.Color3.FromArray(parsedData.fogColor);
  67907. scene.fogStart = parsedData.fogStart;
  67908. scene.fogEnd = parsedData.fogEnd;
  67909. scene.fogDensity = parsedData.fogDensity;
  67910. log += "\tFog mode for scene: ";
  67911. switch (scene.fogMode) {
  67912. // getters not compiling, so using hardcoded
  67913. case 1:
  67914. log += "exp\n";
  67915. break;
  67916. case 2:
  67917. log += "exp2\n";
  67918. break;
  67919. case 3:
  67920. log += "linear\n";
  67921. break;
  67922. }
  67923. }
  67924. //Physics
  67925. if (parsedData.physicsEnabled) {
  67926. var physicsPlugin;
  67927. if (parsedData.physicsEngine === "cannon") {
  67928. physicsPlugin = new BABYLON.CannonJSPlugin();
  67929. }
  67930. else if (parsedData.physicsEngine === "oimo") {
  67931. physicsPlugin = new BABYLON.OimoJSPlugin();
  67932. }
  67933. log = "\tPhysics engine " + (parsedData.physicsEngine ? parsedData.physicsEngine : "oimo") + " enabled\n";
  67934. //else - default engine, which is currently oimo
  67935. var physicsGravity = parsedData.physicsGravity ? BABYLON.Vector3.FromArray(parsedData.physicsGravity) : null;
  67936. scene.enablePhysics(physicsGravity, physicsPlugin);
  67937. }
  67938. // Metadata
  67939. if (parsedData.metadata !== undefined && parsedData.metadata !== null) {
  67940. scene.metadata = parsedData.metadata;
  67941. }
  67942. //collisions, if defined. otherwise, default is true
  67943. if (parsedData.collisionsEnabled !== undefined && parsedData.collisionsEnabled !== null) {
  67944. scene.collisionsEnabled = parsedData.collisionsEnabled;
  67945. }
  67946. scene.workerCollisions = !!parsedData.workerCollisions;
  67947. var container = loadAssetContainer(scene, data, rootUrl, onError, true);
  67948. if (!container) {
  67949. return false;
  67950. }
  67951. if (parsedData.autoAnimate) {
  67952. scene.beginAnimation(scene, parsedData.autoAnimateFrom, parsedData.autoAnimateTo, parsedData.autoAnimateLoop, parsedData.autoAnimateSpeed || 1.0);
  67953. }
  67954. if (parsedData.activeCameraID !== undefined && parsedData.activeCameraID !== null) {
  67955. scene.setActiveCameraByID(parsedData.activeCameraID);
  67956. }
  67957. // Environment texture
  67958. if (parsedData.environmentTexture !== undefined && parsedData.environmentTexture !== null) {
  67959. scene.environmentTexture = BABYLON.CubeTexture.CreateFromPrefilteredData(rootUrl + parsedData.environmentTexture, scene);
  67960. if (parsedData.createDefaultSkybox === true) {
  67961. var skyboxScale = (scene.activeCamera !== undefined && scene.activeCamera !== null) ? (scene.activeCamera.maxZ - scene.activeCamera.minZ) / 2 : 1000;
  67962. var skyboxBlurLevel = parsedData.skyboxBlurLevel || 0;
  67963. scene.createDefaultSkybox(undefined, true, skyboxScale, skyboxBlurLevel);
  67964. }
  67965. }
  67966. // Finish
  67967. return true;
  67968. }
  67969. catch (err) {
  67970. var msg = logOperation("importScene", parsedData ? parsedData.producer : "Unknown") + log;
  67971. if (onError) {
  67972. onError(msg, err);
  67973. }
  67974. else {
  67975. BABYLON.Tools.Log(msg);
  67976. throw err;
  67977. }
  67978. }
  67979. finally {
  67980. if (log !== null && BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.NO_LOGGING) {
  67981. BABYLON.Tools.Log(logOperation("importScene", parsedData ? parsedData.producer : "Unknown") + (BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.MINIMAL_LOGGING ? log : ""));
  67982. }
  67983. }
  67984. return false;
  67985. },
  67986. loadAssetContainer: function (scene, data, rootUrl, onError) {
  67987. var container = loadAssetContainer(scene, data, rootUrl, onError);
  67988. return container;
  67989. }
  67990. });
  67991. })(BABYLON || (BABYLON = {}));
  67992. //# sourceMappingURL=babylon.babylonFileLoader.js.map
  67993. var BABYLON;
  67994. (function (BABYLON) {
  67995. var FilesInput = /** @class */ (function () {
  67996. function FilesInput(engine, scene, sceneLoadedCallback, progressCallback, additionalRenderLoopLogicCallback, textureLoadingCallback, startingProcessingFilesCallback, onReloadCallback, errorCallback) {
  67997. this.onProcessFileCallback = function () { return true; };
  67998. this._engine = engine;
  67999. this._currentScene = scene;
  68000. this._sceneLoadedCallback = sceneLoadedCallback;
  68001. this._progressCallback = progressCallback;
  68002. this._additionalRenderLoopLogicCallback = additionalRenderLoopLogicCallback;
  68003. this._textureLoadingCallback = textureLoadingCallback;
  68004. this._startingProcessingFilesCallback = startingProcessingFilesCallback;
  68005. this._onReloadCallback = onReloadCallback;
  68006. this._errorCallback = errorCallback;
  68007. }
  68008. FilesInput.prototype.monitorElementForDragNDrop = function (elementToMonitor) {
  68009. var _this = this;
  68010. if (elementToMonitor) {
  68011. this._elementToMonitor = elementToMonitor;
  68012. this._dragEnterHandler = function (e) { _this.drag(e); };
  68013. this._dragOverHandler = function (e) { _this.drag(e); };
  68014. this._dropHandler = function (e) { _this.drop(e); };
  68015. this._elementToMonitor.addEventListener("dragenter", this._dragEnterHandler, false);
  68016. this._elementToMonitor.addEventListener("dragover", this._dragOverHandler, false);
  68017. this._elementToMonitor.addEventListener("drop", this._dropHandler, false);
  68018. }
  68019. };
  68020. FilesInput.prototype.dispose = function () {
  68021. if (!this._elementToMonitor) {
  68022. return;
  68023. }
  68024. this._elementToMonitor.removeEventListener("dragenter", this._dragEnterHandler);
  68025. this._elementToMonitor.removeEventListener("dragover", this._dragOverHandler);
  68026. this._elementToMonitor.removeEventListener("drop", this._dropHandler);
  68027. };
  68028. FilesInput.prototype.renderFunction = function () {
  68029. if (this._additionalRenderLoopLogicCallback) {
  68030. this._additionalRenderLoopLogicCallback();
  68031. }
  68032. if (this._currentScene) {
  68033. if (this._textureLoadingCallback) {
  68034. var remaining = this._currentScene.getWaitingItemsCount();
  68035. if (remaining > 0) {
  68036. this._textureLoadingCallback(remaining);
  68037. }
  68038. }
  68039. this._currentScene.render();
  68040. }
  68041. };
  68042. FilesInput.prototype.drag = function (e) {
  68043. e.stopPropagation();
  68044. e.preventDefault();
  68045. };
  68046. FilesInput.prototype.drop = function (eventDrop) {
  68047. eventDrop.stopPropagation();
  68048. eventDrop.preventDefault();
  68049. this.loadFiles(eventDrop);
  68050. };
  68051. FilesInput.prototype._traverseFolder = function (folder, files, remaining, callback) {
  68052. var _this = this;
  68053. var reader = folder.createReader();
  68054. var relativePath = folder.fullPath.replace(/^\//, "").replace(/(.+?)\/?$/, "$1/");
  68055. reader.readEntries(function (entries) {
  68056. remaining.count += entries.length;
  68057. for (var _i = 0, entries_1 = entries; _i < entries_1.length; _i++) {
  68058. var entry = entries_1[_i];
  68059. if (entry.isFile) {
  68060. entry.file(function (file) {
  68061. file.correctName = relativePath + file.name;
  68062. files.push(file);
  68063. if (--remaining.count === 0) {
  68064. callback();
  68065. }
  68066. });
  68067. }
  68068. else if (entry.isDirectory) {
  68069. _this._traverseFolder(entry, files, remaining, callback);
  68070. }
  68071. }
  68072. if (--remaining.count) {
  68073. callback();
  68074. }
  68075. });
  68076. };
  68077. FilesInput.prototype._processFiles = function (files) {
  68078. for (var i = 0; i < files.length; i++) {
  68079. var name = files[i].correctName.toLowerCase();
  68080. var extension = name.split('.').pop();
  68081. if (!this.onProcessFileCallback(files[i], name, extension)) {
  68082. continue;
  68083. }
  68084. if ((extension === "babylon" || extension === "stl" || extension === "obj" || extension === "gltf" || extension === "glb")
  68085. && name.indexOf(".binary.babylon") === -1 && name.indexOf(".incremental.babylon") === -1) {
  68086. this._sceneFileToLoad = files[i];
  68087. }
  68088. else {
  68089. FilesInput.FilesToLoad[name] = files[i];
  68090. }
  68091. }
  68092. };
  68093. FilesInput.prototype.loadFiles = function (event) {
  68094. var _this = this;
  68095. if (this._startingProcessingFilesCallback)
  68096. this._startingProcessingFilesCallback();
  68097. // Handling data transfer via drag'n'drop
  68098. if (event && event.dataTransfer && event.dataTransfer.files) {
  68099. this._filesToLoad = event.dataTransfer.files;
  68100. }
  68101. // Handling files from input files
  68102. if (event && event.target && event.target.files) {
  68103. this._filesToLoad = event.target.files;
  68104. }
  68105. if (this._filesToLoad && this._filesToLoad.length > 0) {
  68106. var files_1 = new Array();
  68107. var folders = [];
  68108. var items = event.dataTransfer ? event.dataTransfer.items : null;
  68109. for (var i = 0; i < this._filesToLoad.length; i++) {
  68110. var fileToLoad = this._filesToLoad[i];
  68111. var name_1 = fileToLoad.name.toLowerCase();
  68112. var entry = void 0;
  68113. fileToLoad.correctName = name_1;
  68114. if (items) {
  68115. var item = items[i];
  68116. if (item.getAsEntry) {
  68117. entry = item.getAsEntry();
  68118. }
  68119. else if (item.webkitGetAsEntry) {
  68120. entry = item.webkitGetAsEntry();
  68121. }
  68122. }
  68123. if (!entry) {
  68124. files_1.push(fileToLoad);
  68125. }
  68126. else {
  68127. if (entry.isDirectory) {
  68128. folders.push(entry);
  68129. }
  68130. else {
  68131. files_1.push(fileToLoad);
  68132. }
  68133. }
  68134. }
  68135. if (folders.length === 0) {
  68136. this._processFiles(files_1);
  68137. this._processReload();
  68138. }
  68139. else {
  68140. var remaining = { count: folders.length };
  68141. for (var _i = 0, folders_1 = folders; _i < folders_1.length; _i++) {
  68142. var folder = folders_1[_i];
  68143. this._traverseFolder(folder, files_1, remaining, function () {
  68144. _this._processFiles(files_1);
  68145. if (remaining.count === 0) {
  68146. _this._processReload();
  68147. }
  68148. });
  68149. }
  68150. }
  68151. }
  68152. };
  68153. FilesInput.prototype._processReload = function () {
  68154. if (this._onReloadCallback) {
  68155. this._onReloadCallback(this._sceneFileToLoad);
  68156. }
  68157. else {
  68158. this.reload();
  68159. }
  68160. };
  68161. FilesInput.prototype.reload = function () {
  68162. var _this = this;
  68163. // If a scene file has been provided
  68164. if (this._sceneFileToLoad) {
  68165. if (this._currentScene) {
  68166. if (BABYLON.Tools.errorsCount > 0) {
  68167. BABYLON.Tools.ClearLogCache();
  68168. }
  68169. this._engine.stopRenderLoop();
  68170. this._currentScene.dispose();
  68171. }
  68172. BABYLON.SceneLoader.LoadAsync("file:", this._sceneFileToLoad, this._engine, function (progress) {
  68173. if (_this._progressCallback) {
  68174. _this._progressCallback(progress);
  68175. }
  68176. }).then(function (scene) {
  68177. _this._currentScene = scene;
  68178. if (_this._sceneLoadedCallback) {
  68179. _this._sceneLoadedCallback(_this._sceneFileToLoad, _this._currentScene);
  68180. }
  68181. // Wait for textures and shaders to be ready
  68182. _this._currentScene.executeWhenReady(function () {
  68183. _this._engine.runRenderLoop(function () {
  68184. _this.renderFunction();
  68185. });
  68186. });
  68187. }).catch(function (error) {
  68188. if (_this._errorCallback) {
  68189. _this._errorCallback(_this._sceneFileToLoad, _this._currentScene, error.message);
  68190. }
  68191. });
  68192. }
  68193. else {
  68194. BABYLON.Tools.Error("Please provide a valid .babylon file.");
  68195. }
  68196. };
  68197. FilesInput.FilesToLoad = {};
  68198. return FilesInput;
  68199. }());
  68200. BABYLON.FilesInput = FilesInput;
  68201. })(BABYLON || (BABYLON = {}));
  68202. //# sourceMappingURL=babylon.filesInput.js.map
  68203. var BABYLON;
  68204. (function (BABYLON) {
  68205. /**
  68206. * This class implement a typical dictionary using a string as key and the generic type T as value.
  68207. * The underlying implementation relies on an associative array to ensure the best performances.
  68208. * The value can be anything including 'null' but except 'undefined'
  68209. */
  68210. var StringDictionary = /** @class */ (function () {
  68211. function StringDictionary() {
  68212. this._count = 0;
  68213. this._data = {};
  68214. }
  68215. /**
  68216. * This will clear this dictionary and copy the content from the 'source' one.
  68217. * If the T value is a custom object, it won't be copied/cloned, the same object will be used
  68218. * @param source the dictionary to take the content from and copy to this dictionary
  68219. */
  68220. StringDictionary.prototype.copyFrom = function (source) {
  68221. var _this = this;
  68222. this.clear();
  68223. source.forEach(function (t, v) { return _this.add(t, v); });
  68224. };
  68225. /**
  68226. * Get a value based from its key
  68227. * @param key the given key to get the matching value from
  68228. * @return the value if found, otherwise undefined is returned
  68229. */
  68230. StringDictionary.prototype.get = function (key) {
  68231. var val = this._data[key];
  68232. if (val !== undefined) {
  68233. return val;
  68234. }
  68235. return undefined;
  68236. };
  68237. /**
  68238. * Get a value from its key or add it if it doesn't exist.
  68239. * This method will ensure you that a given key/data will be present in the dictionary.
  68240. * @param key the given key to get the matching value from
  68241. * @param factory the factory that will create the value if the key is not present in the dictionary.
  68242. * The factory will only be invoked if there's no data for the given key.
  68243. * @return the value corresponding to the key.
  68244. */
  68245. StringDictionary.prototype.getOrAddWithFactory = function (key, factory) {
  68246. var val = this.get(key);
  68247. if (val !== undefined) {
  68248. return val;
  68249. }
  68250. val = factory(key);
  68251. if (val) {
  68252. this.add(key, val);
  68253. }
  68254. return val;
  68255. };
  68256. /**
  68257. * Get a value from its key if present in the dictionary otherwise add it
  68258. * @param key the key to get the value from
  68259. * @param val if there's no such key/value pair in the dictionary add it with this value
  68260. * @return the value corresponding to the key
  68261. */
  68262. StringDictionary.prototype.getOrAdd = function (key, val) {
  68263. var curVal = this.get(key);
  68264. if (curVal !== undefined) {
  68265. return curVal;
  68266. }
  68267. this.add(key, val);
  68268. return val;
  68269. };
  68270. /**
  68271. * Check if there's a given key in the dictionary
  68272. * @param key the key to check for
  68273. * @return true if the key is present, false otherwise
  68274. */
  68275. StringDictionary.prototype.contains = function (key) {
  68276. return this._data[key] !== undefined;
  68277. };
  68278. /**
  68279. * Add a new key and its corresponding value
  68280. * @param key the key to add
  68281. * @param value the value corresponding to the key
  68282. * @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
  68283. */
  68284. StringDictionary.prototype.add = function (key, value) {
  68285. if (this._data[key] !== undefined) {
  68286. return false;
  68287. }
  68288. this._data[key] = value;
  68289. ++this._count;
  68290. return true;
  68291. };
  68292. StringDictionary.prototype.set = function (key, value) {
  68293. if (this._data[key] === undefined) {
  68294. return false;
  68295. }
  68296. this._data[key] = value;
  68297. return true;
  68298. };
  68299. /**
  68300. * Get the element of the given key and remove it from the dictionary
  68301. * @param key
  68302. */
  68303. StringDictionary.prototype.getAndRemove = function (key) {
  68304. var val = this.get(key);
  68305. if (val !== undefined) {
  68306. delete this._data[key];
  68307. --this._count;
  68308. return val;
  68309. }
  68310. return null;
  68311. };
  68312. /**
  68313. * Remove a key/value from the dictionary.
  68314. * @param key the key to remove
  68315. * @return true if the item was successfully deleted, false if no item with such key exist in the dictionary
  68316. */
  68317. StringDictionary.prototype.remove = function (key) {
  68318. if (this.contains(key)) {
  68319. delete this._data[key];
  68320. --this._count;
  68321. return true;
  68322. }
  68323. return false;
  68324. };
  68325. /**
  68326. * Clear the whole content of the dictionary
  68327. */
  68328. StringDictionary.prototype.clear = function () {
  68329. this._data = {};
  68330. this._count = 0;
  68331. };
  68332. Object.defineProperty(StringDictionary.prototype, "count", {
  68333. get: function () {
  68334. return this._count;
  68335. },
  68336. enumerable: true,
  68337. configurable: true
  68338. });
  68339. /**
  68340. * Execute a callback on each key/val of the dictionary.
  68341. * Note that you can remove any element in this dictionary in the callback implementation
  68342. * @param callback the callback to execute on a given key/value pair
  68343. */
  68344. StringDictionary.prototype.forEach = function (callback) {
  68345. for (var cur in this._data) {
  68346. var val = this._data[cur];
  68347. callback(cur, val);
  68348. }
  68349. };
  68350. /**
  68351. * Execute a callback on every occurrence of the dictionary until it returns a valid TRes object.
  68352. * If the callback returns null or undefined the method will iterate to the next key/value pair
  68353. * Note that you can remove any element in this dictionary in the callback implementation
  68354. * @param callback the callback to execute, if it return a valid T instanced object the enumeration will stop and the object will be returned
  68355. */
  68356. StringDictionary.prototype.first = function (callback) {
  68357. for (var cur in this._data) {
  68358. var val = this._data[cur];
  68359. var res = callback(cur, val);
  68360. if (res) {
  68361. return res;
  68362. }
  68363. }
  68364. return null;
  68365. };
  68366. return StringDictionary;
  68367. }());
  68368. BABYLON.StringDictionary = StringDictionary;
  68369. })(BABYLON || (BABYLON = {}));
  68370. //# sourceMappingURL=babylon.stringDictionary.js.map
  68371. var BABYLON;
  68372. (function (BABYLON) {
  68373. var Tags = /** @class */ (function () {
  68374. function Tags() {
  68375. }
  68376. Tags.EnableFor = function (obj) {
  68377. obj._tags = obj._tags || {};
  68378. obj.hasTags = function () {
  68379. return Tags.HasTags(obj);
  68380. };
  68381. obj.addTags = function (tagsString) {
  68382. return Tags.AddTagsTo(obj, tagsString);
  68383. };
  68384. obj.removeTags = function (tagsString) {
  68385. return Tags.RemoveTagsFrom(obj, tagsString);
  68386. };
  68387. obj.matchesTagsQuery = function (tagsQuery) {
  68388. return Tags.MatchesQuery(obj, tagsQuery);
  68389. };
  68390. };
  68391. Tags.DisableFor = function (obj) {
  68392. delete obj._tags;
  68393. delete obj.hasTags;
  68394. delete obj.addTags;
  68395. delete obj.removeTags;
  68396. delete obj.matchesTagsQuery;
  68397. };
  68398. Tags.HasTags = function (obj) {
  68399. if (!obj._tags) {
  68400. return false;
  68401. }
  68402. return !BABYLON.Tools.IsEmpty(obj._tags);
  68403. };
  68404. Tags.GetTags = function (obj, asString) {
  68405. if (asString === void 0) { asString = true; }
  68406. if (!obj._tags) {
  68407. return null;
  68408. }
  68409. if (asString) {
  68410. var tagsArray = [];
  68411. for (var tag in obj._tags) {
  68412. if (obj._tags.hasOwnProperty(tag) && obj._tags[tag] === true) {
  68413. tagsArray.push(tag);
  68414. }
  68415. }
  68416. return tagsArray.join(" ");
  68417. }
  68418. else {
  68419. return obj._tags;
  68420. }
  68421. };
  68422. // the tags 'true' and 'false' are reserved and cannot be used as tags
  68423. // a tag cannot start with '||', '&&', and '!'
  68424. // it cannot contain whitespaces
  68425. Tags.AddTagsTo = function (obj, tagsString) {
  68426. if (!tagsString) {
  68427. return;
  68428. }
  68429. if (typeof tagsString !== "string") {
  68430. return;
  68431. }
  68432. var tags = tagsString.split(" ");
  68433. tags.forEach(function (tag, index, array) {
  68434. Tags._AddTagTo(obj, tag);
  68435. });
  68436. };
  68437. Tags._AddTagTo = function (obj, tag) {
  68438. tag = tag.trim();
  68439. if (tag === "" || tag === "true" || tag === "false") {
  68440. return;
  68441. }
  68442. if (tag.match(/[\s]/) || tag.match(/^([!]|([|]|[&]){2})/)) {
  68443. return;
  68444. }
  68445. Tags.EnableFor(obj);
  68446. obj._tags[tag] = true;
  68447. };
  68448. Tags.RemoveTagsFrom = function (obj, tagsString) {
  68449. if (!Tags.HasTags(obj)) {
  68450. return;
  68451. }
  68452. var tags = tagsString.split(" ");
  68453. for (var t in tags) {
  68454. Tags._RemoveTagFrom(obj, tags[t]);
  68455. }
  68456. };
  68457. Tags._RemoveTagFrom = function (obj, tag) {
  68458. delete obj._tags[tag];
  68459. };
  68460. Tags.MatchesQuery = function (obj, tagsQuery) {
  68461. if (tagsQuery === undefined) {
  68462. return true;
  68463. }
  68464. if (tagsQuery === "") {
  68465. return Tags.HasTags(obj);
  68466. }
  68467. return BABYLON.AndOrNotEvaluator.Eval(tagsQuery, function (r) { return Tags.HasTags(obj) && obj._tags[r]; });
  68468. };
  68469. return Tags;
  68470. }());
  68471. BABYLON.Tags = Tags;
  68472. })(BABYLON || (BABYLON = {}));
  68473. //# sourceMappingURL=babylon.tags.js.map
  68474. var BABYLON;
  68475. (function (BABYLON) {
  68476. /**
  68477. * Class used to evalaute queries containing `and` and `or` operators
  68478. */
  68479. var AndOrNotEvaluator = /** @class */ (function () {
  68480. function AndOrNotEvaluator() {
  68481. }
  68482. /**
  68483. * Evaluate a query
  68484. * @param query defines the query to evaluate
  68485. * @param evaluateCallback defines the callback used to filter result
  68486. * @returns true if the query matches
  68487. */
  68488. AndOrNotEvaluator.Eval = function (query, evaluateCallback) {
  68489. if (!query.match(/\([^\(\)]*\)/g)) {
  68490. query = AndOrNotEvaluator._HandleParenthesisContent(query, evaluateCallback);
  68491. }
  68492. else {
  68493. query = query.replace(/\([^\(\)]*\)/g, function (r) {
  68494. // remove parenthesis
  68495. r = r.slice(1, r.length - 1);
  68496. return AndOrNotEvaluator._HandleParenthesisContent(r, evaluateCallback);
  68497. });
  68498. }
  68499. if (query === "true") {
  68500. return true;
  68501. }
  68502. if (query === "false") {
  68503. return false;
  68504. }
  68505. return AndOrNotEvaluator.Eval(query, evaluateCallback);
  68506. };
  68507. AndOrNotEvaluator._HandleParenthesisContent = function (parenthesisContent, evaluateCallback) {
  68508. evaluateCallback = evaluateCallback || (function (r) {
  68509. return r === "true" ? true : false;
  68510. });
  68511. var result;
  68512. var or = parenthesisContent.split("||");
  68513. for (var i in or) {
  68514. if (or.hasOwnProperty(i)) {
  68515. var ori = AndOrNotEvaluator._SimplifyNegation(or[i].trim());
  68516. var and = ori.split("&&");
  68517. if (and.length > 1) {
  68518. for (var j = 0; j < and.length; ++j) {
  68519. var andj = AndOrNotEvaluator._SimplifyNegation(and[j].trim());
  68520. if (andj !== "true" && andj !== "false") {
  68521. if (andj[0] === "!") {
  68522. result = !evaluateCallback(andj.substring(1));
  68523. }
  68524. else {
  68525. result = evaluateCallback(andj);
  68526. }
  68527. }
  68528. else {
  68529. result = andj === "true" ? true : false;
  68530. }
  68531. if (!result) { // no need to continue since 'false && ... && ...' will always return false
  68532. ori = "false";
  68533. break;
  68534. }
  68535. }
  68536. }
  68537. if (result || ori === "true") { // no need to continue since 'true || ... || ...' will always return true
  68538. result = true;
  68539. break;
  68540. }
  68541. // result equals false (or undefined)
  68542. if (ori !== "true" && ori !== "false") {
  68543. if (ori[0] === "!") {
  68544. result = !evaluateCallback(ori.substring(1));
  68545. }
  68546. else {
  68547. result = evaluateCallback(ori);
  68548. }
  68549. }
  68550. else {
  68551. result = ori === "true" ? true : false;
  68552. }
  68553. }
  68554. }
  68555. // the whole parenthesis scope is replaced by 'true' or 'false'
  68556. return result ? "true" : "false";
  68557. };
  68558. AndOrNotEvaluator._SimplifyNegation = function (booleanString) {
  68559. booleanString = booleanString.replace(/^[\s!]+/, function (r) {
  68560. // remove whitespaces
  68561. r = r.replace(/[\s]/g, function () { return ""; });
  68562. return r.length % 2 ? "!" : "";
  68563. });
  68564. booleanString = booleanString.trim();
  68565. if (booleanString === "!true") {
  68566. booleanString = "false";
  68567. }
  68568. else if (booleanString === "!false") {
  68569. booleanString = "true";
  68570. }
  68571. return booleanString;
  68572. };
  68573. return AndOrNotEvaluator;
  68574. }());
  68575. BABYLON.AndOrNotEvaluator = AndOrNotEvaluator;
  68576. })(BABYLON || (BABYLON = {}));
  68577. //# sourceMappingURL=babylon.andOrNotEvaluator.js.map
  68578. var BABYLON;
  68579. (function (BABYLON) {
  68580. /**
  68581. * Class used to enable access to IndexedDB
  68582. * @see @https://developer.mozilla.org/en-US/docs/Web/API/IndexedDB_API
  68583. */
  68584. var Database = /** @class */ (function () {
  68585. /**
  68586. * Creates a new Database
  68587. * @param urlToScene defines the url to load the scene
  68588. * @param callbackManifestChecked defines the callback to use when manifest is checked
  68589. * @param disableManifestCheck defines a boolean indicating that we want to skip the manifest validation (it will be considered validated and up to date)
  68590. */
  68591. function Database(urlToScene, callbackManifestChecked, disableManifestCheck) {
  68592. if (disableManifestCheck === void 0) { disableManifestCheck = false; }
  68593. var _this = this;
  68594. // Handling various flavors of prefixed version of IndexedDB
  68595. this.idbFactory = (window.indexedDB || window.mozIndexedDB || window.webkitIndexedDB || window.msIndexedDB);
  68596. this.callbackManifestChecked = callbackManifestChecked;
  68597. this.currentSceneUrl = Database._ReturnFullUrlLocation(urlToScene);
  68598. this.db = null;
  68599. this._enableSceneOffline = false;
  68600. this._enableTexturesOffline = false;
  68601. this.manifestVersionFound = 0;
  68602. this.mustUpdateRessources = false;
  68603. this.hasReachedQuota = false;
  68604. if (!Database.IDBStorageEnabled) {
  68605. this.callbackManifestChecked(true);
  68606. }
  68607. else {
  68608. if (disableManifestCheck) {
  68609. this._enableSceneOffline = true;
  68610. this._enableTexturesOffline = true;
  68611. this.manifestVersionFound = 1;
  68612. BABYLON.Tools.SetImmediate(function () {
  68613. _this.callbackManifestChecked(true);
  68614. });
  68615. }
  68616. else {
  68617. this._checkManifestFile();
  68618. }
  68619. }
  68620. }
  68621. Object.defineProperty(Database.prototype, "enableSceneOffline", {
  68622. /**
  68623. * Gets a boolean indicating if scene must be saved in the database
  68624. */
  68625. get: function () {
  68626. return this._enableSceneOffline;
  68627. },
  68628. enumerable: true,
  68629. configurable: true
  68630. });
  68631. Object.defineProperty(Database.prototype, "enableTexturesOffline", {
  68632. /**
  68633. * Gets a boolean indicating if textures must be saved in the database
  68634. */
  68635. get: function () {
  68636. return this._enableTexturesOffline;
  68637. },
  68638. enumerable: true,
  68639. configurable: true
  68640. });
  68641. Database.prototype._checkManifestFile = function () {
  68642. var _this = this;
  68643. var noManifestFile = function () {
  68644. _this._enableSceneOffline = false;
  68645. _this._enableTexturesOffline = false;
  68646. _this.callbackManifestChecked(false);
  68647. };
  68648. var timeStampUsed = false;
  68649. var manifestURL = this.currentSceneUrl + ".manifest";
  68650. var xhr = new XMLHttpRequest();
  68651. if (navigator.onLine) {
  68652. // Adding a timestamp to by-pass browsers' cache
  68653. timeStampUsed = true;
  68654. manifestURL = manifestURL + (manifestURL.match(/\?/) == null ? "?" : "&") + Date.now();
  68655. }
  68656. xhr.open("GET", manifestURL, true);
  68657. xhr.addEventListener("load", function () {
  68658. if (xhr.status === 200 || BABYLON.Tools.ValidateXHRData(xhr, 1)) {
  68659. try {
  68660. var manifestFile = JSON.parse(xhr.response);
  68661. _this._enableSceneOffline = manifestFile.enableSceneOffline;
  68662. _this._enableTexturesOffline = manifestFile.enableTexturesOffline;
  68663. if (manifestFile.version && !isNaN(parseInt(manifestFile.version))) {
  68664. _this.manifestVersionFound = manifestFile.version;
  68665. }
  68666. if (_this.callbackManifestChecked) {
  68667. _this.callbackManifestChecked(true);
  68668. }
  68669. }
  68670. catch (ex) {
  68671. noManifestFile();
  68672. }
  68673. }
  68674. else {
  68675. noManifestFile();
  68676. }
  68677. }, false);
  68678. xhr.addEventListener("error", function (event) {
  68679. if (timeStampUsed) {
  68680. timeStampUsed = false;
  68681. // Let's retry without the timeStamp
  68682. // It could fail when coupled with HTML5 Offline API
  68683. var retryManifestURL = _this.currentSceneUrl + ".manifest";
  68684. xhr.open("GET", retryManifestURL, true);
  68685. xhr.send();
  68686. }
  68687. else {
  68688. noManifestFile();
  68689. }
  68690. }, false);
  68691. try {
  68692. xhr.send();
  68693. }
  68694. catch (ex) {
  68695. BABYLON.Tools.Error("Error on XHR send request.");
  68696. this.callbackManifestChecked(false);
  68697. }
  68698. };
  68699. /**
  68700. * Open the database and make it available
  68701. * @param successCallback defines the callback to call on success
  68702. * @param errorCallback defines the callback to call on error
  68703. */
  68704. Database.prototype.openAsync = function (successCallback, errorCallback) {
  68705. var _this = this;
  68706. var handleError = function () {
  68707. _this.isSupported = false;
  68708. if (errorCallback)
  68709. errorCallback();
  68710. };
  68711. if (!this.idbFactory || !(this._enableSceneOffline || this._enableTexturesOffline)) {
  68712. // Your browser doesn't support IndexedDB
  68713. this.isSupported = false;
  68714. if (errorCallback)
  68715. errorCallback();
  68716. }
  68717. else {
  68718. // If the DB hasn't been opened or created yet
  68719. if (!this.db) {
  68720. this.hasReachedQuota = false;
  68721. this.isSupported = true;
  68722. var request = this.idbFactory.open("babylonjs", 1);
  68723. // Could occur if user is blocking the quota for the DB and/or doesn't grant access to IndexedDB
  68724. request.onerror = function (event) {
  68725. handleError();
  68726. };
  68727. // executes when a version change transaction cannot complete due to other active transactions
  68728. request.onblocked = function (event) {
  68729. BABYLON.Tools.Error("IDB request blocked. Please reload the page.");
  68730. handleError();
  68731. };
  68732. // DB has been opened successfully
  68733. request.onsuccess = function (event) {
  68734. _this.db = request.result;
  68735. successCallback();
  68736. };
  68737. // Initialization of the DB. Creating Scenes & Textures stores
  68738. request.onupgradeneeded = function (event) {
  68739. _this.db = (event.target).result;
  68740. if (_this.db) {
  68741. try {
  68742. _this.db.createObjectStore("scenes", { keyPath: "sceneUrl" });
  68743. _this.db.createObjectStore("versions", { keyPath: "sceneUrl" });
  68744. _this.db.createObjectStore("textures", { keyPath: "textureUrl" });
  68745. }
  68746. catch (ex) {
  68747. BABYLON.Tools.Error("Error while creating object stores. Exception: " + ex.message);
  68748. handleError();
  68749. }
  68750. }
  68751. };
  68752. }
  68753. // DB has already been created and opened
  68754. else {
  68755. if (successCallback)
  68756. successCallback();
  68757. }
  68758. }
  68759. };
  68760. /**
  68761. * Loads an image from the database
  68762. * @param url defines the url to load from
  68763. * @param image defines the target DOM image
  68764. */
  68765. Database.prototype.loadImageFromDB = function (url, image) {
  68766. var _this = this;
  68767. var completeURL = Database._ReturnFullUrlLocation(url);
  68768. var saveAndLoadImage = function () {
  68769. if (!_this.hasReachedQuota && _this.db !== null) {
  68770. // the texture is not yet in the DB, let's try to save it
  68771. _this._saveImageIntoDBAsync(completeURL, image);
  68772. }
  68773. // If the texture is not in the DB and we've reached the DB quota limit
  68774. // let's load it directly from the web
  68775. else {
  68776. image.src = url;
  68777. }
  68778. };
  68779. if (!this.mustUpdateRessources) {
  68780. this._loadImageFromDBAsync(completeURL, image, saveAndLoadImage);
  68781. }
  68782. // First time we're download the images or update requested in the manifest file by a version change
  68783. else {
  68784. saveAndLoadImage();
  68785. }
  68786. };
  68787. Database.prototype._loadImageFromDBAsync = function (url, image, notInDBCallback) {
  68788. if (this.isSupported && this.db !== null) {
  68789. var texture;
  68790. var transaction = this.db.transaction(["textures"]);
  68791. transaction.onabort = function (event) {
  68792. image.src = url;
  68793. };
  68794. transaction.oncomplete = function (event) {
  68795. var blobTextureURL;
  68796. if (texture) {
  68797. var URL = window.URL || window.webkitURL;
  68798. blobTextureURL = URL.createObjectURL(texture.data, { oneTimeOnly: true });
  68799. image.onerror = function () {
  68800. BABYLON.Tools.Error("Error loading image from blob URL: " + blobTextureURL + " switching back to web url: " + url);
  68801. image.src = url;
  68802. };
  68803. image.src = blobTextureURL;
  68804. }
  68805. else {
  68806. notInDBCallback();
  68807. }
  68808. };
  68809. var getRequest = transaction.objectStore("textures").get(url);
  68810. getRequest.onsuccess = function (event) {
  68811. texture = (event.target).result;
  68812. };
  68813. getRequest.onerror = function (event) {
  68814. BABYLON.Tools.Error("Error loading texture " + url + " from DB.");
  68815. image.src = url;
  68816. };
  68817. }
  68818. else {
  68819. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  68820. image.src = url;
  68821. }
  68822. };
  68823. Database.prototype._saveImageIntoDBAsync = function (url, image) {
  68824. var _this = this;
  68825. if (this.isSupported) {
  68826. // In case of error (type not supported or quota exceeded), we're at least sending back XHR data to allow texture loading later on
  68827. var generateBlobUrl = function () {
  68828. var blobTextureURL;
  68829. if (blob) {
  68830. var URL = window.URL || window.webkitURL;
  68831. try {
  68832. blobTextureURL = URL.createObjectURL(blob, { oneTimeOnly: true });
  68833. }
  68834. // Chrome is raising a type error if we're setting the oneTimeOnly parameter
  68835. catch (ex) {
  68836. blobTextureURL = URL.createObjectURL(blob);
  68837. }
  68838. }
  68839. if (blobTextureURL) {
  68840. image.src = blobTextureURL;
  68841. }
  68842. };
  68843. if (Database.IsUASupportingBlobStorage) { // Create XHR
  68844. var xhr = new XMLHttpRequest(), blob;
  68845. xhr.open("GET", url, true);
  68846. xhr.responseType = "blob";
  68847. xhr.addEventListener("load", function () {
  68848. if (xhr.status === 200 && _this.db) {
  68849. // Blob as response (XHR2)
  68850. blob = xhr.response;
  68851. var transaction = _this.db.transaction(["textures"], "readwrite");
  68852. // the transaction could abort because of a QuotaExceededError error
  68853. transaction.onabort = function (event) {
  68854. try {
  68855. //backwards compatibility with ts 1.0, srcElement doesn't have an "error" according to ts 1.3
  68856. var srcElement = (event.srcElement || event.target);
  68857. var error = srcElement.error;
  68858. if (error && error.name === "QuotaExceededError") {
  68859. _this.hasReachedQuota = true;
  68860. }
  68861. }
  68862. catch (ex) { }
  68863. generateBlobUrl();
  68864. };
  68865. transaction.oncomplete = function (event) {
  68866. generateBlobUrl();
  68867. };
  68868. var newTexture = { textureUrl: url, data: blob };
  68869. try {
  68870. // Put the blob into the dabase
  68871. var addRequest = transaction.objectStore("textures").put(newTexture);
  68872. addRequest.onsuccess = function (event) {
  68873. };
  68874. addRequest.onerror = function (event) {
  68875. generateBlobUrl();
  68876. };
  68877. }
  68878. catch (ex) {
  68879. // "DataCloneError" generated by Chrome when you try to inject blob into IndexedDB
  68880. if (ex.code === 25) {
  68881. Database.IsUASupportingBlobStorage = false;
  68882. }
  68883. image.src = url;
  68884. }
  68885. }
  68886. else {
  68887. image.src = url;
  68888. }
  68889. }, false);
  68890. xhr.addEventListener("error", function (event) {
  68891. BABYLON.Tools.Error("Error in XHR request in BABYLON.Database.");
  68892. image.src = url;
  68893. }, false);
  68894. xhr.send();
  68895. }
  68896. else {
  68897. image.src = url;
  68898. }
  68899. }
  68900. else {
  68901. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  68902. image.src = url;
  68903. }
  68904. };
  68905. Database.prototype._checkVersionFromDB = function (url, versionLoaded) {
  68906. var _this = this;
  68907. var updateVersion = function () {
  68908. // the version is not yet in the DB or we need to update it
  68909. _this._saveVersionIntoDBAsync(url, versionLoaded);
  68910. };
  68911. this._loadVersionFromDBAsync(url, versionLoaded, updateVersion);
  68912. };
  68913. Database.prototype._loadVersionFromDBAsync = function (url, callback, updateInDBCallback) {
  68914. var _this = this;
  68915. if (this.isSupported && this.db) {
  68916. var version;
  68917. try {
  68918. var transaction = this.db.transaction(["versions"]);
  68919. transaction.oncomplete = function (event) {
  68920. if (version) {
  68921. // If the version in the JSON file is > than the version in DB
  68922. if (_this.manifestVersionFound > version.data) {
  68923. _this.mustUpdateRessources = true;
  68924. updateInDBCallback();
  68925. }
  68926. else {
  68927. callback(version.data);
  68928. }
  68929. }
  68930. // version was not found in DB
  68931. else {
  68932. _this.mustUpdateRessources = true;
  68933. updateInDBCallback();
  68934. }
  68935. };
  68936. transaction.onabort = function (event) {
  68937. callback(-1);
  68938. };
  68939. var getRequest = transaction.objectStore("versions").get(url);
  68940. getRequest.onsuccess = function (event) {
  68941. version = (event.target).result;
  68942. };
  68943. getRequest.onerror = function (event) {
  68944. BABYLON.Tools.Error("Error loading version for scene " + url + " from DB.");
  68945. callback(-1);
  68946. };
  68947. }
  68948. catch (ex) {
  68949. BABYLON.Tools.Error("Error while accessing 'versions' object store (READ OP). Exception: " + ex.message);
  68950. callback(-1);
  68951. }
  68952. }
  68953. else {
  68954. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  68955. callback(-1);
  68956. }
  68957. };
  68958. Database.prototype._saveVersionIntoDBAsync = function (url, callback) {
  68959. var _this = this;
  68960. if (this.isSupported && !this.hasReachedQuota && this.db) {
  68961. try {
  68962. // Open a transaction to the database
  68963. var transaction = this.db.transaction(["versions"], "readwrite");
  68964. // the transaction could abort because of a QuotaExceededError error
  68965. transaction.onabort = function (event) {
  68966. try { //backwards compatibility with ts 1.0, srcElement doesn't have an "error" according to ts 1.3
  68967. var error = event.srcElement['error'];
  68968. if (error && error.name === "QuotaExceededError") {
  68969. _this.hasReachedQuota = true;
  68970. }
  68971. }
  68972. catch (ex) { }
  68973. callback(-1);
  68974. };
  68975. transaction.oncomplete = function (event) {
  68976. callback(_this.manifestVersionFound);
  68977. };
  68978. var newVersion = { sceneUrl: url, data: this.manifestVersionFound };
  68979. // Put the scene into the database
  68980. var addRequest = transaction.objectStore("versions").put(newVersion);
  68981. addRequest.onsuccess = function (event) {
  68982. };
  68983. addRequest.onerror = function (event) {
  68984. BABYLON.Tools.Error("Error in DB add version request in BABYLON.Database.");
  68985. };
  68986. }
  68987. catch (ex) {
  68988. BABYLON.Tools.Error("Error while accessing 'versions' object store (WRITE OP). Exception: " + ex.message);
  68989. callback(-1);
  68990. }
  68991. }
  68992. else {
  68993. callback(-1);
  68994. }
  68995. };
  68996. /**
  68997. * Loads a file from database
  68998. * @param url defines the URL to load from
  68999. * @param sceneLoaded defines a callback to call on success
  69000. * @param progressCallBack defines a callback to call when progress changed
  69001. * @param errorCallback defines a callback to call on error
  69002. * @param useArrayBuffer defines a boolean to use array buffer instead of text string
  69003. */
  69004. Database.prototype.loadFileFromDB = function (url, sceneLoaded, progressCallBack, errorCallback, useArrayBuffer) {
  69005. var _this = this;
  69006. var completeUrl = Database._ReturnFullUrlLocation(url);
  69007. var saveAndLoadFile = function () {
  69008. // the scene is not yet in the DB, let's try to save it
  69009. _this._saveFileIntoDBAsync(completeUrl, sceneLoaded, progressCallBack);
  69010. };
  69011. this._checkVersionFromDB(completeUrl, function (version) {
  69012. if (version !== -1) {
  69013. if (!_this.mustUpdateRessources) {
  69014. _this._loadFileFromDBAsync(completeUrl, sceneLoaded, saveAndLoadFile, useArrayBuffer);
  69015. }
  69016. else {
  69017. _this._saveFileIntoDBAsync(completeUrl, sceneLoaded, progressCallBack, useArrayBuffer);
  69018. }
  69019. }
  69020. else {
  69021. if (errorCallback) {
  69022. errorCallback();
  69023. }
  69024. }
  69025. });
  69026. };
  69027. Database.prototype._loadFileFromDBAsync = function (url, callback, notInDBCallback, useArrayBuffer) {
  69028. if (this.isSupported && this.db) {
  69029. var targetStore;
  69030. if (url.indexOf(".babylon") !== -1) {
  69031. targetStore = "scenes";
  69032. }
  69033. else {
  69034. targetStore = "textures";
  69035. }
  69036. var file;
  69037. var transaction = this.db.transaction([targetStore]);
  69038. transaction.oncomplete = function (event) {
  69039. if (file) {
  69040. callback(file.data);
  69041. }
  69042. // file was not found in DB
  69043. else {
  69044. notInDBCallback();
  69045. }
  69046. };
  69047. transaction.onabort = function (event) {
  69048. notInDBCallback();
  69049. };
  69050. var getRequest = transaction.objectStore(targetStore).get(url);
  69051. getRequest.onsuccess = function (event) {
  69052. file = (event.target).result;
  69053. };
  69054. getRequest.onerror = function (event) {
  69055. BABYLON.Tools.Error("Error loading file " + url + " from DB.");
  69056. notInDBCallback();
  69057. };
  69058. }
  69059. else {
  69060. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  69061. callback();
  69062. }
  69063. };
  69064. Database.prototype._saveFileIntoDBAsync = function (url, callback, progressCallback, useArrayBuffer) {
  69065. var _this = this;
  69066. if (this.isSupported) {
  69067. var targetStore;
  69068. if (url.indexOf(".babylon") !== -1) {
  69069. targetStore = "scenes";
  69070. }
  69071. else {
  69072. targetStore = "textures";
  69073. }
  69074. // Create XHR
  69075. var xhr = new XMLHttpRequest();
  69076. var fileData;
  69077. xhr.open("GET", url, true);
  69078. if (useArrayBuffer) {
  69079. xhr.responseType = "arraybuffer";
  69080. }
  69081. if (progressCallback) {
  69082. xhr.onprogress = progressCallback;
  69083. }
  69084. xhr.addEventListener("load", function () {
  69085. if (xhr.status === 200 || BABYLON.Tools.ValidateXHRData(xhr, !useArrayBuffer ? 1 : 6)) {
  69086. // Blob as response (XHR2)
  69087. //fileData = xhr.responseText;
  69088. fileData = !useArrayBuffer ? xhr.responseText : xhr.response;
  69089. if (!_this.hasReachedQuota && _this.db) {
  69090. // Open a transaction to the database
  69091. var transaction = _this.db.transaction([targetStore], "readwrite");
  69092. // the transaction could abort because of a QuotaExceededError error
  69093. transaction.onabort = function (event) {
  69094. try {
  69095. //backwards compatibility with ts 1.0, srcElement doesn't have an "error" according to ts 1.3
  69096. var error = event.srcElement['error'];
  69097. if (error && error.name === "QuotaExceededError") {
  69098. _this.hasReachedQuota = true;
  69099. }
  69100. }
  69101. catch (ex) { }
  69102. callback(fileData);
  69103. };
  69104. transaction.oncomplete = function (event) {
  69105. callback(fileData);
  69106. };
  69107. var newFile;
  69108. if (targetStore === "scenes") {
  69109. newFile = { sceneUrl: url, data: fileData, version: _this.manifestVersionFound };
  69110. }
  69111. else {
  69112. newFile = { textureUrl: url, data: fileData };
  69113. }
  69114. try {
  69115. // Put the scene into the database
  69116. var addRequest = transaction.objectStore(targetStore).put(newFile);
  69117. addRequest.onsuccess = function (event) {
  69118. };
  69119. addRequest.onerror = function (event) {
  69120. BABYLON.Tools.Error("Error in DB add file request in BABYLON.Database.");
  69121. };
  69122. }
  69123. catch (ex) {
  69124. callback(fileData);
  69125. }
  69126. }
  69127. else {
  69128. callback(fileData);
  69129. }
  69130. }
  69131. else {
  69132. callback();
  69133. }
  69134. }, false);
  69135. xhr.addEventListener("error", function (event) {
  69136. BABYLON.Tools.Error("error on XHR request.");
  69137. callback();
  69138. }, false);
  69139. xhr.send();
  69140. }
  69141. else {
  69142. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  69143. callback();
  69144. }
  69145. };
  69146. /** Gets a boolean indicating if the user agent supports blob storage (this value will be updated after creating the first Database object) */
  69147. Database.IsUASupportingBlobStorage = true;
  69148. /** Gets a boolean indicating if Database storate is enabled */
  69149. Database.IDBStorageEnabled = true;
  69150. Database._ParseURL = function (url) {
  69151. var a = document.createElement('a');
  69152. a.href = url;
  69153. var urlWithoutHash = url.substring(0, url.lastIndexOf("#"));
  69154. var fileName = url.substring(urlWithoutHash.lastIndexOf("/") + 1, url.length);
  69155. var absLocation = url.substring(0, url.indexOf(fileName, 0));
  69156. return absLocation;
  69157. };
  69158. Database._ReturnFullUrlLocation = function (url) {
  69159. if (url.indexOf("http:/") === -1 && url.indexOf("https:/") === -1) {
  69160. return (Database._ParseURL(window.location.href) + url);
  69161. }
  69162. else {
  69163. return url;
  69164. }
  69165. };
  69166. return Database;
  69167. }());
  69168. BABYLON.Database = Database;
  69169. })(BABYLON || (BABYLON = {}));
  69170. //# sourceMappingURL=babylon.database.js.map
  69171. var BABYLON;
  69172. (function (BABYLON) {
  69173. var FresnelParameters = /** @class */ (function () {
  69174. function FresnelParameters() {
  69175. this._isEnabled = true;
  69176. this.leftColor = BABYLON.Color3.White();
  69177. this.rightColor = BABYLON.Color3.Black();
  69178. this.bias = 0;
  69179. this.power = 1;
  69180. }
  69181. Object.defineProperty(FresnelParameters.prototype, "isEnabled", {
  69182. get: function () {
  69183. return this._isEnabled;
  69184. },
  69185. set: function (value) {
  69186. if (this._isEnabled === value) {
  69187. return;
  69188. }
  69189. this._isEnabled = value;
  69190. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.FresnelDirtyFlag | BABYLON.Material.MiscDirtyFlag);
  69191. },
  69192. enumerable: true,
  69193. configurable: true
  69194. });
  69195. FresnelParameters.prototype.clone = function () {
  69196. var newFresnelParameters = new FresnelParameters();
  69197. BABYLON.Tools.DeepCopy(this, newFresnelParameters);
  69198. return newFresnelParameters;
  69199. };
  69200. FresnelParameters.prototype.serialize = function () {
  69201. var serializationObject = {};
  69202. serializationObject.isEnabled = this.isEnabled;
  69203. serializationObject.leftColor = this.leftColor.asArray();
  69204. serializationObject.rightColor = this.rightColor.asArray();
  69205. serializationObject.bias = this.bias;
  69206. serializationObject.power = this.power;
  69207. return serializationObject;
  69208. };
  69209. FresnelParameters.Parse = function (parsedFresnelParameters) {
  69210. var fresnelParameters = new FresnelParameters();
  69211. fresnelParameters.isEnabled = parsedFresnelParameters.isEnabled;
  69212. fresnelParameters.leftColor = BABYLON.Color3.FromArray(parsedFresnelParameters.leftColor);
  69213. fresnelParameters.rightColor = BABYLON.Color3.FromArray(parsedFresnelParameters.rightColor);
  69214. fresnelParameters.bias = parsedFresnelParameters.bias;
  69215. fresnelParameters.power = parsedFresnelParameters.power || 1.0;
  69216. return fresnelParameters;
  69217. };
  69218. return FresnelParameters;
  69219. }());
  69220. BABYLON.FresnelParameters = FresnelParameters;
  69221. })(BABYLON || (BABYLON = {}));
  69222. //# sourceMappingURL=babylon.fresnelParameters.js.map
  69223. var BABYLON;
  69224. (function (BABYLON) {
  69225. var MultiMaterial = /** @class */ (function (_super) {
  69226. __extends(MultiMaterial, _super);
  69227. function MultiMaterial(name, scene) {
  69228. var _this = _super.call(this, name, scene, true) || this;
  69229. scene.multiMaterials.push(_this);
  69230. _this.subMaterials = new Array();
  69231. _this.storeEffectOnSubMeshes = true; // multimaterial is considered like a push material
  69232. return _this;
  69233. }
  69234. Object.defineProperty(MultiMaterial.prototype, "subMaterials", {
  69235. get: function () {
  69236. return this._subMaterials;
  69237. },
  69238. set: function (value) {
  69239. this._subMaterials = value;
  69240. this._hookArray(value);
  69241. },
  69242. enumerable: true,
  69243. configurable: true
  69244. });
  69245. MultiMaterial.prototype._hookArray = function (array) {
  69246. var _this = this;
  69247. var oldPush = array.push;
  69248. array.push = function () {
  69249. var items = [];
  69250. for (var _i = 0; _i < arguments.length; _i++) {
  69251. items[_i] = arguments[_i];
  69252. }
  69253. var result = oldPush.apply(array, items);
  69254. _this._markAllSubMeshesAsTexturesDirty();
  69255. return result;
  69256. };
  69257. var oldSplice = array.splice;
  69258. array.splice = function (index, deleteCount) {
  69259. var deleted = oldSplice.apply(array, [index, deleteCount]);
  69260. _this._markAllSubMeshesAsTexturesDirty();
  69261. return deleted;
  69262. };
  69263. };
  69264. // Properties
  69265. MultiMaterial.prototype.getSubMaterial = function (index) {
  69266. if (index < 0 || index >= this.subMaterials.length) {
  69267. return this.getScene().defaultMaterial;
  69268. }
  69269. return this.subMaterials[index];
  69270. };
  69271. MultiMaterial.prototype.getActiveTextures = function () {
  69272. return (_a = _super.prototype.getActiveTextures.call(this)).concat.apply(_a, this.subMaterials.map(function (subMaterial) {
  69273. if (subMaterial) {
  69274. return subMaterial.getActiveTextures();
  69275. }
  69276. else {
  69277. return [];
  69278. }
  69279. }));
  69280. var _a;
  69281. };
  69282. // Methods
  69283. MultiMaterial.prototype.getClassName = function () {
  69284. return "MultiMaterial";
  69285. };
  69286. MultiMaterial.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  69287. for (var index = 0; index < this.subMaterials.length; index++) {
  69288. var subMaterial = this.subMaterials[index];
  69289. if (subMaterial) {
  69290. if (subMaterial.storeEffectOnSubMeshes) {
  69291. if (!subMaterial.isReadyForSubMesh(mesh, subMesh, useInstances)) {
  69292. return false;
  69293. }
  69294. continue;
  69295. }
  69296. if (!subMaterial.isReady(mesh)) {
  69297. return false;
  69298. }
  69299. }
  69300. }
  69301. return true;
  69302. };
  69303. MultiMaterial.prototype.clone = function (name, cloneChildren) {
  69304. var newMultiMaterial = new MultiMaterial(name, this.getScene());
  69305. for (var index = 0; index < this.subMaterials.length; index++) {
  69306. var subMaterial = null;
  69307. var current = this.subMaterials[index];
  69308. if (cloneChildren && current) {
  69309. subMaterial = current.clone(name + "-" + current.name);
  69310. }
  69311. else {
  69312. subMaterial = this.subMaterials[index];
  69313. }
  69314. newMultiMaterial.subMaterials.push(subMaterial);
  69315. }
  69316. return newMultiMaterial;
  69317. };
  69318. MultiMaterial.prototype.serialize = function () {
  69319. var serializationObject = {};
  69320. serializationObject.name = this.name;
  69321. serializationObject.id = this.id;
  69322. if (BABYLON.Tags) {
  69323. serializationObject.tags = BABYLON.Tags.GetTags(this);
  69324. }
  69325. serializationObject.materials = [];
  69326. for (var matIndex = 0; matIndex < this.subMaterials.length; matIndex++) {
  69327. var subMat = this.subMaterials[matIndex];
  69328. if (subMat) {
  69329. serializationObject.materials.push(subMat.id);
  69330. }
  69331. else {
  69332. serializationObject.materials.push(null);
  69333. }
  69334. }
  69335. return serializationObject;
  69336. };
  69337. MultiMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  69338. var scene = this.getScene();
  69339. if (!scene) {
  69340. return;
  69341. }
  69342. var index = scene.multiMaterials.indexOf(this);
  69343. if (index >= 0) {
  69344. scene.multiMaterials.splice(index, 1);
  69345. }
  69346. _super.prototype.dispose.call(this, forceDisposeEffect, forceDisposeTextures);
  69347. };
  69348. return MultiMaterial;
  69349. }(BABYLON.Material));
  69350. BABYLON.MultiMaterial = MultiMaterial;
  69351. })(BABYLON || (BABYLON = {}));
  69352. //# sourceMappingURL=babylon.multiMaterial.js.map
  69353. var BABYLON;
  69354. (function (BABYLON) {
  69355. var FreeCameraTouchInput = /** @class */ (function () {
  69356. function FreeCameraTouchInput() {
  69357. this._offsetX = null;
  69358. this._offsetY = null;
  69359. this._pointerPressed = new Array();
  69360. this.touchAngularSensibility = 200000.0;
  69361. this.touchMoveSensibility = 250.0;
  69362. }
  69363. FreeCameraTouchInput.prototype.attachControl = function (element, noPreventDefault) {
  69364. var _this = this;
  69365. var previousPosition = null;
  69366. if (this._pointerInput === undefined) {
  69367. this._onLostFocus = function (evt) {
  69368. _this._offsetX = null;
  69369. _this._offsetY = null;
  69370. };
  69371. this._pointerInput = function (p, s) {
  69372. var evt = p.event;
  69373. if (evt.pointerType === "mouse") {
  69374. return;
  69375. }
  69376. if (p.type === BABYLON.PointerEventTypes.POINTERDOWN) {
  69377. if (!noPreventDefault) {
  69378. evt.preventDefault();
  69379. }
  69380. _this._pointerPressed.push(evt.pointerId);
  69381. if (_this._pointerPressed.length !== 1) {
  69382. return;
  69383. }
  69384. previousPosition = {
  69385. x: evt.clientX,
  69386. y: evt.clientY
  69387. };
  69388. }
  69389. else if (p.type === BABYLON.PointerEventTypes.POINTERUP) {
  69390. if (!noPreventDefault) {
  69391. evt.preventDefault();
  69392. }
  69393. var index = _this._pointerPressed.indexOf(evt.pointerId);
  69394. if (index === -1) {
  69395. return;
  69396. }
  69397. _this._pointerPressed.splice(index, 1);
  69398. if (index != 0) {
  69399. return;
  69400. }
  69401. previousPosition = null;
  69402. _this._offsetX = null;
  69403. _this._offsetY = null;
  69404. }
  69405. else if (p.type === BABYLON.PointerEventTypes.POINTERMOVE) {
  69406. if (!noPreventDefault) {
  69407. evt.preventDefault();
  69408. }
  69409. if (!previousPosition) {
  69410. return;
  69411. }
  69412. var index = _this._pointerPressed.indexOf(evt.pointerId);
  69413. if (index != 0) {
  69414. return;
  69415. }
  69416. _this._offsetX = evt.clientX - previousPosition.x;
  69417. _this._offsetY = -(evt.clientY - previousPosition.y);
  69418. }
  69419. };
  69420. }
  69421. this._observer = this.camera.getScene().onPointerObservable.add(this._pointerInput, BABYLON.PointerEventTypes.POINTERDOWN | BABYLON.PointerEventTypes.POINTERUP | BABYLON.PointerEventTypes.POINTERMOVE);
  69422. if (this._onLostFocus) {
  69423. element.addEventListener("blur", this._onLostFocus);
  69424. }
  69425. };
  69426. FreeCameraTouchInput.prototype.detachControl = function (element) {
  69427. if (this._pointerInput && element) {
  69428. if (this._observer) {
  69429. this.camera.getScene().onPointerObservable.remove(this._observer);
  69430. this._observer = null;
  69431. }
  69432. if (this._onLostFocus) {
  69433. element.removeEventListener("blur", this._onLostFocus);
  69434. this._onLostFocus = null;
  69435. }
  69436. this._pointerPressed = [];
  69437. this._offsetX = null;
  69438. this._offsetY = null;
  69439. }
  69440. };
  69441. FreeCameraTouchInput.prototype.checkInputs = function () {
  69442. if (this._offsetX && this._offsetY) {
  69443. var camera = this.camera;
  69444. camera.cameraRotation.y += this._offsetX / this.touchAngularSensibility;
  69445. if (this._pointerPressed.length > 1) {
  69446. camera.cameraRotation.x += -this._offsetY / this.touchAngularSensibility;
  69447. }
  69448. else {
  69449. var speed = camera._computeLocalCameraSpeed();
  69450. var direction = new BABYLON.Vector3(0, 0, speed * this._offsetY / this.touchMoveSensibility);
  69451. BABYLON.Matrix.RotationYawPitchRollToRef(camera.rotation.y, camera.rotation.x, 0, camera._cameraRotationMatrix);
  69452. camera.cameraDirection.addInPlace(BABYLON.Vector3.TransformCoordinates(direction, camera._cameraRotationMatrix));
  69453. }
  69454. }
  69455. };
  69456. FreeCameraTouchInput.prototype.getClassName = function () {
  69457. return "FreeCameraTouchInput";
  69458. };
  69459. FreeCameraTouchInput.prototype.getSimpleName = function () {
  69460. return "touch";
  69461. };
  69462. __decorate([
  69463. BABYLON.serialize()
  69464. ], FreeCameraTouchInput.prototype, "touchAngularSensibility", void 0);
  69465. __decorate([
  69466. BABYLON.serialize()
  69467. ], FreeCameraTouchInput.prototype, "touchMoveSensibility", void 0);
  69468. return FreeCameraTouchInput;
  69469. }());
  69470. BABYLON.FreeCameraTouchInput = FreeCameraTouchInput;
  69471. BABYLON.CameraInputTypes["FreeCameraTouchInput"] = FreeCameraTouchInput;
  69472. })(BABYLON || (BABYLON = {}));
  69473. //# sourceMappingURL=babylon.freeCameraTouchInput.js.map
  69474. var BABYLON;
  69475. (function (BABYLON) {
  69476. // We're mainly based on the logic defined into the FreeCamera code
  69477. var TouchCamera = /** @class */ (function (_super) {
  69478. __extends(TouchCamera, _super);
  69479. //-- end properties for backward compatibility for inputs
  69480. function TouchCamera(name, position, scene) {
  69481. var _this = _super.call(this, name, position, scene) || this;
  69482. _this.inputs.addTouch();
  69483. _this._setupInputs();
  69484. return _this;
  69485. }
  69486. Object.defineProperty(TouchCamera.prototype, "touchAngularSensibility", {
  69487. //-- Begin properties for backward compatibility for inputs
  69488. get: function () {
  69489. var touch = this.inputs.attached["touch"];
  69490. if (touch)
  69491. return touch.touchAngularSensibility;
  69492. return 0;
  69493. },
  69494. set: function (value) {
  69495. var touch = this.inputs.attached["touch"];
  69496. if (touch)
  69497. touch.touchAngularSensibility = value;
  69498. },
  69499. enumerable: true,
  69500. configurable: true
  69501. });
  69502. Object.defineProperty(TouchCamera.prototype, "touchMoveSensibility", {
  69503. get: function () {
  69504. var touch = this.inputs.attached["touch"];
  69505. if (touch)
  69506. return touch.touchMoveSensibility;
  69507. return 0;
  69508. },
  69509. set: function (value) {
  69510. var touch = this.inputs.attached["touch"];
  69511. if (touch)
  69512. touch.touchMoveSensibility = value;
  69513. },
  69514. enumerable: true,
  69515. configurable: true
  69516. });
  69517. TouchCamera.prototype.getClassName = function () {
  69518. return "TouchCamera";
  69519. };
  69520. TouchCamera.prototype._setupInputs = function () {
  69521. var mouse = this.inputs.attached["mouse"];
  69522. if (mouse) {
  69523. mouse.touchEnabled = false;
  69524. }
  69525. };
  69526. return TouchCamera;
  69527. }(BABYLON.FreeCamera));
  69528. BABYLON.TouchCamera = TouchCamera;
  69529. })(BABYLON || (BABYLON = {}));
  69530. //# sourceMappingURL=babylon.touchCamera.js.map
  69531. var BABYLON;
  69532. (function (BABYLON) {
  69533. var ProceduralTexture = /** @class */ (function (_super) {
  69534. __extends(ProceduralTexture, _super);
  69535. function ProceduralTexture(name, size, fragment, scene, fallbackTexture, generateMipMaps, isCube) {
  69536. if (fallbackTexture === void 0) { fallbackTexture = null; }
  69537. if (generateMipMaps === void 0) { generateMipMaps = true; }
  69538. if (isCube === void 0) { isCube = false; }
  69539. var _this = _super.call(this, null, scene, !generateMipMaps) || this;
  69540. _this.isCube = isCube;
  69541. _this.isEnabled = true;
  69542. _this._currentRefreshId = -1;
  69543. _this._refreshRate = 1;
  69544. _this._vertexBuffers = {};
  69545. _this._uniforms = new Array();
  69546. _this._samplers = new Array();
  69547. _this._textures = {};
  69548. _this._floats = {};
  69549. _this._floatsArrays = {};
  69550. _this._colors3 = {};
  69551. _this._colors4 = {};
  69552. _this._vectors2 = {};
  69553. _this._vectors3 = {};
  69554. _this._matrices = {};
  69555. _this._fallbackTextureUsed = false;
  69556. scene.proceduralTextures.push(_this);
  69557. _this._engine = scene.getEngine();
  69558. _this.name = name;
  69559. _this.isRenderTarget = true;
  69560. _this._size = size;
  69561. _this._generateMipMaps = generateMipMaps;
  69562. _this.setFragment(fragment);
  69563. _this._fallbackTexture = fallbackTexture;
  69564. if (isCube) {
  69565. _this._texture = _this._engine.createRenderTargetCubeTexture(size, { generateMipMaps: generateMipMaps });
  69566. _this.setFloat("face", 0);
  69567. }
  69568. else {
  69569. _this._texture = _this._engine.createRenderTargetTexture(size, generateMipMaps);
  69570. }
  69571. // VBO
  69572. var vertices = [];
  69573. vertices.push(1, 1);
  69574. vertices.push(-1, 1);
  69575. vertices.push(-1, -1);
  69576. vertices.push(1, -1);
  69577. _this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(_this._engine, vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  69578. _this._createIndexBuffer();
  69579. return _this;
  69580. }
  69581. ProceduralTexture.prototype._createIndexBuffer = function () {
  69582. var engine = this._engine;
  69583. // Indices
  69584. var indices = [];
  69585. indices.push(0);
  69586. indices.push(1);
  69587. indices.push(2);
  69588. indices.push(0);
  69589. indices.push(2);
  69590. indices.push(3);
  69591. this._indexBuffer = engine.createIndexBuffer(indices);
  69592. };
  69593. ProceduralTexture.prototype._rebuild = function () {
  69594. var vb = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  69595. if (vb) {
  69596. vb._rebuild();
  69597. }
  69598. this._createIndexBuffer();
  69599. if (this.refreshRate === BABYLON.RenderTargetTexture.REFRESHRATE_RENDER_ONCE) {
  69600. this.refreshRate = BABYLON.RenderTargetTexture.REFRESHRATE_RENDER_ONCE;
  69601. }
  69602. };
  69603. ProceduralTexture.prototype.reset = function () {
  69604. if (this._effect === undefined) {
  69605. return;
  69606. }
  69607. var engine = this._engine;
  69608. engine._releaseEffect(this._effect);
  69609. };
  69610. ProceduralTexture.prototype.isReady = function () {
  69611. var _this = this;
  69612. var engine = this._engine;
  69613. var shaders;
  69614. if (!this._fragment) {
  69615. return false;
  69616. }
  69617. if (this._fallbackTextureUsed) {
  69618. return true;
  69619. }
  69620. if (this._fragment.fragmentElement !== undefined) {
  69621. shaders = { vertex: "procedural", fragmentElement: this._fragment.fragmentElement };
  69622. }
  69623. else {
  69624. shaders = { vertex: "procedural", fragment: this._fragment };
  69625. }
  69626. this._effect = engine.createEffect(shaders, [BABYLON.VertexBuffer.PositionKind], this._uniforms, this._samplers, "", undefined, undefined, function () {
  69627. _this.releaseInternalTexture();
  69628. if (_this._fallbackTexture) {
  69629. _this._texture = _this._fallbackTexture._texture;
  69630. if (_this._texture) {
  69631. _this._texture.incrementReferences();
  69632. }
  69633. }
  69634. _this._fallbackTextureUsed = true;
  69635. });
  69636. return this._effect.isReady();
  69637. };
  69638. ProceduralTexture.prototype.resetRefreshCounter = function () {
  69639. this._currentRefreshId = -1;
  69640. };
  69641. ProceduralTexture.prototype.setFragment = function (fragment) {
  69642. this._fragment = fragment;
  69643. };
  69644. Object.defineProperty(ProceduralTexture.prototype, "refreshRate", {
  69645. get: function () {
  69646. return this._refreshRate;
  69647. },
  69648. // Use 0 to render just once, 1 to render on every frame, 2 to render every two frames and so on...
  69649. set: function (value) {
  69650. this._refreshRate = value;
  69651. this.resetRefreshCounter();
  69652. },
  69653. enumerable: true,
  69654. configurable: true
  69655. });
  69656. ProceduralTexture.prototype._shouldRender = function () {
  69657. if (!this.isEnabled || !this.isReady() || !this._texture) {
  69658. return false;
  69659. }
  69660. if (this._fallbackTextureUsed) {
  69661. return false;
  69662. }
  69663. if (this._currentRefreshId === -1) { // At least render once
  69664. this._currentRefreshId = 1;
  69665. return true;
  69666. }
  69667. if (this.refreshRate === this._currentRefreshId) {
  69668. this._currentRefreshId = 1;
  69669. return true;
  69670. }
  69671. this._currentRefreshId++;
  69672. return false;
  69673. };
  69674. ProceduralTexture.prototype.getRenderSize = function () {
  69675. return this._size;
  69676. };
  69677. ProceduralTexture.prototype.resize = function (size, generateMipMaps) {
  69678. if (this._fallbackTextureUsed) {
  69679. return;
  69680. }
  69681. this.releaseInternalTexture();
  69682. this._texture = this._engine.createRenderTargetTexture(size, generateMipMaps);
  69683. };
  69684. ProceduralTexture.prototype._checkUniform = function (uniformName) {
  69685. if (this._uniforms.indexOf(uniformName) === -1) {
  69686. this._uniforms.push(uniformName);
  69687. }
  69688. };
  69689. ProceduralTexture.prototype.setTexture = function (name, texture) {
  69690. if (this._samplers.indexOf(name) === -1) {
  69691. this._samplers.push(name);
  69692. }
  69693. this._textures[name] = texture;
  69694. return this;
  69695. };
  69696. ProceduralTexture.prototype.setFloat = function (name, value) {
  69697. this._checkUniform(name);
  69698. this._floats[name] = value;
  69699. return this;
  69700. };
  69701. ProceduralTexture.prototype.setFloats = function (name, value) {
  69702. this._checkUniform(name);
  69703. this._floatsArrays[name] = value;
  69704. return this;
  69705. };
  69706. ProceduralTexture.prototype.setColor3 = function (name, value) {
  69707. this._checkUniform(name);
  69708. this._colors3[name] = value;
  69709. return this;
  69710. };
  69711. ProceduralTexture.prototype.setColor4 = function (name, value) {
  69712. this._checkUniform(name);
  69713. this._colors4[name] = value;
  69714. return this;
  69715. };
  69716. ProceduralTexture.prototype.setVector2 = function (name, value) {
  69717. this._checkUniform(name);
  69718. this._vectors2[name] = value;
  69719. return this;
  69720. };
  69721. ProceduralTexture.prototype.setVector3 = function (name, value) {
  69722. this._checkUniform(name);
  69723. this._vectors3[name] = value;
  69724. return this;
  69725. };
  69726. ProceduralTexture.prototype.setMatrix = function (name, value) {
  69727. this._checkUniform(name);
  69728. this._matrices[name] = value;
  69729. return this;
  69730. };
  69731. ProceduralTexture.prototype.render = function (useCameraPostProcess) {
  69732. var scene = this.getScene();
  69733. if (!scene) {
  69734. return;
  69735. }
  69736. var engine = this._engine;
  69737. // Render
  69738. engine.enableEffect(this._effect);
  69739. engine.setState(false);
  69740. // Texture
  69741. for (var name in this._textures) {
  69742. this._effect.setTexture(name, this._textures[name]);
  69743. }
  69744. // Float
  69745. for (name in this._floats) {
  69746. this._effect.setFloat(name, this._floats[name]);
  69747. }
  69748. // Floats
  69749. for (name in this._floatsArrays) {
  69750. this._effect.setArray(name, this._floatsArrays[name]);
  69751. }
  69752. // Color3
  69753. for (name in this._colors3) {
  69754. this._effect.setColor3(name, this._colors3[name]);
  69755. }
  69756. // Color4
  69757. for (name in this._colors4) {
  69758. var color = this._colors4[name];
  69759. this._effect.setFloat4(name, color.r, color.g, color.b, color.a);
  69760. }
  69761. // Vector2
  69762. for (name in this._vectors2) {
  69763. this._effect.setVector2(name, this._vectors2[name]);
  69764. }
  69765. // Vector3
  69766. for (name in this._vectors3) {
  69767. this._effect.setVector3(name, this._vectors3[name]);
  69768. }
  69769. // Matrix
  69770. for (name in this._matrices) {
  69771. this._effect.setMatrix(name, this._matrices[name]);
  69772. }
  69773. if (!this._texture) {
  69774. return;
  69775. }
  69776. if (this.isCube) {
  69777. for (var face = 0; face < 6; face++) {
  69778. engine.bindFramebuffer(this._texture, face, undefined, undefined, true);
  69779. // VBOs
  69780. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._effect);
  69781. this._effect.setFloat("face", face);
  69782. // Clear
  69783. engine.clear(scene.clearColor, true, true, true);
  69784. // Draw order
  69785. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  69786. // Mipmaps
  69787. if (face === 5) {
  69788. engine.generateMipMapsForCubemap(this._texture);
  69789. }
  69790. }
  69791. }
  69792. else {
  69793. engine.bindFramebuffer(this._texture, 0, undefined, undefined, true);
  69794. // VBOs
  69795. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._effect);
  69796. // Clear
  69797. engine.clear(scene.clearColor, true, true, true);
  69798. // Draw order
  69799. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  69800. }
  69801. // Unbind
  69802. engine.unBindFramebuffer(this._texture, this.isCube);
  69803. if (this.onGenerated) {
  69804. this.onGenerated();
  69805. }
  69806. };
  69807. ProceduralTexture.prototype.clone = function () {
  69808. var textureSize = this.getSize();
  69809. var newTexture = new ProceduralTexture(this.name, textureSize.width, this._fragment, this.getScene(), this._fallbackTexture, this._generateMipMaps);
  69810. // Base texture
  69811. newTexture.hasAlpha = this.hasAlpha;
  69812. newTexture.level = this.level;
  69813. // RenderTarget Texture
  69814. newTexture.coordinatesMode = this.coordinatesMode;
  69815. return newTexture;
  69816. };
  69817. ProceduralTexture.prototype.dispose = function () {
  69818. var scene = this.getScene();
  69819. if (!scene) {
  69820. return;
  69821. }
  69822. var index = scene.proceduralTextures.indexOf(this);
  69823. if (index >= 0) {
  69824. scene.proceduralTextures.splice(index, 1);
  69825. }
  69826. var vertexBuffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  69827. if (vertexBuffer) {
  69828. vertexBuffer.dispose();
  69829. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  69830. }
  69831. if (this._indexBuffer && this._engine._releaseBuffer(this._indexBuffer)) {
  69832. this._indexBuffer = null;
  69833. }
  69834. _super.prototype.dispose.call(this);
  69835. };
  69836. return ProceduralTexture;
  69837. }(BABYLON.Texture));
  69838. BABYLON.ProceduralTexture = ProceduralTexture;
  69839. })(BABYLON || (BABYLON = {}));
  69840. //# sourceMappingURL=babylon.proceduralTexture.js.map
  69841. var BABYLON;
  69842. (function (BABYLON) {
  69843. var CustomProceduralTexture = /** @class */ (function (_super) {
  69844. __extends(CustomProceduralTexture, _super);
  69845. function CustomProceduralTexture(name, texturePath, size, scene, fallbackTexture, generateMipMaps) {
  69846. var _this = _super.call(this, name, size, null, scene, fallbackTexture, generateMipMaps) || this;
  69847. _this._animate = true;
  69848. _this._time = 0;
  69849. _this._texturePath = texturePath;
  69850. //Try to load json
  69851. _this.loadJson(texturePath);
  69852. _this.refreshRate = 1;
  69853. return _this;
  69854. }
  69855. CustomProceduralTexture.prototype.loadJson = function (jsonUrl) {
  69856. var _this = this;
  69857. var noConfigFile = function () {
  69858. BABYLON.Tools.Log("No config file found in " + jsonUrl + " trying to use ShadersStore or DOM element");
  69859. try {
  69860. _this.setFragment(_this._texturePath);
  69861. }
  69862. catch (ex) {
  69863. BABYLON.Tools.Error("No json or ShaderStore or DOM element found for CustomProceduralTexture");
  69864. }
  69865. };
  69866. var configFileUrl = jsonUrl + "/config.json";
  69867. var xhr = new XMLHttpRequest();
  69868. xhr.open("GET", configFileUrl, true);
  69869. xhr.addEventListener("load", function () {
  69870. if (xhr.status === 200 || BABYLON.Tools.ValidateXHRData(xhr, 1)) {
  69871. try {
  69872. _this._config = JSON.parse(xhr.response);
  69873. _this.updateShaderUniforms();
  69874. _this.updateTextures();
  69875. _this.setFragment(_this._texturePath + "/custom");
  69876. _this._animate = _this._config.animate;
  69877. _this.refreshRate = _this._config.refreshrate;
  69878. }
  69879. catch (ex) {
  69880. noConfigFile();
  69881. }
  69882. }
  69883. else {
  69884. noConfigFile();
  69885. }
  69886. }, false);
  69887. xhr.addEventListener("error", function () {
  69888. noConfigFile();
  69889. }, false);
  69890. try {
  69891. xhr.send();
  69892. }
  69893. catch (ex) {
  69894. BABYLON.Tools.Error("CustomProceduralTexture: Error on XHR send request.");
  69895. }
  69896. };
  69897. CustomProceduralTexture.prototype.isReady = function () {
  69898. if (!_super.prototype.isReady.call(this)) {
  69899. return false;
  69900. }
  69901. for (var name in this._textures) {
  69902. var texture = this._textures[name];
  69903. if (!texture.isReady()) {
  69904. return false;
  69905. }
  69906. }
  69907. return true;
  69908. };
  69909. CustomProceduralTexture.prototype.render = function (useCameraPostProcess) {
  69910. var scene = this.getScene();
  69911. if (this._animate && scene) {
  69912. this._time += scene.getAnimationRatio() * 0.03;
  69913. this.updateShaderUniforms();
  69914. }
  69915. _super.prototype.render.call(this, useCameraPostProcess);
  69916. };
  69917. CustomProceduralTexture.prototype.updateTextures = function () {
  69918. for (var i = 0; i < this._config.sampler2Ds.length; i++) {
  69919. this.setTexture(this._config.sampler2Ds[i].sample2Dname, new BABYLON.Texture(this._texturePath + "/" + this._config.sampler2Ds[i].textureRelativeUrl, this.getScene()));
  69920. }
  69921. };
  69922. CustomProceduralTexture.prototype.updateShaderUniforms = function () {
  69923. if (this._config) {
  69924. for (var j = 0; j < this._config.uniforms.length; j++) {
  69925. var uniform = this._config.uniforms[j];
  69926. switch (uniform.type) {
  69927. case "float":
  69928. this.setFloat(uniform.name, uniform.value);
  69929. break;
  69930. case "color3":
  69931. this.setColor3(uniform.name, new BABYLON.Color3(uniform.r, uniform.g, uniform.b));
  69932. break;
  69933. case "color4":
  69934. this.setColor4(uniform.name, new BABYLON.Color4(uniform.r, uniform.g, uniform.b, uniform.a));
  69935. break;
  69936. case "vector2":
  69937. this.setVector2(uniform.name, new BABYLON.Vector2(uniform.x, uniform.y));
  69938. break;
  69939. case "vector3":
  69940. this.setVector3(uniform.name, new BABYLON.Vector3(uniform.x, uniform.y, uniform.z));
  69941. break;
  69942. }
  69943. }
  69944. }
  69945. this.setFloat("time", this._time);
  69946. };
  69947. Object.defineProperty(CustomProceduralTexture.prototype, "animate", {
  69948. get: function () {
  69949. return this._animate;
  69950. },
  69951. set: function (value) {
  69952. this._animate = value;
  69953. },
  69954. enumerable: true,
  69955. configurable: true
  69956. });
  69957. return CustomProceduralTexture;
  69958. }(BABYLON.ProceduralTexture));
  69959. BABYLON.CustomProceduralTexture = CustomProceduralTexture;
  69960. })(BABYLON || (BABYLON = {}));
  69961. //# sourceMappingURL=babylon.customProceduralTexture.js.map
  69962. var BABYLON;
  69963. (function (BABYLON) {
  69964. var FreeCameraGamepadInput = /** @class */ (function () {
  69965. function FreeCameraGamepadInput() {
  69966. this.gamepadAngularSensibility = 200;
  69967. this.gamepadMoveSensibility = 40;
  69968. // private members
  69969. this._cameraTransform = BABYLON.Matrix.Identity();
  69970. this._deltaTransform = BABYLON.Vector3.Zero();
  69971. this._vector3 = BABYLON.Vector3.Zero();
  69972. this._vector2 = BABYLON.Vector2.Zero();
  69973. }
  69974. FreeCameraGamepadInput.prototype.attachControl = function (element, noPreventDefault) {
  69975. var _this = this;
  69976. var manager = this.camera.getScene().gamepadManager;
  69977. this._onGamepadConnectedObserver = manager.onGamepadConnectedObservable.add(function (gamepad) {
  69978. if (gamepad.type !== BABYLON.Gamepad.POSE_ENABLED) {
  69979. // prioritize XBOX gamepads.
  69980. if (!_this.gamepad || gamepad.type === BABYLON.Gamepad.XBOX) {
  69981. _this.gamepad = gamepad;
  69982. }
  69983. }
  69984. });
  69985. this._onGamepadDisconnectedObserver = manager.onGamepadDisconnectedObservable.add(function (gamepad) {
  69986. if (_this.gamepad === gamepad) {
  69987. _this.gamepad = null;
  69988. }
  69989. });
  69990. this.gamepad = manager.getGamepadByType(BABYLON.Gamepad.XBOX);
  69991. };
  69992. FreeCameraGamepadInput.prototype.detachControl = function (element) {
  69993. this.camera.getScene().gamepadManager.onGamepadConnectedObservable.remove(this._onGamepadConnectedObserver);
  69994. this.camera.getScene().gamepadManager.onGamepadDisconnectedObservable.remove(this._onGamepadDisconnectedObserver);
  69995. this.gamepad = null;
  69996. };
  69997. FreeCameraGamepadInput.prototype.checkInputs = function () {
  69998. if (this.gamepad && this.gamepad.leftStick) {
  69999. var camera = this.camera;
  70000. var LSValues = this.gamepad.leftStick;
  70001. var normalizedLX = LSValues.x / this.gamepadMoveSensibility;
  70002. var normalizedLY = LSValues.y / this.gamepadMoveSensibility;
  70003. LSValues.x = Math.abs(normalizedLX) > 0.005 ? 0 + normalizedLX : 0;
  70004. LSValues.y = Math.abs(normalizedLY) > 0.005 ? 0 + normalizedLY : 0;
  70005. var RSValues = this.gamepad.rightStick;
  70006. if (RSValues) {
  70007. var normalizedRX = RSValues.x / this.gamepadAngularSensibility;
  70008. var normalizedRY = RSValues.y / this.gamepadAngularSensibility;
  70009. RSValues.x = Math.abs(normalizedRX) > 0.001 ? 0 + normalizedRX : 0;
  70010. RSValues.y = Math.abs(normalizedRY) > 0.001 ? 0 + normalizedRY : 0;
  70011. }
  70012. else {
  70013. RSValues = { x: 0, y: 0 };
  70014. }
  70015. if (!camera.rotationQuaternion) {
  70016. BABYLON.Matrix.RotationYawPitchRollToRef(camera.rotation.y, camera.rotation.x, 0, this._cameraTransform);
  70017. }
  70018. else {
  70019. camera.rotationQuaternion.toRotationMatrix(this._cameraTransform);
  70020. }
  70021. var speed = camera._computeLocalCameraSpeed() * 50.0;
  70022. this._vector3.copyFromFloats(LSValues.x * speed, 0, -LSValues.y * speed);
  70023. BABYLON.Vector3.TransformCoordinatesToRef(this._vector3, this._cameraTransform, this._deltaTransform);
  70024. camera.cameraDirection.addInPlace(this._deltaTransform);
  70025. this._vector2.copyFromFloats(RSValues.y, RSValues.x);
  70026. camera.cameraRotation.addInPlace(this._vector2);
  70027. }
  70028. };
  70029. FreeCameraGamepadInput.prototype.getClassName = function () {
  70030. return "FreeCameraGamepadInput";
  70031. };
  70032. FreeCameraGamepadInput.prototype.getSimpleName = function () {
  70033. return "gamepad";
  70034. };
  70035. __decorate([
  70036. BABYLON.serialize()
  70037. ], FreeCameraGamepadInput.prototype, "gamepadAngularSensibility", void 0);
  70038. __decorate([
  70039. BABYLON.serialize()
  70040. ], FreeCameraGamepadInput.prototype, "gamepadMoveSensibility", void 0);
  70041. return FreeCameraGamepadInput;
  70042. }());
  70043. BABYLON.FreeCameraGamepadInput = FreeCameraGamepadInput;
  70044. BABYLON.CameraInputTypes["FreeCameraGamepadInput"] = FreeCameraGamepadInput;
  70045. })(BABYLON || (BABYLON = {}));
  70046. //# sourceMappingURL=babylon.freeCameraGamepadInput.js.map
  70047. var BABYLON;
  70048. (function (BABYLON) {
  70049. var ArcRotateCameraGamepadInput = /** @class */ (function () {
  70050. function ArcRotateCameraGamepadInput() {
  70051. this.gamepadRotationSensibility = 80;
  70052. this.gamepadMoveSensibility = 40;
  70053. }
  70054. ArcRotateCameraGamepadInput.prototype.attachControl = function (element, noPreventDefault) {
  70055. var _this = this;
  70056. var manager = this.camera.getScene().gamepadManager;
  70057. this._onGamepadConnectedObserver = manager.onGamepadConnectedObservable.add(function (gamepad) {
  70058. if (gamepad.type !== BABYLON.Gamepad.POSE_ENABLED) {
  70059. // prioritize XBOX gamepads.
  70060. if (!_this.gamepad || gamepad.type === BABYLON.Gamepad.XBOX) {
  70061. _this.gamepad = gamepad;
  70062. }
  70063. }
  70064. });
  70065. this._onGamepadDisconnectedObserver = manager.onGamepadDisconnectedObservable.add(function (gamepad) {
  70066. if (_this.gamepad === gamepad) {
  70067. _this.gamepad = null;
  70068. }
  70069. });
  70070. this.gamepad = manager.getGamepadByType(BABYLON.Gamepad.XBOX);
  70071. };
  70072. ArcRotateCameraGamepadInput.prototype.detachControl = function (element) {
  70073. this.camera.getScene().gamepadManager.onGamepadConnectedObservable.remove(this._onGamepadConnectedObserver);
  70074. this.camera.getScene().gamepadManager.onGamepadDisconnectedObservable.remove(this._onGamepadDisconnectedObserver);
  70075. this.gamepad = null;
  70076. };
  70077. ArcRotateCameraGamepadInput.prototype.checkInputs = function () {
  70078. if (this.gamepad) {
  70079. var camera = this.camera;
  70080. var RSValues = this.gamepad.rightStick;
  70081. if (RSValues) {
  70082. if (RSValues.x != 0) {
  70083. var normalizedRX = RSValues.x / this.gamepadRotationSensibility;
  70084. if (normalizedRX != 0 && Math.abs(normalizedRX) > 0.005) {
  70085. camera.inertialAlphaOffset += normalizedRX;
  70086. }
  70087. }
  70088. if (RSValues.y != 0) {
  70089. var normalizedRY = RSValues.y / this.gamepadRotationSensibility;
  70090. if (normalizedRY != 0 && Math.abs(normalizedRY) > 0.005) {
  70091. camera.inertialBetaOffset += normalizedRY;
  70092. }
  70093. }
  70094. }
  70095. var LSValues = this.gamepad.leftStick;
  70096. if (LSValues && LSValues.y != 0) {
  70097. var normalizedLY = LSValues.y / this.gamepadMoveSensibility;
  70098. if (normalizedLY != 0 && Math.abs(normalizedLY) > 0.005) {
  70099. this.camera.inertialRadiusOffset -= normalizedLY;
  70100. }
  70101. }
  70102. }
  70103. };
  70104. ArcRotateCameraGamepadInput.prototype.getClassName = function () {
  70105. return "ArcRotateCameraGamepadInput";
  70106. };
  70107. ArcRotateCameraGamepadInput.prototype.getSimpleName = function () {
  70108. return "gamepad";
  70109. };
  70110. __decorate([
  70111. BABYLON.serialize()
  70112. ], ArcRotateCameraGamepadInput.prototype, "gamepadRotationSensibility", void 0);
  70113. __decorate([
  70114. BABYLON.serialize()
  70115. ], ArcRotateCameraGamepadInput.prototype, "gamepadMoveSensibility", void 0);
  70116. return ArcRotateCameraGamepadInput;
  70117. }());
  70118. BABYLON.ArcRotateCameraGamepadInput = ArcRotateCameraGamepadInput;
  70119. BABYLON.CameraInputTypes["ArcRotateCameraGamepadInput"] = ArcRotateCameraGamepadInput;
  70120. })(BABYLON || (BABYLON = {}));
  70121. //# sourceMappingURL=babylon.arcRotateCameraGamepadInput.js.map
  70122. var BABYLON;
  70123. (function (BABYLON) {
  70124. var GamepadManager = /** @class */ (function () {
  70125. function GamepadManager(_scene) {
  70126. var _this = this;
  70127. this._scene = _scene;
  70128. this._babylonGamepads = [];
  70129. this._oneGamepadConnected = false;
  70130. this._isMonitoring = false;
  70131. this.onGamepadDisconnectedObservable = new BABYLON.Observable();
  70132. if (!BABYLON.Tools.IsWindowObjectExist()) {
  70133. this._gamepadEventSupported = false;
  70134. }
  70135. else {
  70136. this._gamepadEventSupported = 'GamepadEvent' in window;
  70137. this._gamepadSupport = (navigator.getGamepads ||
  70138. navigator.webkitGetGamepads || navigator.msGetGamepads || navigator.webkitGamepads);
  70139. }
  70140. this.onGamepadConnectedObservable = new BABYLON.Observable(function (observer) {
  70141. // This will be used to raise the onGamepadConnected for all gamepads ALREADY connected
  70142. for (var i in _this._babylonGamepads) {
  70143. var gamepad = _this._babylonGamepads[i];
  70144. if (gamepad && gamepad._isConnected) {
  70145. _this.onGamepadConnectedObservable.notifyObserver(observer, gamepad);
  70146. }
  70147. }
  70148. });
  70149. this._onGamepadConnectedEvent = function (evt) {
  70150. var gamepad = evt.gamepad;
  70151. if (gamepad.index in _this._babylonGamepads) {
  70152. if (_this._babylonGamepads[gamepad.index].isConnected) {
  70153. return;
  70154. }
  70155. }
  70156. var newGamepad;
  70157. if (_this._babylonGamepads[gamepad.index]) {
  70158. newGamepad = _this._babylonGamepads[gamepad.index];
  70159. newGamepad.browserGamepad = gamepad;
  70160. newGamepad._isConnected = true;
  70161. }
  70162. else {
  70163. newGamepad = _this._addNewGamepad(gamepad);
  70164. }
  70165. _this.onGamepadConnectedObservable.notifyObservers(newGamepad);
  70166. _this._startMonitoringGamepads();
  70167. };
  70168. this._onGamepadDisconnectedEvent = function (evt) {
  70169. var gamepad = evt.gamepad;
  70170. // Remove the gamepad from the list of gamepads to monitor.
  70171. for (var i in _this._babylonGamepads) {
  70172. if (_this._babylonGamepads[i].index === gamepad.index) {
  70173. var disconnectedGamepad = _this._babylonGamepads[i];
  70174. disconnectedGamepad._isConnected = false;
  70175. _this.onGamepadDisconnectedObservable.notifyObservers(disconnectedGamepad);
  70176. break;
  70177. }
  70178. }
  70179. };
  70180. if (this._gamepadSupport) {
  70181. //first add already-connected gamepads
  70182. this._updateGamepadObjects();
  70183. if (this._babylonGamepads.length) {
  70184. this._startMonitoringGamepads();
  70185. }
  70186. // Checking if the gamepad connected event is supported (like in Firefox)
  70187. if (this._gamepadEventSupported) {
  70188. window.addEventListener('gamepadconnected', this._onGamepadConnectedEvent, false);
  70189. window.addEventListener('gamepaddisconnected', this._onGamepadDisconnectedEvent, false);
  70190. }
  70191. else {
  70192. this._startMonitoringGamepads();
  70193. }
  70194. }
  70195. }
  70196. Object.defineProperty(GamepadManager.prototype, "gamepads", {
  70197. get: function () {
  70198. return this._babylonGamepads;
  70199. },
  70200. enumerable: true,
  70201. configurable: true
  70202. });
  70203. GamepadManager.prototype.getGamepadByType = function (type) {
  70204. if (type === void 0) { type = BABYLON.Gamepad.XBOX; }
  70205. for (var _i = 0, _a = this._babylonGamepads; _i < _a.length; _i++) {
  70206. var gamepad = _a[_i];
  70207. if (gamepad && gamepad.type === type) {
  70208. return gamepad;
  70209. }
  70210. }
  70211. return null;
  70212. };
  70213. GamepadManager.prototype.dispose = function () {
  70214. if (this._gamepadEventSupported) {
  70215. if (this._onGamepadConnectedEvent) {
  70216. window.removeEventListener('gamepadconnected', this._onGamepadConnectedEvent);
  70217. }
  70218. if (this._onGamepadDisconnectedEvent) {
  70219. window.removeEventListener('gamepaddisconnected', this._onGamepadDisconnectedEvent);
  70220. }
  70221. this._onGamepadConnectedEvent = null;
  70222. this._onGamepadDisconnectedEvent = null;
  70223. }
  70224. this._babylonGamepads.forEach(function (gamepad) {
  70225. gamepad.dispose();
  70226. });
  70227. this.onGamepadConnectedObservable.clear();
  70228. this.onGamepadDisconnectedObservable.clear();
  70229. this._oneGamepadConnected = false;
  70230. this._stopMonitoringGamepads();
  70231. this._babylonGamepads = [];
  70232. };
  70233. GamepadManager.prototype._addNewGamepad = function (gamepad) {
  70234. if (!this._oneGamepadConnected) {
  70235. this._oneGamepadConnected = true;
  70236. }
  70237. var newGamepad;
  70238. var xboxOne = (gamepad.id.search("Xbox One") !== -1);
  70239. if (xboxOne || gamepad.id.search("Xbox 360") !== -1 || gamepad.id.search("xinput") !== -1) {
  70240. newGamepad = new BABYLON.Xbox360Pad(gamepad.id, gamepad.index, gamepad, xboxOne);
  70241. }
  70242. // if pose is supported, use the (WebVR) pose enabled controller
  70243. else if (gamepad.pose) {
  70244. newGamepad = BABYLON.PoseEnabledControllerHelper.InitiateController(gamepad);
  70245. }
  70246. else {
  70247. newGamepad = new BABYLON.GenericPad(gamepad.id, gamepad.index, gamepad);
  70248. }
  70249. this._babylonGamepads[newGamepad.index] = newGamepad;
  70250. return newGamepad;
  70251. };
  70252. GamepadManager.prototype._startMonitoringGamepads = function () {
  70253. if (!this._isMonitoring) {
  70254. this._isMonitoring = true;
  70255. //back-comp
  70256. if (!this._scene) {
  70257. this._checkGamepadsStatus();
  70258. }
  70259. }
  70260. };
  70261. GamepadManager.prototype._stopMonitoringGamepads = function () {
  70262. this._isMonitoring = false;
  70263. };
  70264. GamepadManager.prototype._checkGamepadsStatus = function () {
  70265. var _this = this;
  70266. // Hack to be compatible Chrome
  70267. this._updateGamepadObjects();
  70268. for (var i in this._babylonGamepads) {
  70269. var gamepad = this._babylonGamepads[i];
  70270. if (!gamepad || !gamepad.isConnected) {
  70271. continue;
  70272. }
  70273. gamepad.update();
  70274. }
  70275. if (this._isMonitoring && !this._scene) {
  70276. BABYLON.Tools.QueueNewFrame(function () { _this._checkGamepadsStatus(); });
  70277. }
  70278. };
  70279. // This function is called only on Chrome, which does not properly support
  70280. // connection/disconnection events and forces you to recopy again the gamepad object
  70281. GamepadManager.prototype._updateGamepadObjects = function () {
  70282. var gamepads = navigator.getGamepads ? navigator.getGamepads() : (navigator.webkitGetGamepads ? navigator.webkitGetGamepads() : []);
  70283. for (var i = 0; i < gamepads.length; i++) {
  70284. var gamepad = gamepads[i];
  70285. if (gamepad) {
  70286. if (!this._babylonGamepads[gamepad.index]) {
  70287. var newGamepad = this._addNewGamepad(gamepad);
  70288. this.onGamepadConnectedObservable.notifyObservers(newGamepad);
  70289. }
  70290. else {
  70291. // Forced to copy again this object for Chrome for unknown reason
  70292. this._babylonGamepads[i].browserGamepad = gamepad;
  70293. if (!this._babylonGamepads[i].isConnected) {
  70294. this._babylonGamepads[i]._isConnected = true;
  70295. this.onGamepadConnectedObservable.notifyObservers(this._babylonGamepads[i]);
  70296. }
  70297. }
  70298. }
  70299. }
  70300. };
  70301. return GamepadManager;
  70302. }());
  70303. BABYLON.GamepadManager = GamepadManager;
  70304. })(BABYLON || (BABYLON = {}));
  70305. //# sourceMappingURL=babylon.gamepadManager.js.map
  70306. var BABYLON;
  70307. (function (BABYLON) {
  70308. var StickValues = /** @class */ (function () {
  70309. function StickValues(x, y) {
  70310. this.x = x;
  70311. this.y = y;
  70312. }
  70313. return StickValues;
  70314. }());
  70315. BABYLON.StickValues = StickValues;
  70316. var Gamepad = /** @class */ (function () {
  70317. function Gamepad(id, index, browserGamepad, leftStickX, leftStickY, rightStickX, rightStickY) {
  70318. if (leftStickX === void 0) { leftStickX = 0; }
  70319. if (leftStickY === void 0) { leftStickY = 1; }
  70320. if (rightStickX === void 0) { rightStickX = 2; }
  70321. if (rightStickY === void 0) { rightStickY = 3; }
  70322. this.id = id;
  70323. this.index = index;
  70324. this.browserGamepad = browserGamepad;
  70325. this._isConnected = true;
  70326. this._invertLeftStickY = false;
  70327. this.type = Gamepad.GAMEPAD;
  70328. this._leftStickAxisX = leftStickX;
  70329. this._leftStickAxisY = leftStickY;
  70330. this._rightStickAxisX = rightStickX;
  70331. this._rightStickAxisY = rightStickY;
  70332. if (this.browserGamepad.axes.length >= 2) {
  70333. this._leftStick = { x: this.browserGamepad.axes[this._leftStickAxisX], y: this.browserGamepad.axes[this._leftStickAxisY] };
  70334. }
  70335. if (this.browserGamepad.axes.length >= 4) {
  70336. this._rightStick = { x: this.browserGamepad.axes[this._rightStickAxisX], y: this.browserGamepad.axes[this._rightStickAxisY] };
  70337. }
  70338. }
  70339. Object.defineProperty(Gamepad.prototype, "isConnected", {
  70340. get: function () {
  70341. return this._isConnected;
  70342. },
  70343. enumerable: true,
  70344. configurable: true
  70345. });
  70346. Gamepad.prototype.onleftstickchanged = function (callback) {
  70347. this._onleftstickchanged = callback;
  70348. };
  70349. Gamepad.prototype.onrightstickchanged = function (callback) {
  70350. this._onrightstickchanged = callback;
  70351. };
  70352. Object.defineProperty(Gamepad.prototype, "leftStick", {
  70353. get: function () {
  70354. return this._leftStick;
  70355. },
  70356. set: function (newValues) {
  70357. if (this._onleftstickchanged && (this._leftStick.x !== newValues.x || this._leftStick.y !== newValues.y)) {
  70358. this._onleftstickchanged(newValues);
  70359. }
  70360. this._leftStick = newValues;
  70361. },
  70362. enumerable: true,
  70363. configurable: true
  70364. });
  70365. Object.defineProperty(Gamepad.prototype, "rightStick", {
  70366. get: function () {
  70367. return this._rightStick;
  70368. },
  70369. set: function (newValues) {
  70370. if (this._onrightstickchanged && (this._rightStick.x !== newValues.x || this._rightStick.y !== newValues.y)) {
  70371. this._onrightstickchanged(newValues);
  70372. }
  70373. this._rightStick = newValues;
  70374. },
  70375. enumerable: true,
  70376. configurable: true
  70377. });
  70378. Gamepad.prototype.update = function () {
  70379. if (this._leftStick) {
  70380. this.leftStick = { x: this.browserGamepad.axes[this._leftStickAxisX], y: this.browserGamepad.axes[this._leftStickAxisY] };
  70381. if (this._invertLeftStickY) {
  70382. this.leftStick.y *= -1;
  70383. }
  70384. }
  70385. if (this._rightStick) {
  70386. this.rightStick = { x: this.browserGamepad.axes[this._rightStickAxisX], y: this.browserGamepad.axes[this._rightStickAxisY] };
  70387. }
  70388. };
  70389. Gamepad.prototype.dispose = function () {
  70390. };
  70391. Gamepad.GAMEPAD = 0;
  70392. Gamepad.GENERIC = 1;
  70393. Gamepad.XBOX = 2;
  70394. Gamepad.POSE_ENABLED = 3;
  70395. return Gamepad;
  70396. }());
  70397. BABYLON.Gamepad = Gamepad;
  70398. var GenericPad = /** @class */ (function (_super) {
  70399. __extends(GenericPad, _super);
  70400. function GenericPad(id, index, browserGamepad) {
  70401. var _this = _super.call(this, id, index, browserGamepad) || this;
  70402. _this.onButtonDownObservable = new BABYLON.Observable();
  70403. _this.onButtonUpObservable = new BABYLON.Observable();
  70404. _this.type = Gamepad.GENERIC;
  70405. _this._buttons = new Array(browserGamepad.buttons.length);
  70406. return _this;
  70407. }
  70408. GenericPad.prototype.onbuttondown = function (callback) {
  70409. this._onbuttondown = callback;
  70410. };
  70411. GenericPad.prototype.onbuttonup = function (callback) {
  70412. this._onbuttonup = callback;
  70413. };
  70414. GenericPad.prototype._setButtonValue = function (newValue, currentValue, buttonIndex) {
  70415. if (newValue !== currentValue) {
  70416. if (newValue === 1) {
  70417. if (this._onbuttondown) {
  70418. this._onbuttondown(buttonIndex);
  70419. }
  70420. this.onButtonDownObservable.notifyObservers(buttonIndex);
  70421. }
  70422. if (newValue === 0) {
  70423. if (this._onbuttonup) {
  70424. this._onbuttonup(buttonIndex);
  70425. }
  70426. this.onButtonUpObservable.notifyObservers(buttonIndex);
  70427. }
  70428. }
  70429. return newValue;
  70430. };
  70431. GenericPad.prototype.update = function () {
  70432. _super.prototype.update.call(this);
  70433. for (var index = 0; index < this._buttons.length; index++) {
  70434. this._buttons[index] = this._setButtonValue(this.browserGamepad.buttons[index].value, this._buttons[index], index);
  70435. }
  70436. };
  70437. GenericPad.prototype.dispose = function () {
  70438. _super.prototype.dispose.call(this);
  70439. this.onButtonDownObservable.clear();
  70440. this.onButtonUpObservable.clear();
  70441. };
  70442. return GenericPad;
  70443. }(Gamepad));
  70444. BABYLON.GenericPad = GenericPad;
  70445. })(BABYLON || (BABYLON = {}));
  70446. //# sourceMappingURL=babylon.gamepad.js.map
  70447. var BABYLON;
  70448. (function (BABYLON) {
  70449. /**
  70450. * Defines supported buttons for XBox360 compatible gamepads
  70451. */
  70452. var Xbox360Button;
  70453. (function (Xbox360Button) {
  70454. /** A */
  70455. Xbox360Button[Xbox360Button["A"] = 0] = "A";
  70456. /** B */
  70457. Xbox360Button[Xbox360Button["B"] = 1] = "B";
  70458. /** X */
  70459. Xbox360Button[Xbox360Button["X"] = 2] = "X";
  70460. /** Y */
  70461. Xbox360Button[Xbox360Button["Y"] = 3] = "Y";
  70462. /** Start */
  70463. Xbox360Button[Xbox360Button["Start"] = 4] = "Start";
  70464. /** Back */
  70465. Xbox360Button[Xbox360Button["Back"] = 5] = "Back";
  70466. /** Left button */
  70467. Xbox360Button[Xbox360Button["LB"] = 6] = "LB";
  70468. /** Right button */
  70469. Xbox360Button[Xbox360Button["RB"] = 7] = "RB";
  70470. /** Left stick */
  70471. Xbox360Button[Xbox360Button["LeftStick"] = 8] = "LeftStick";
  70472. /** Right stick */
  70473. Xbox360Button[Xbox360Button["RightStick"] = 9] = "RightStick";
  70474. })(Xbox360Button = BABYLON.Xbox360Button || (BABYLON.Xbox360Button = {}));
  70475. /** Defines values for XBox360 DPad */
  70476. var Xbox360Dpad;
  70477. (function (Xbox360Dpad) {
  70478. /** Up */
  70479. Xbox360Dpad[Xbox360Dpad["Up"] = 0] = "Up";
  70480. /** Down */
  70481. Xbox360Dpad[Xbox360Dpad["Down"] = 1] = "Down";
  70482. /** Left */
  70483. Xbox360Dpad[Xbox360Dpad["Left"] = 2] = "Left";
  70484. /** Right */
  70485. Xbox360Dpad[Xbox360Dpad["Right"] = 3] = "Right";
  70486. })(Xbox360Dpad = BABYLON.Xbox360Dpad || (BABYLON.Xbox360Dpad = {}));
  70487. /**
  70488. * Defines a XBox360 gamepad
  70489. */
  70490. var Xbox360Pad = /** @class */ (function (_super) {
  70491. __extends(Xbox360Pad, _super);
  70492. /**
  70493. * Creates a new XBox360 gamepad object
  70494. * @param id defines the id of this gamepad
  70495. * @param index defines its index
  70496. * @param gamepad defines the internal HTML gamepad object
  70497. * @param xboxOne defines if it is a XBox One gamepad
  70498. */
  70499. function Xbox360Pad(id, index, gamepad, xboxOne) {
  70500. if (xboxOne === void 0) { xboxOne = false; }
  70501. var _this = _super.call(this, id, index, gamepad, 0, 1, 2, 3) || this;
  70502. _this._leftTrigger = 0;
  70503. _this._rightTrigger = 0;
  70504. /** Observable raised when a button is pressed */
  70505. _this.onButtonDownObservable = new BABYLON.Observable();
  70506. /** Observable raised when a button is released */
  70507. _this.onButtonUpObservable = new BABYLON.Observable();
  70508. /** Observable raised when a pad is pressed */
  70509. _this.onPadDownObservable = new BABYLON.Observable();
  70510. /** Observable raised when a pad is released */
  70511. _this.onPadUpObservable = new BABYLON.Observable();
  70512. _this._buttonA = 0;
  70513. _this._buttonB = 0;
  70514. _this._buttonX = 0;
  70515. _this._buttonY = 0;
  70516. _this._buttonBack = 0;
  70517. _this._buttonStart = 0;
  70518. _this._buttonLB = 0;
  70519. _this._buttonRB = 0;
  70520. _this._buttonLeftStick = 0;
  70521. _this._buttonRightStick = 0;
  70522. _this._dPadUp = 0;
  70523. _this._dPadDown = 0;
  70524. _this._dPadLeft = 0;
  70525. _this._dPadRight = 0;
  70526. _this._isXboxOnePad = false;
  70527. _this.type = BABYLON.Gamepad.XBOX;
  70528. _this._isXboxOnePad = xboxOne;
  70529. return _this;
  70530. }
  70531. /**
  70532. * Defines the callback to call when left trigger is pressed
  70533. * @param callback defines the callback to use
  70534. */
  70535. Xbox360Pad.prototype.onlefttriggerchanged = function (callback) {
  70536. this._onlefttriggerchanged = callback;
  70537. };
  70538. /**
  70539. * Defines the callback to call when right trigger is pressed
  70540. * @param callback defines the callback to use
  70541. */
  70542. Xbox360Pad.prototype.onrighttriggerchanged = function (callback) {
  70543. this._onrighttriggerchanged = callback;
  70544. };
  70545. Object.defineProperty(Xbox360Pad.prototype, "leftTrigger", {
  70546. /**
  70547. * Gets or sets left trigger value
  70548. */
  70549. get: function () {
  70550. return this._leftTrigger;
  70551. },
  70552. set: function (newValue) {
  70553. if (this._onlefttriggerchanged && this._leftTrigger !== newValue) {
  70554. this._onlefttriggerchanged(newValue);
  70555. }
  70556. this._leftTrigger = newValue;
  70557. },
  70558. enumerable: true,
  70559. configurable: true
  70560. });
  70561. Object.defineProperty(Xbox360Pad.prototype, "rightTrigger", {
  70562. /**
  70563. * Gets or sets right trigger value
  70564. */
  70565. get: function () {
  70566. return this._rightTrigger;
  70567. },
  70568. set: function (newValue) {
  70569. if (this._onrighttriggerchanged && this._rightTrigger !== newValue) {
  70570. this._onrighttriggerchanged(newValue);
  70571. }
  70572. this._rightTrigger = newValue;
  70573. },
  70574. enumerable: true,
  70575. configurable: true
  70576. });
  70577. /**
  70578. * Defines the callback to call when a button is pressed
  70579. * @param callback defines the callback to use
  70580. */
  70581. Xbox360Pad.prototype.onbuttondown = function (callback) {
  70582. this._onbuttondown = callback;
  70583. };
  70584. /**
  70585. * Defines the callback to call when a button is released
  70586. * @param callback defines the callback to use
  70587. */
  70588. Xbox360Pad.prototype.onbuttonup = function (callback) {
  70589. this._onbuttonup = callback;
  70590. };
  70591. /**
  70592. * Defines the callback to call when a pad is pressed
  70593. * @param callback defines the callback to use
  70594. */
  70595. Xbox360Pad.prototype.ondpaddown = function (callback) {
  70596. this._ondpaddown = callback;
  70597. };
  70598. /**
  70599. * Defines the callback to call when a pad is released
  70600. * @param callback defines the callback to use
  70601. */
  70602. Xbox360Pad.prototype.ondpadup = function (callback) {
  70603. this._ondpadup = callback;
  70604. };
  70605. Xbox360Pad.prototype._setButtonValue = function (newValue, currentValue, buttonType) {
  70606. if (newValue !== currentValue) {
  70607. if (newValue === 1) {
  70608. if (this._onbuttondown) {
  70609. this._onbuttondown(buttonType);
  70610. }
  70611. this.onButtonDownObservable.notifyObservers(buttonType);
  70612. }
  70613. if (newValue === 0) {
  70614. if (this._onbuttonup) {
  70615. this._onbuttonup(buttonType);
  70616. }
  70617. this.onButtonUpObservable.notifyObservers(buttonType);
  70618. }
  70619. }
  70620. return newValue;
  70621. };
  70622. Xbox360Pad.prototype._setDPadValue = function (newValue, currentValue, buttonType) {
  70623. if (newValue !== currentValue) {
  70624. if (newValue === 1) {
  70625. if (this._ondpaddown) {
  70626. this._ondpaddown(buttonType);
  70627. }
  70628. this.onPadDownObservable.notifyObservers(buttonType);
  70629. }
  70630. if (newValue === 0) {
  70631. if (this._ondpadup) {
  70632. this._ondpadup(buttonType);
  70633. }
  70634. this.onPadUpObservable.notifyObservers(buttonType);
  70635. }
  70636. }
  70637. return newValue;
  70638. };
  70639. Object.defineProperty(Xbox360Pad.prototype, "buttonA", {
  70640. /** Gets or sets value of A button */
  70641. get: function () {
  70642. return this._buttonA;
  70643. },
  70644. set: function (value) {
  70645. this._buttonA = this._setButtonValue(value, this._buttonA, Xbox360Button.A);
  70646. },
  70647. enumerable: true,
  70648. configurable: true
  70649. });
  70650. Object.defineProperty(Xbox360Pad.prototype, "buttonB", {
  70651. /** Gets or sets value of B button */
  70652. get: function () {
  70653. return this._buttonB;
  70654. },
  70655. set: function (value) {
  70656. this._buttonB = this._setButtonValue(value, this._buttonB, Xbox360Button.B);
  70657. },
  70658. enumerable: true,
  70659. configurable: true
  70660. });
  70661. Object.defineProperty(Xbox360Pad.prototype, "buttonX", {
  70662. /** Gets or sets value of X button */
  70663. get: function () {
  70664. return this._buttonX;
  70665. },
  70666. set: function (value) {
  70667. this._buttonX = this._setButtonValue(value, this._buttonX, Xbox360Button.X);
  70668. },
  70669. enumerable: true,
  70670. configurable: true
  70671. });
  70672. Object.defineProperty(Xbox360Pad.prototype, "buttonY", {
  70673. /** Gets or sets value of Y button */
  70674. get: function () {
  70675. return this._buttonY;
  70676. },
  70677. set: function (value) {
  70678. this._buttonY = this._setButtonValue(value, this._buttonY, Xbox360Button.Y);
  70679. },
  70680. enumerable: true,
  70681. configurable: true
  70682. });
  70683. Object.defineProperty(Xbox360Pad.prototype, "buttonStart", {
  70684. /** Gets or sets value of Start button */
  70685. get: function () {
  70686. return this._buttonStart;
  70687. },
  70688. set: function (value) {
  70689. this._buttonStart = this._setButtonValue(value, this._buttonStart, Xbox360Button.Start);
  70690. },
  70691. enumerable: true,
  70692. configurable: true
  70693. });
  70694. Object.defineProperty(Xbox360Pad.prototype, "buttonBack", {
  70695. /** Gets or sets value of Back button */
  70696. get: function () {
  70697. return this._buttonBack;
  70698. },
  70699. set: function (value) {
  70700. this._buttonBack = this._setButtonValue(value, this._buttonBack, Xbox360Button.Back);
  70701. },
  70702. enumerable: true,
  70703. configurable: true
  70704. });
  70705. Object.defineProperty(Xbox360Pad.prototype, "buttonLB", {
  70706. /** Gets or sets value of Left button */
  70707. get: function () {
  70708. return this._buttonLB;
  70709. },
  70710. set: function (value) {
  70711. this._buttonLB = this._setButtonValue(value, this._buttonLB, Xbox360Button.LB);
  70712. },
  70713. enumerable: true,
  70714. configurable: true
  70715. });
  70716. Object.defineProperty(Xbox360Pad.prototype, "buttonRB", {
  70717. /** Gets or sets value of Right button */
  70718. get: function () {
  70719. return this._buttonRB;
  70720. },
  70721. set: function (value) {
  70722. this._buttonRB = this._setButtonValue(value, this._buttonRB, Xbox360Button.RB);
  70723. },
  70724. enumerable: true,
  70725. configurable: true
  70726. });
  70727. Object.defineProperty(Xbox360Pad.prototype, "buttonLeftStick", {
  70728. /** Gets or sets value of left stick */
  70729. get: function () {
  70730. return this._buttonLeftStick;
  70731. },
  70732. set: function (value) {
  70733. this._buttonLeftStick = this._setButtonValue(value, this._buttonLeftStick, Xbox360Button.LeftStick);
  70734. },
  70735. enumerable: true,
  70736. configurable: true
  70737. });
  70738. Object.defineProperty(Xbox360Pad.prototype, "buttonRightStick", {
  70739. /** Gets or sets value of right stick */
  70740. get: function () {
  70741. return this._buttonRightStick;
  70742. },
  70743. set: function (value) {
  70744. this._buttonRightStick = this._setButtonValue(value, this._buttonRightStick, Xbox360Button.RightStick);
  70745. },
  70746. enumerable: true,
  70747. configurable: true
  70748. });
  70749. Object.defineProperty(Xbox360Pad.prototype, "dPadUp", {
  70750. /** Gets or sets value of DPad up */
  70751. get: function () {
  70752. return this._dPadUp;
  70753. },
  70754. set: function (value) {
  70755. this._dPadUp = this._setDPadValue(value, this._dPadUp, Xbox360Dpad.Up);
  70756. },
  70757. enumerable: true,
  70758. configurable: true
  70759. });
  70760. Object.defineProperty(Xbox360Pad.prototype, "dPadDown", {
  70761. /** Gets or sets value of DPad down */
  70762. get: function () {
  70763. return this._dPadDown;
  70764. },
  70765. set: function (value) {
  70766. this._dPadDown = this._setDPadValue(value, this._dPadDown, Xbox360Dpad.Down);
  70767. },
  70768. enumerable: true,
  70769. configurable: true
  70770. });
  70771. Object.defineProperty(Xbox360Pad.prototype, "dPadLeft", {
  70772. /** Gets or sets value of DPad left */
  70773. get: function () {
  70774. return this._dPadLeft;
  70775. },
  70776. set: function (value) {
  70777. this._dPadLeft = this._setDPadValue(value, this._dPadLeft, Xbox360Dpad.Left);
  70778. },
  70779. enumerable: true,
  70780. configurable: true
  70781. });
  70782. Object.defineProperty(Xbox360Pad.prototype, "dPadRight", {
  70783. /** Gets or sets value of DPad right */
  70784. get: function () {
  70785. return this._dPadRight;
  70786. },
  70787. set: function (value) {
  70788. this._dPadRight = this._setDPadValue(value, this._dPadRight, Xbox360Dpad.Right);
  70789. },
  70790. enumerable: true,
  70791. configurable: true
  70792. });
  70793. /**
  70794. * Force the gamepad to synchronize with device values
  70795. */
  70796. Xbox360Pad.prototype.update = function () {
  70797. _super.prototype.update.call(this);
  70798. if (this._isXboxOnePad) {
  70799. this.buttonA = this.browserGamepad.buttons[0].value;
  70800. this.buttonB = this.browserGamepad.buttons[1].value;
  70801. this.buttonX = this.browserGamepad.buttons[2].value;
  70802. this.buttonY = this.browserGamepad.buttons[3].value;
  70803. this.buttonLB = this.browserGamepad.buttons[4].value;
  70804. this.buttonRB = this.browserGamepad.buttons[5].value;
  70805. this.leftTrigger = this.browserGamepad.axes[2];
  70806. this.rightTrigger = this.browserGamepad.axes[5];
  70807. this.buttonBack = this.browserGamepad.buttons[9].value;
  70808. this.buttonStart = this.browserGamepad.buttons[8].value;
  70809. this.buttonLeftStick = this.browserGamepad.buttons[6].value;
  70810. this.buttonRightStick = this.browserGamepad.buttons[7].value;
  70811. this.dPadUp = this.browserGamepad.buttons[11].value;
  70812. this.dPadDown = this.browserGamepad.buttons[12].value;
  70813. this.dPadLeft = this.browserGamepad.buttons[13].value;
  70814. this.dPadRight = this.browserGamepad.buttons[14].value;
  70815. }
  70816. else {
  70817. this.buttonA = this.browserGamepad.buttons[0].value;
  70818. this.buttonB = this.browserGamepad.buttons[1].value;
  70819. this.buttonX = this.browserGamepad.buttons[2].value;
  70820. this.buttonY = this.browserGamepad.buttons[3].value;
  70821. this.buttonLB = this.browserGamepad.buttons[4].value;
  70822. this.buttonRB = this.browserGamepad.buttons[5].value;
  70823. this.leftTrigger = this.browserGamepad.buttons[6].value;
  70824. this.rightTrigger = this.browserGamepad.buttons[7].value;
  70825. this.buttonBack = this.browserGamepad.buttons[8].value;
  70826. this.buttonStart = this.browserGamepad.buttons[9].value;
  70827. this.buttonLeftStick = this.browserGamepad.buttons[10].value;
  70828. this.buttonRightStick = this.browserGamepad.buttons[11].value;
  70829. this.dPadUp = this.browserGamepad.buttons[12].value;
  70830. this.dPadDown = this.browserGamepad.buttons[13].value;
  70831. this.dPadLeft = this.browserGamepad.buttons[14].value;
  70832. this.dPadRight = this.browserGamepad.buttons[15].value;
  70833. }
  70834. };
  70835. Xbox360Pad.prototype.dispose = function () {
  70836. _super.prototype.dispose.call(this);
  70837. this.onButtonDownObservable.clear();
  70838. this.onButtonUpObservable.clear();
  70839. this.onPadDownObservable.clear();
  70840. this.onPadUpObservable.clear();
  70841. };
  70842. return Xbox360Pad;
  70843. }(BABYLON.Gamepad));
  70844. BABYLON.Xbox360Pad = Xbox360Pad;
  70845. })(BABYLON || (BABYLON = {}));
  70846. //# sourceMappingURL=babylon.xboxGamepad.js.map
  70847. var BABYLON;
  70848. (function (BABYLON) {
  70849. /**
  70850. * Defines the types of pose enabled controllers that are supported
  70851. */
  70852. var PoseEnabledControllerType;
  70853. (function (PoseEnabledControllerType) {
  70854. /**
  70855. * HTC Vive
  70856. */
  70857. PoseEnabledControllerType[PoseEnabledControllerType["VIVE"] = 0] = "VIVE";
  70858. /**
  70859. * Oculus Rift
  70860. */
  70861. PoseEnabledControllerType[PoseEnabledControllerType["OCULUS"] = 1] = "OCULUS";
  70862. /**
  70863. * Windows mixed reality
  70864. */
  70865. PoseEnabledControllerType[PoseEnabledControllerType["WINDOWS"] = 2] = "WINDOWS";
  70866. /**
  70867. * Samsung gear VR
  70868. */
  70869. PoseEnabledControllerType[PoseEnabledControllerType["GEAR_VR"] = 3] = "GEAR_VR";
  70870. /**
  70871. * Google Daydream
  70872. */
  70873. PoseEnabledControllerType[PoseEnabledControllerType["DAYDREAM"] = 4] = "DAYDREAM";
  70874. /**
  70875. * Generic
  70876. */
  70877. PoseEnabledControllerType[PoseEnabledControllerType["GENERIC"] = 5] = "GENERIC";
  70878. })(PoseEnabledControllerType = BABYLON.PoseEnabledControllerType || (BABYLON.PoseEnabledControllerType = {}));
  70879. /**
  70880. * Defines the PoseEnabledControllerHelper object that is used initialize a gamepad as the controller type it is specified as (eg. windows mixed reality controller)
  70881. */
  70882. var PoseEnabledControllerHelper = /** @class */ (function () {
  70883. function PoseEnabledControllerHelper() {
  70884. }
  70885. /**
  70886. * Initializes a gamepad as the controller type it is specified as (eg. windows mixed reality controller)
  70887. * @param vrGamepad the gamepad to initialized
  70888. * @returns a vr controller of the type the gamepad identified as
  70889. */
  70890. PoseEnabledControllerHelper.InitiateController = function (vrGamepad) {
  70891. // Oculus Touch
  70892. if (vrGamepad.id.indexOf('Oculus Touch') !== -1) {
  70893. return new BABYLON.OculusTouchController(vrGamepad);
  70894. }
  70895. // Windows Mixed Reality controllers
  70896. else if (vrGamepad.id.indexOf(BABYLON.WindowsMotionController.GAMEPAD_ID_PREFIX) === 0) {
  70897. return new BABYLON.WindowsMotionController(vrGamepad);
  70898. }
  70899. // HTC Vive
  70900. else if (vrGamepad.id.toLowerCase().indexOf('openvr') !== -1) {
  70901. return new BABYLON.ViveController(vrGamepad);
  70902. }
  70903. // Samsung/Oculus Gear VR
  70904. else if (vrGamepad.id.indexOf(BABYLON.GearVRController.GAMEPAD_ID_PREFIX) === 0) {
  70905. return new BABYLON.GearVRController(vrGamepad);
  70906. }
  70907. // Google Daydream
  70908. else if (vrGamepad.id.indexOf(BABYLON.DaydreamController.GAMEPAD_ID_PREFIX) === 0) {
  70909. return new BABYLON.DaydreamController(vrGamepad);
  70910. }
  70911. // Generic
  70912. else {
  70913. return new BABYLON.GenericController(vrGamepad);
  70914. }
  70915. };
  70916. return PoseEnabledControllerHelper;
  70917. }());
  70918. BABYLON.PoseEnabledControllerHelper = PoseEnabledControllerHelper;
  70919. /**
  70920. * Defines the PoseEnabledController object that contains state of a vr capable controller
  70921. */
  70922. var PoseEnabledController = /** @class */ (function (_super) {
  70923. __extends(PoseEnabledController, _super);
  70924. /**
  70925. * Creates a new PoseEnabledController from a gamepad
  70926. * @param browserGamepad the gamepad that the PoseEnabledController should be created from
  70927. */
  70928. function PoseEnabledController(browserGamepad) {
  70929. var _this = _super.call(this, browserGamepad.id, browserGamepad.index, browserGamepad) || this;
  70930. // Represents device position and rotation in room space. Should only be used to help calculate babylon space values
  70931. _this._deviceRoomPosition = BABYLON.Vector3.Zero();
  70932. _this._deviceRoomRotationQuaternion = new BABYLON.Quaternion();
  70933. /**
  70934. * The device position in babylon space
  70935. */
  70936. _this.devicePosition = BABYLON.Vector3.Zero();
  70937. /**
  70938. * The device rotation in babylon space
  70939. */
  70940. _this.deviceRotationQuaternion = new BABYLON.Quaternion();
  70941. /**
  70942. * The scale factor of the device in babylon space
  70943. */
  70944. _this.deviceScaleFactor = 1;
  70945. _this._leftHandSystemQuaternion = new BABYLON.Quaternion();
  70946. /**
  70947. * Internal, matrix used to convert room space to babylon space
  70948. */
  70949. _this._deviceToWorld = BABYLON.Matrix.Identity();
  70950. /**
  70951. * Node to be used when casting a ray from the controller
  70952. */
  70953. _this._pointingPoseNode = null;
  70954. _this._workingMatrix = BABYLON.Matrix.Identity();
  70955. _this.type = BABYLON.Gamepad.POSE_ENABLED;
  70956. _this.controllerType = PoseEnabledControllerType.GENERIC;
  70957. _this.position = BABYLON.Vector3.Zero();
  70958. _this.rotationQuaternion = new BABYLON.Quaternion();
  70959. _this._calculatedPosition = BABYLON.Vector3.Zero();
  70960. _this._calculatedRotation = new BABYLON.Quaternion();
  70961. BABYLON.Quaternion.RotationYawPitchRollToRef(Math.PI, 0, 0, _this._leftHandSystemQuaternion);
  70962. return _this;
  70963. }
  70964. /**
  70965. * Updates the state of the pose enbaled controller and mesh based on the current position and rotation of the controller
  70966. */
  70967. PoseEnabledController.prototype.update = function () {
  70968. _super.prototype.update.call(this);
  70969. var pose = this.browserGamepad.pose;
  70970. this.updateFromDevice(pose);
  70971. BABYLON.Vector3.TransformCoordinatesToRef(this._calculatedPosition, this._deviceToWorld, this.devicePosition);
  70972. this._deviceToWorld.getRotationMatrixToRef(this._workingMatrix);
  70973. BABYLON.Quaternion.FromRotationMatrixToRef(this._workingMatrix, this.deviceRotationQuaternion);
  70974. this.deviceRotationQuaternion.multiplyInPlace(this._calculatedRotation);
  70975. if (this._mesh) {
  70976. this._mesh.position.copyFrom(this.devicePosition);
  70977. if (this._mesh.rotationQuaternion) {
  70978. this._mesh.rotationQuaternion.copyFrom(this.deviceRotationQuaternion);
  70979. }
  70980. }
  70981. };
  70982. /**
  70983. * Updates the state of the pose enbaled controller based on the raw pose data from the device
  70984. * @param poseData raw pose fromthe device
  70985. */
  70986. PoseEnabledController.prototype.updateFromDevice = function (poseData) {
  70987. if (poseData) {
  70988. this.rawPose = poseData;
  70989. if (poseData.position) {
  70990. this._deviceRoomPosition.copyFromFloats(poseData.position[0], poseData.position[1], -poseData.position[2]);
  70991. if (this._mesh && this._mesh.getScene().useRightHandedSystem) {
  70992. this._deviceRoomPosition.z *= -1;
  70993. }
  70994. this._deviceRoomPosition.scaleToRef(this.deviceScaleFactor, this._calculatedPosition);
  70995. this._calculatedPosition.addInPlace(this.position);
  70996. }
  70997. var pose = this.rawPose;
  70998. if (poseData.orientation && pose.orientation) {
  70999. this._deviceRoomRotationQuaternion.copyFromFloats(pose.orientation[0], pose.orientation[1], -pose.orientation[2], -pose.orientation[3]);
  71000. if (this._mesh) {
  71001. if (this._mesh.getScene().useRightHandedSystem) {
  71002. this._deviceRoomRotationQuaternion.z *= -1;
  71003. this._deviceRoomRotationQuaternion.w *= -1;
  71004. }
  71005. else {
  71006. this._deviceRoomRotationQuaternion.multiplyToRef(this._leftHandSystemQuaternion, this._deviceRoomRotationQuaternion);
  71007. }
  71008. }
  71009. // if the camera is set, rotate to the camera's rotation
  71010. this._deviceRoomRotationQuaternion.multiplyToRef(this.rotationQuaternion, this._calculatedRotation);
  71011. }
  71012. }
  71013. };
  71014. /**
  71015. * Attaches a mesh to the controller
  71016. * @param mesh the mesh to be attached
  71017. */
  71018. PoseEnabledController.prototype.attachToMesh = function (mesh) {
  71019. if (this._mesh) {
  71020. this._mesh.parent = null;
  71021. }
  71022. this._mesh = mesh;
  71023. if (this._poseControlledCamera) {
  71024. this._mesh.parent = this._poseControlledCamera;
  71025. }
  71026. if (!this._mesh.rotationQuaternion) {
  71027. this._mesh.rotationQuaternion = new BABYLON.Quaternion();
  71028. }
  71029. };
  71030. /**
  71031. * Attaches the controllers mesh to a camera
  71032. * @param camera the camera the mesh should be attached to
  71033. */
  71034. PoseEnabledController.prototype.attachToPoseControlledCamera = function (camera) {
  71035. this._poseControlledCamera = camera;
  71036. if (this._mesh) {
  71037. this._mesh.parent = this._poseControlledCamera;
  71038. }
  71039. };
  71040. /**
  71041. * Disposes of the controller
  71042. */
  71043. PoseEnabledController.prototype.dispose = function () {
  71044. if (this._mesh) {
  71045. this._mesh.dispose();
  71046. }
  71047. this._mesh = null;
  71048. _super.prototype.dispose.call(this);
  71049. };
  71050. Object.defineProperty(PoseEnabledController.prototype, "mesh", {
  71051. /**
  71052. * The mesh that is attached to the controller
  71053. */
  71054. get: function () {
  71055. return this._mesh;
  71056. },
  71057. enumerable: true,
  71058. configurable: true
  71059. });
  71060. /**
  71061. * Gets the ray of the controller in the direction the controller is pointing
  71062. * @param length the length the resulting ray should be
  71063. * @returns a ray in the direction the controller is pointing
  71064. */
  71065. PoseEnabledController.prototype.getForwardRay = function (length) {
  71066. if (length === void 0) { length = 100; }
  71067. if (!this.mesh) {
  71068. return new BABYLON.Ray(BABYLON.Vector3.Zero(), new BABYLON.Vector3(0, 0, 1), length);
  71069. }
  71070. var m = this._pointingPoseNode ? this._pointingPoseNode.getWorldMatrix() : this.mesh.getWorldMatrix();
  71071. var origin = m.getTranslation();
  71072. var forward = new BABYLON.Vector3(0, 0, -1);
  71073. var forwardWorld = BABYLON.Vector3.TransformNormal(forward, m);
  71074. var direction = BABYLON.Vector3.Normalize(forwardWorld);
  71075. return new BABYLON.Ray(origin, direction, length);
  71076. };
  71077. /**
  71078. * Name of the child mesh that can be used to cast a ray from the controller
  71079. */
  71080. PoseEnabledController.POINTING_POSE = "POINTING_POSE";
  71081. return PoseEnabledController;
  71082. }(BABYLON.Gamepad));
  71083. BABYLON.PoseEnabledController = PoseEnabledController;
  71084. })(BABYLON || (BABYLON = {}));
  71085. //# sourceMappingURL=babylon.poseEnabledController.js.map
  71086. var BABYLON;
  71087. (function (BABYLON) {
  71088. /**
  71089. * Defines the WebVRController object that represents controllers tracked in 3D space
  71090. */
  71091. var WebVRController = /** @class */ (function (_super) {
  71092. __extends(WebVRController, _super);
  71093. /**
  71094. * Creates a new WebVRController from a gamepad
  71095. * @param vrGamepad the gamepad that the WebVRController should be created from
  71096. */
  71097. function WebVRController(vrGamepad) {
  71098. var _this = _super.call(this, vrGamepad) || this;
  71099. // Observables
  71100. /**
  71101. * Fired when the trigger state has changed
  71102. */
  71103. _this.onTriggerStateChangedObservable = new BABYLON.Observable();
  71104. /**
  71105. * Fired when the main button state has changed
  71106. */
  71107. _this.onMainButtonStateChangedObservable = new BABYLON.Observable();
  71108. /**
  71109. * Fired when the secondary button state has changed
  71110. */
  71111. _this.onSecondaryButtonStateChangedObservable = new BABYLON.Observable();
  71112. /**
  71113. * Fired when the pad state has changed
  71114. */
  71115. _this.onPadStateChangedObservable = new BABYLON.Observable();
  71116. /**
  71117. * Fired when controllers stick values have changed
  71118. */
  71119. _this.onPadValuesChangedObservable = new BABYLON.Observable();
  71120. /**
  71121. * X and Y axis corrisponding to the controllers joystick
  71122. */
  71123. _this.pad = { x: 0, y: 0 };
  71124. // avoid GC, store state in a tmp object
  71125. _this._changes = {
  71126. pressChanged: false,
  71127. touchChanged: false,
  71128. valueChanged: false,
  71129. changed: false
  71130. };
  71131. _this._buttons = new Array(vrGamepad.buttons.length);
  71132. _this.hand = vrGamepad.hand;
  71133. return _this;
  71134. }
  71135. /**
  71136. * Fired when a controller button's state has changed
  71137. * @param callback the callback containing the button that was modified
  71138. */
  71139. WebVRController.prototype.onButtonStateChange = function (callback) {
  71140. this._onButtonStateChange = callback;
  71141. };
  71142. Object.defineProperty(WebVRController.prototype, "defaultModel", {
  71143. /**
  71144. * The default controller model for the controller
  71145. */
  71146. get: function () {
  71147. return this._defaultModel;
  71148. },
  71149. enumerable: true,
  71150. configurable: true
  71151. });
  71152. /**
  71153. * Updates the state of the controller and mesh based on the current position and rotation of the controller
  71154. */
  71155. WebVRController.prototype.update = function () {
  71156. _super.prototype.update.call(this);
  71157. for (var index = 0; index < this._buttons.length; index++) {
  71158. this._setButtonValue(this.browserGamepad.buttons[index], this._buttons[index], index);
  71159. }
  71160. ;
  71161. if (this.leftStick.x !== this.pad.x || this.leftStick.y !== this.pad.y) {
  71162. this.pad.x = this.leftStick.x;
  71163. this.pad.y = this.leftStick.y;
  71164. this.onPadValuesChangedObservable.notifyObservers(this.pad);
  71165. }
  71166. };
  71167. WebVRController.prototype._setButtonValue = function (newState, currentState, buttonIndex) {
  71168. if (!newState) {
  71169. newState = {
  71170. pressed: false,
  71171. touched: false,
  71172. value: 0
  71173. };
  71174. }
  71175. if (!currentState) {
  71176. this._buttons[buttonIndex] = {
  71177. pressed: newState.pressed,
  71178. touched: newState.touched,
  71179. value: newState.value
  71180. };
  71181. return;
  71182. }
  71183. this._checkChanges(newState, currentState);
  71184. if (this._changes.changed) {
  71185. this._onButtonStateChange && this._onButtonStateChange(this.index, buttonIndex, newState);
  71186. this._handleButtonChange(buttonIndex, newState, this._changes);
  71187. }
  71188. this._buttons[buttonIndex].pressed = newState.pressed;
  71189. this._buttons[buttonIndex].touched = newState.touched;
  71190. // oculus triggers are never 0, thou not touched.
  71191. this._buttons[buttonIndex].value = newState.value < 0.00000001 ? 0 : newState.value;
  71192. };
  71193. WebVRController.prototype._checkChanges = function (newState, currentState) {
  71194. this._changes.pressChanged = newState.pressed !== currentState.pressed;
  71195. this._changes.touchChanged = newState.touched !== currentState.touched;
  71196. this._changes.valueChanged = newState.value !== currentState.value;
  71197. this._changes.changed = this._changes.pressChanged || this._changes.touchChanged || this._changes.valueChanged;
  71198. return this._changes;
  71199. };
  71200. /**
  71201. * Disposes of th webVRCOntroller
  71202. */
  71203. WebVRController.prototype.dispose = function () {
  71204. _super.prototype.dispose.call(this);
  71205. this.onTriggerStateChangedObservable.clear();
  71206. this.onMainButtonStateChangedObservable.clear();
  71207. this.onSecondaryButtonStateChangedObservable.clear();
  71208. this.onPadStateChangedObservable.clear();
  71209. this.onPadValuesChangedObservable.clear();
  71210. };
  71211. return WebVRController;
  71212. }(BABYLON.PoseEnabledController));
  71213. BABYLON.WebVRController = WebVRController;
  71214. })(BABYLON || (BABYLON = {}));
  71215. //# sourceMappingURL=babylon.webVRController.js.map
  71216. var BABYLON;
  71217. (function (BABYLON) {
  71218. /**
  71219. * Oculus Touch Controller
  71220. */
  71221. var OculusTouchController = /** @class */ (function (_super) {
  71222. __extends(OculusTouchController, _super);
  71223. /**
  71224. * Creates a new OculusTouchController from a gamepad
  71225. * @param vrGamepad the gamepad that the controller should be created from
  71226. */
  71227. function OculusTouchController(vrGamepad) {
  71228. var _this = _super.call(this, vrGamepad) || this;
  71229. /**
  71230. * Fired when the secondary trigger on this controller is modified
  71231. */
  71232. _this.onSecondaryTriggerStateChangedObservable = new BABYLON.Observable();
  71233. /**
  71234. * Fired when the thumb rest on this controller is modified
  71235. */
  71236. _this.onThumbRestChangedObservable = new BABYLON.Observable();
  71237. _this.controllerType = BABYLON.PoseEnabledControllerType.OCULUS;
  71238. return _this;
  71239. }
  71240. /**
  71241. * Implements abstract method on WebVRController class, loading controller meshes and calling this.attachToMesh if successful.
  71242. * @param scene scene in which to add meshes
  71243. * @param meshLoaded optional callback function that will be called if the mesh loads successfully.
  71244. */
  71245. OculusTouchController.prototype.initControllerMesh = function (scene, meshLoaded) {
  71246. var _this = this;
  71247. var meshName;
  71248. // Hand
  71249. if (this.hand === 'left') {
  71250. meshName = OculusTouchController.MODEL_LEFT_FILENAME;
  71251. }
  71252. else { // Right is the default if no hand is specified
  71253. meshName = OculusTouchController.MODEL_RIGHT_FILENAME;
  71254. }
  71255. BABYLON.SceneLoader.ImportMesh("", OculusTouchController.MODEL_BASE_URL, meshName, scene, function (newMeshes) {
  71256. /*
  71257. Parent Mesh name: oculus_touch_left
  71258. - body
  71259. - trigger
  71260. - thumbstick
  71261. - grip
  71262. - button_y
  71263. - button_x
  71264. - button_enter
  71265. */
  71266. _this._defaultModel = newMeshes[1];
  71267. _this.attachToMesh(_this._defaultModel);
  71268. if (meshLoaded) {
  71269. meshLoaded(_this._defaultModel);
  71270. }
  71271. });
  71272. };
  71273. Object.defineProperty(OculusTouchController.prototype, "onAButtonStateChangedObservable", {
  71274. /**
  71275. * Fired when the A button on this controller is modified
  71276. */
  71277. get: function () {
  71278. if (this.hand === 'right') {
  71279. return this.onMainButtonStateChangedObservable;
  71280. }
  71281. else {
  71282. throw new Error('No A button on left hand');
  71283. }
  71284. },
  71285. enumerable: true,
  71286. configurable: true
  71287. });
  71288. Object.defineProperty(OculusTouchController.prototype, "onBButtonStateChangedObservable", {
  71289. /**
  71290. * Fired when the B button on this controller is modified
  71291. */
  71292. get: function () {
  71293. if (this.hand === 'right') {
  71294. return this.onSecondaryButtonStateChangedObservable;
  71295. }
  71296. else {
  71297. throw new Error('No B button on left hand');
  71298. }
  71299. },
  71300. enumerable: true,
  71301. configurable: true
  71302. });
  71303. Object.defineProperty(OculusTouchController.prototype, "onXButtonStateChangedObservable", {
  71304. /**
  71305. * Fired when the X button on this controller is modified
  71306. */
  71307. get: function () {
  71308. if (this.hand === 'left') {
  71309. return this.onMainButtonStateChangedObservable;
  71310. }
  71311. else {
  71312. throw new Error('No X button on right hand');
  71313. }
  71314. },
  71315. enumerable: true,
  71316. configurable: true
  71317. });
  71318. Object.defineProperty(OculusTouchController.prototype, "onYButtonStateChangedObservable", {
  71319. /**
  71320. * Fired when the Y button on this controller is modified
  71321. */
  71322. get: function () {
  71323. if (this.hand === 'left') {
  71324. return this.onSecondaryButtonStateChangedObservable;
  71325. }
  71326. else {
  71327. throw new Error('No Y button on right hand');
  71328. }
  71329. },
  71330. enumerable: true,
  71331. configurable: true
  71332. });
  71333. /**
  71334. * Called once for each button that changed state since the last frame
  71335. * 0) thumb stick (touch, press, value = pressed (0,1)). value is in this.leftStick
  71336. * 1) index trigger (touch (?), press (only when value > 0.1), value 0 to 1)
  71337. * 2) secondary trigger (same)
  71338. * 3) A (right) X (left), touch, pressed = value
  71339. * 4) B / Y
  71340. * 5) thumb rest
  71341. * @param buttonIdx Which button index changed
  71342. * @param state New state of the button
  71343. * @param changes Which properties on the state changed since last frame
  71344. */
  71345. OculusTouchController.prototype._handleButtonChange = function (buttonIdx, state, changes) {
  71346. var notifyObject = state; //{ state: state, changes: changes };
  71347. var triggerDirection = this.hand === 'right' ? -1 : 1;
  71348. switch (buttonIdx) {
  71349. case 0:
  71350. this.onPadStateChangedObservable.notifyObservers(notifyObject);
  71351. return;
  71352. case 1: // index trigger
  71353. if (this._defaultModel) {
  71354. (this._defaultModel.getChildren()[3]).rotation.x = -notifyObject.value * 0.20;
  71355. (this._defaultModel.getChildren()[3]).position.y = -notifyObject.value * 0.005;
  71356. (this._defaultModel.getChildren()[3]).position.z = -notifyObject.value * 0.005;
  71357. }
  71358. this.onTriggerStateChangedObservable.notifyObservers(notifyObject);
  71359. return;
  71360. case 2: // secondary trigger
  71361. if (this._defaultModel) {
  71362. (this._defaultModel.getChildren()[4]).position.x = triggerDirection * notifyObject.value * 0.0035;
  71363. }
  71364. this.onSecondaryTriggerStateChangedObservable.notifyObservers(notifyObject);
  71365. return;
  71366. case 3:
  71367. if (this._defaultModel) {
  71368. if (notifyObject.pressed) {
  71369. (this._defaultModel.getChildren()[1]).position.y = -0.001;
  71370. }
  71371. else {
  71372. (this._defaultModel.getChildren()[1]).position.y = 0;
  71373. }
  71374. }
  71375. this.onMainButtonStateChangedObservable.notifyObservers(notifyObject);
  71376. return;
  71377. case 4:
  71378. if (this._defaultModel) {
  71379. if (notifyObject.pressed) {
  71380. (this._defaultModel.getChildren()[2]).position.y = -0.001;
  71381. }
  71382. else {
  71383. (this._defaultModel.getChildren()[2]).position.y = 0;
  71384. }
  71385. }
  71386. this.onSecondaryButtonStateChangedObservable.notifyObservers(notifyObject);
  71387. return;
  71388. case 5:
  71389. this.onThumbRestChangedObservable.notifyObservers(notifyObject);
  71390. return;
  71391. }
  71392. };
  71393. /**
  71394. * Base Url for the controller model.
  71395. */
  71396. OculusTouchController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/oculus/';
  71397. /**
  71398. * File name for the left controller model.
  71399. */
  71400. OculusTouchController.MODEL_LEFT_FILENAME = 'left.babylon';
  71401. /**
  71402. * File name for the right controller model.
  71403. */
  71404. OculusTouchController.MODEL_RIGHT_FILENAME = 'right.babylon';
  71405. return OculusTouchController;
  71406. }(BABYLON.WebVRController));
  71407. BABYLON.OculusTouchController = OculusTouchController;
  71408. })(BABYLON || (BABYLON = {}));
  71409. //# sourceMappingURL=babylon.oculusTouchController.js.map
  71410. var BABYLON;
  71411. (function (BABYLON) {
  71412. /**
  71413. * Vive Controller
  71414. */
  71415. var ViveController = /** @class */ (function (_super) {
  71416. __extends(ViveController, _super);
  71417. /**
  71418. * Creates a new ViveController from a gamepad
  71419. * @param vrGamepad the gamepad that the controller should be created from
  71420. */
  71421. function ViveController(vrGamepad) {
  71422. var _this = _super.call(this, vrGamepad) || this;
  71423. _this.controllerType = BABYLON.PoseEnabledControllerType.VIVE;
  71424. _this._invertLeftStickY = true;
  71425. return _this;
  71426. }
  71427. /**
  71428. * Implements abstract method on WebVRController class, loading controller meshes and calling this.attachToMesh if successful.
  71429. * @param scene scene in which to add meshes
  71430. * @param meshLoaded optional callback function that will be called if the mesh loads successfully.
  71431. */
  71432. ViveController.prototype.initControllerMesh = function (scene, meshLoaded) {
  71433. var _this = this;
  71434. BABYLON.SceneLoader.ImportMesh("", ViveController.MODEL_BASE_URL, ViveController.MODEL_FILENAME, scene, function (newMeshes) {
  71435. /*
  71436. Parent Mesh name: ViveWand
  71437. - body
  71438. - r_gripper
  71439. - l_gripper
  71440. - menu_button
  71441. - system_button
  71442. - trackpad
  71443. - trigger
  71444. - LED
  71445. */
  71446. _this._defaultModel = newMeshes[1];
  71447. _this.attachToMesh(_this._defaultModel);
  71448. if (meshLoaded) {
  71449. meshLoaded(_this._defaultModel);
  71450. }
  71451. });
  71452. };
  71453. Object.defineProperty(ViveController.prototype, "onLeftButtonStateChangedObservable", {
  71454. /**
  71455. * Fired when the left button on this controller is modified
  71456. */
  71457. get: function () {
  71458. return this.onMainButtonStateChangedObservable;
  71459. },
  71460. enumerable: true,
  71461. configurable: true
  71462. });
  71463. Object.defineProperty(ViveController.prototype, "onRightButtonStateChangedObservable", {
  71464. /**
  71465. * Fired when the right button on this controller is modified
  71466. */
  71467. get: function () {
  71468. return this.onMainButtonStateChangedObservable;
  71469. },
  71470. enumerable: true,
  71471. configurable: true
  71472. });
  71473. Object.defineProperty(ViveController.prototype, "onMenuButtonStateChangedObservable", {
  71474. /**
  71475. * Fired when the menu button on this controller is modified
  71476. */
  71477. get: function () {
  71478. return this.onSecondaryButtonStateChangedObservable;
  71479. },
  71480. enumerable: true,
  71481. configurable: true
  71482. });
  71483. /**
  71484. * Called once for each button that changed state since the last frame
  71485. * Vive mapping:
  71486. * 0: touchpad
  71487. * 1: trigger
  71488. * 2: left AND right buttons
  71489. * 3: menu button
  71490. * @param buttonIdx Which button index changed
  71491. * @param state New state of the button
  71492. * @param changes Which properties on the state changed since last frame
  71493. */
  71494. ViveController.prototype._handleButtonChange = function (buttonIdx, state, changes) {
  71495. var notifyObject = state; //{ state: state, changes: changes };
  71496. switch (buttonIdx) {
  71497. case 0:
  71498. this.onPadStateChangedObservable.notifyObservers(notifyObject);
  71499. return;
  71500. case 1: // index trigger
  71501. if (this._defaultModel) {
  71502. (this._defaultModel.getChildren()[6]).rotation.x = -notifyObject.value * 0.15;
  71503. }
  71504. this.onTriggerStateChangedObservable.notifyObservers(notifyObject);
  71505. return;
  71506. case 2: // left AND right button
  71507. this.onMainButtonStateChangedObservable.notifyObservers(notifyObject);
  71508. return;
  71509. case 3:
  71510. if (this._defaultModel) {
  71511. if (notifyObject.pressed) {
  71512. (this._defaultModel.getChildren()[2]).position.y = -0.001;
  71513. }
  71514. else {
  71515. (this._defaultModel.getChildren()[2]).position.y = 0;
  71516. }
  71517. }
  71518. this.onSecondaryButtonStateChangedObservable.notifyObservers(notifyObject);
  71519. return;
  71520. }
  71521. };
  71522. /**
  71523. * Base Url for the controller model.
  71524. */
  71525. ViveController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/vive/';
  71526. /**
  71527. * File name for the controller model.
  71528. */
  71529. ViveController.MODEL_FILENAME = 'wand.babylon';
  71530. return ViveController;
  71531. }(BABYLON.WebVRController));
  71532. BABYLON.ViveController = ViveController;
  71533. })(BABYLON || (BABYLON = {}));
  71534. //# sourceMappingURL=babylon.viveController.js.map
  71535. var BABYLON;
  71536. (function (BABYLON) {
  71537. /**
  71538. * Generic Controller
  71539. */
  71540. var GenericController = /** @class */ (function (_super) {
  71541. __extends(GenericController, _super);
  71542. /**
  71543. * Creates a new GenericController from a gamepad
  71544. * @param vrGamepad the gamepad that the controller should be created from
  71545. */
  71546. function GenericController(vrGamepad) {
  71547. return _super.call(this, vrGamepad) || this;
  71548. }
  71549. /**
  71550. * Implements abstract method on WebVRController class, loading controller meshes and calling this.attachToMesh if successful.
  71551. * @param scene scene in which to add meshes
  71552. * @param meshLoaded optional callback function that will be called if the mesh loads successfully.
  71553. */
  71554. GenericController.prototype.initControllerMesh = function (scene, meshLoaded) {
  71555. var _this = this;
  71556. BABYLON.SceneLoader.ImportMesh("", GenericController.MODEL_BASE_URL, GenericController.MODEL_FILENAME, scene, function (newMeshes) {
  71557. _this._defaultModel = newMeshes[1];
  71558. _this.attachToMesh(_this._defaultModel);
  71559. if (meshLoaded) {
  71560. meshLoaded(_this._defaultModel);
  71561. }
  71562. });
  71563. };
  71564. /**
  71565. * Called once for each button that changed state since the last frame
  71566. * @param buttonIdx Which button index changed
  71567. * @param state New state of the button
  71568. * @param changes Which properties on the state changed since last frame
  71569. */
  71570. GenericController.prototype._handleButtonChange = function (buttonIdx, state, changes) {
  71571. console.log("Button id: " + buttonIdx + "state: ");
  71572. console.dir(state);
  71573. };
  71574. /**
  71575. * Base Url for the controller model.
  71576. */
  71577. GenericController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/generic/';
  71578. /**
  71579. * File name for the controller model.
  71580. */
  71581. GenericController.MODEL_FILENAME = 'generic.babylon';
  71582. return GenericController;
  71583. }(BABYLON.WebVRController));
  71584. BABYLON.GenericController = GenericController;
  71585. })(BABYLON || (BABYLON = {}));
  71586. //# sourceMappingURL=babylon.genericController.js.map
  71587. var BABYLON;
  71588. (function (BABYLON) {
  71589. /**
  71590. * Defines the LoadedMeshInfo object that describes information about the loaded webVR controller mesh
  71591. */
  71592. var LoadedMeshInfo = /** @class */ (function () {
  71593. function LoadedMeshInfo() {
  71594. /**
  71595. * Map of the button meshes contained in the controller
  71596. */
  71597. this.buttonMeshes = {};
  71598. /**
  71599. * Map of the axis meshes contained in the controller
  71600. */
  71601. this.axisMeshes = {};
  71602. }
  71603. return LoadedMeshInfo;
  71604. }());
  71605. /**
  71606. * Defines the WindowsMotionController object that the state of the windows motion controller
  71607. */
  71608. var WindowsMotionController = /** @class */ (function (_super) {
  71609. __extends(WindowsMotionController, _super);
  71610. /**
  71611. * Creates a new WindowsMotionController from a gamepad
  71612. * @param vrGamepad the gamepad that the controller should be created from
  71613. */
  71614. function WindowsMotionController(vrGamepad) {
  71615. var _this = _super.call(this, vrGamepad) || this;
  71616. _this._mapping = {
  71617. // Semantic button names
  71618. buttons: ['thumbstick', 'trigger', 'grip', 'menu', 'trackpad'],
  71619. // A mapping of the button name to glTF model node name
  71620. // that should be transformed by button value.
  71621. buttonMeshNames: {
  71622. 'trigger': 'SELECT',
  71623. 'menu': 'MENU',
  71624. 'grip': 'GRASP',
  71625. 'thumbstick': 'THUMBSTICK_PRESS',
  71626. 'trackpad': 'TOUCHPAD_PRESS'
  71627. },
  71628. // This mapping is used to translate from the Motion Controller to Babylon semantics
  71629. buttonObservableNames: {
  71630. 'trigger': 'onTriggerStateChangedObservable',
  71631. 'menu': 'onSecondaryButtonStateChangedObservable',
  71632. 'grip': 'onMainButtonStateChangedObservable',
  71633. 'thumbstick': 'onPadStateChangedObservable',
  71634. 'trackpad': 'onTrackpadChangedObservable'
  71635. },
  71636. // A mapping of the axis name to glTF model node name
  71637. // that should be transformed by axis value.
  71638. // This array mirrors the browserGamepad.axes array, such that
  71639. // the mesh corresponding to axis 0 is in this array index 0.
  71640. axisMeshNames: [
  71641. 'THUMBSTICK_X',
  71642. 'THUMBSTICK_Y',
  71643. 'TOUCHPAD_TOUCH_X',
  71644. 'TOUCHPAD_TOUCH_Y'
  71645. ],
  71646. pointingPoseMeshName: BABYLON.PoseEnabledController.POINTING_POSE
  71647. };
  71648. /**
  71649. * Fired when the trackpad on this controller is clicked
  71650. */
  71651. _this.onTrackpadChangedObservable = new BABYLON.Observable();
  71652. /**
  71653. * Fired when the trackpad on this controller is modified
  71654. */
  71655. _this.onTrackpadValuesChangedObservable = new BABYLON.Observable();
  71656. /**
  71657. * The current x and y values of this controller's trackpad
  71658. */
  71659. _this.trackpad = { x: 0, y: 0 };
  71660. _this.controllerType = BABYLON.PoseEnabledControllerType.WINDOWS;
  71661. _this._loadedMeshInfo = null;
  71662. return _this;
  71663. }
  71664. Object.defineProperty(WindowsMotionController.prototype, "onTriggerButtonStateChangedObservable", {
  71665. /**
  71666. * Fired when the trigger on this controller is modified
  71667. */
  71668. get: function () {
  71669. return this.onTriggerStateChangedObservable;
  71670. },
  71671. enumerable: true,
  71672. configurable: true
  71673. });
  71674. Object.defineProperty(WindowsMotionController.prototype, "onMenuButtonStateChangedObservable", {
  71675. /**
  71676. * Fired when the menu button on this controller is modified
  71677. */
  71678. get: function () {
  71679. return this.onSecondaryButtonStateChangedObservable;
  71680. },
  71681. enumerable: true,
  71682. configurable: true
  71683. });
  71684. Object.defineProperty(WindowsMotionController.prototype, "onGripButtonStateChangedObservable", {
  71685. /**
  71686. * Fired when the grip button on this controller is modified
  71687. */
  71688. get: function () {
  71689. return this.onMainButtonStateChangedObservable;
  71690. },
  71691. enumerable: true,
  71692. configurable: true
  71693. });
  71694. Object.defineProperty(WindowsMotionController.prototype, "onThumbstickButtonStateChangedObservable", {
  71695. /**
  71696. * Fired when the thumbstick button on this controller is modified
  71697. */
  71698. get: function () {
  71699. return this.onPadStateChangedObservable;
  71700. },
  71701. enumerable: true,
  71702. configurable: true
  71703. });
  71704. Object.defineProperty(WindowsMotionController.prototype, "onTouchpadButtonStateChangedObservable", {
  71705. /**
  71706. * Fired when the touchpad button on this controller is modified
  71707. */
  71708. get: function () {
  71709. return this.onTrackpadChangedObservable;
  71710. },
  71711. enumerable: true,
  71712. configurable: true
  71713. });
  71714. Object.defineProperty(WindowsMotionController.prototype, "onTouchpadValuesChangedObservable", {
  71715. /**
  71716. * Fired when the touchpad values on this controller are modified
  71717. */
  71718. get: function () {
  71719. return this.onTrackpadValuesChangedObservable;
  71720. },
  71721. enumerable: true,
  71722. configurable: true
  71723. });
  71724. /**
  71725. * Called once per frame by the engine.
  71726. */
  71727. WindowsMotionController.prototype.update = function () {
  71728. _super.prototype.update.call(this);
  71729. if (this.browserGamepad.axes) {
  71730. if (this.browserGamepad.axes[2] != this.trackpad.x || this.browserGamepad.axes[3] != this.trackpad.y) {
  71731. this.trackpad.x = this.browserGamepad["axes"][2];
  71732. this.trackpad.y = this.browserGamepad["axes"][3];
  71733. this.onTrackpadValuesChangedObservable.notifyObservers(this.trackpad);
  71734. }
  71735. // Only need to animate axes if there is a loaded mesh
  71736. if (this._loadedMeshInfo) {
  71737. for (var axis = 0; axis < this._mapping.axisMeshNames.length; axis++) {
  71738. this._lerpAxisTransform(axis, this.browserGamepad.axes[axis]);
  71739. }
  71740. }
  71741. }
  71742. };
  71743. /**
  71744. * Called once for each button that changed state since the last frame
  71745. * @param buttonIdx Which button index changed
  71746. * @param state New state of the button
  71747. * @param changes Which properties on the state changed since last frame
  71748. */
  71749. WindowsMotionController.prototype._handleButtonChange = function (buttonIdx, state, changes) {
  71750. var buttonName = this._mapping.buttons[buttonIdx];
  71751. if (!buttonName) {
  71752. return;
  71753. }
  71754. // Only emit events for buttons that we know how to map from index to name
  71755. var observable = this[(this._mapping.buttonObservableNames)[buttonName]];
  71756. if (observable) {
  71757. observable.notifyObservers(state);
  71758. }
  71759. this._lerpButtonTransform(buttonName, state.value);
  71760. };
  71761. /**
  71762. * Moves the buttons on the controller mesh based on their current state
  71763. * @param buttonName the name of the button to move
  71764. * @param buttonValue the value of the button which determines the buttons new position
  71765. */
  71766. WindowsMotionController.prototype._lerpButtonTransform = function (buttonName, buttonValue) {
  71767. // If there is no loaded mesh, there is nothing to transform.
  71768. if (!this._loadedMeshInfo) {
  71769. return;
  71770. }
  71771. var meshInfo = this._loadedMeshInfo.buttonMeshes[buttonName];
  71772. if (!meshInfo.unpressed.rotationQuaternion || !meshInfo.pressed.rotationQuaternion || !meshInfo.value.rotationQuaternion) {
  71773. return;
  71774. }
  71775. BABYLON.Quaternion.SlerpToRef(meshInfo.unpressed.rotationQuaternion, meshInfo.pressed.rotationQuaternion, buttonValue, meshInfo.value.rotationQuaternion);
  71776. BABYLON.Vector3.LerpToRef(meshInfo.unpressed.position, meshInfo.pressed.position, buttonValue, meshInfo.value.position);
  71777. };
  71778. /**
  71779. * Moves the axis on the controller mesh based on its current state
  71780. * @param axis the index of the axis
  71781. * @param axisValue the value of the axis which determines the meshes new position
  71782. * @hidden
  71783. */
  71784. WindowsMotionController.prototype._lerpAxisTransform = function (axis, axisValue) {
  71785. if (!this._loadedMeshInfo) {
  71786. return;
  71787. }
  71788. var meshInfo = this._loadedMeshInfo.axisMeshes[axis];
  71789. if (!meshInfo) {
  71790. return;
  71791. }
  71792. if (!meshInfo.min.rotationQuaternion || !meshInfo.max.rotationQuaternion || !meshInfo.value.rotationQuaternion) {
  71793. return;
  71794. }
  71795. // Convert from gamepad value range (-1 to +1) to lerp range (0 to 1)
  71796. var lerpValue = axisValue * 0.5 + 0.5;
  71797. BABYLON.Quaternion.SlerpToRef(meshInfo.min.rotationQuaternion, meshInfo.max.rotationQuaternion, lerpValue, meshInfo.value.rotationQuaternion);
  71798. BABYLON.Vector3.LerpToRef(meshInfo.min.position, meshInfo.max.position, lerpValue, meshInfo.value.position);
  71799. };
  71800. /**
  71801. * Implements abstract method on WebVRController class, loading controller meshes and calling this.attachToMesh if successful.
  71802. * @param scene scene in which to add meshes
  71803. * @param meshLoaded optional callback function that will be called if the mesh loads successfully.
  71804. */
  71805. WindowsMotionController.prototype.initControllerMesh = function (scene, meshLoaded, forceDefault) {
  71806. var _this = this;
  71807. if (forceDefault === void 0) { forceDefault = false; }
  71808. var path;
  71809. var filename;
  71810. // Checking if GLB loader is present
  71811. if (BABYLON.SceneLoader.IsPluginForExtensionAvailable(".glb")) {
  71812. // Determine the device specific folder based on the ID suffix
  71813. var device = 'default';
  71814. if (this.id && !forceDefault) {
  71815. var match = this.id.match(WindowsMotionController.GAMEPAD_ID_PATTERN);
  71816. device = ((match && match[0]) || device);
  71817. }
  71818. // Hand
  71819. if (this.hand === 'left') {
  71820. filename = WindowsMotionController.MODEL_LEFT_FILENAME;
  71821. }
  71822. else { // Right is the default if no hand is specified
  71823. filename = WindowsMotionController.MODEL_RIGHT_FILENAME;
  71824. }
  71825. path = WindowsMotionController.MODEL_BASE_URL + device + '/';
  71826. }
  71827. else {
  71828. BABYLON.Tools.Warn("You need to reference GLTF loader to load Windows Motion Controllers model. Falling back to generic models");
  71829. path = BABYLON.GenericController.MODEL_BASE_URL;
  71830. filename = BABYLON.GenericController.MODEL_FILENAME;
  71831. }
  71832. BABYLON.SceneLoader.ImportMesh("", path, filename, scene, function (meshes) {
  71833. // glTF files successfully loaded from the remote server, now process them to ensure they are in the right format.
  71834. _this._loadedMeshInfo = _this.processModel(scene, meshes);
  71835. if (!_this._loadedMeshInfo) {
  71836. return;
  71837. }
  71838. _this._defaultModel = _this._loadedMeshInfo.rootNode;
  71839. _this.attachToMesh(_this._defaultModel);
  71840. if (meshLoaded) {
  71841. meshLoaded(_this._defaultModel);
  71842. }
  71843. }, null, function (scene, message) {
  71844. BABYLON.Tools.Log(message);
  71845. BABYLON.Tools.Warn('Failed to retrieve controller model from the remote server: ' + path + filename);
  71846. if (!forceDefault) {
  71847. _this.initControllerMesh(scene, meshLoaded, true);
  71848. }
  71849. });
  71850. };
  71851. /**
  71852. * Takes a list of meshes (as loaded from the glTF file) and finds the root node, as well as nodes that
  71853. * can be transformed by button presses and axes values, based on this._mapping.
  71854. *
  71855. * @param scene scene in which the meshes exist
  71856. * @param meshes list of meshes that make up the controller model to process
  71857. * @return structured view of the given meshes, with mapping of buttons and axes to meshes that can be transformed.
  71858. */
  71859. WindowsMotionController.prototype.processModel = function (scene, meshes) {
  71860. var loadedMeshInfo = null;
  71861. // Create a new mesh to contain the glTF hierarchy
  71862. var parentMesh = new BABYLON.Mesh(this.id + " " + this.hand, scene);
  71863. // Find the root node in the loaded glTF scene, and attach it as a child of 'parentMesh'
  71864. var childMesh = null;
  71865. for (var i = 0; i < meshes.length; i++) {
  71866. var mesh = meshes[i];
  71867. if (!mesh.parent) {
  71868. // Exclude controller meshes from picking results
  71869. mesh.isPickable = false;
  71870. // Handle root node, attach to the new parentMesh
  71871. childMesh = mesh;
  71872. break;
  71873. }
  71874. }
  71875. if (childMesh) {
  71876. childMesh.setParent(parentMesh);
  71877. // Create our mesh info. Note that this method will always return non-null.
  71878. loadedMeshInfo = this.createMeshInfo(parentMesh);
  71879. }
  71880. else {
  71881. BABYLON.Tools.Warn('Could not find root node in model file.');
  71882. }
  71883. return loadedMeshInfo;
  71884. };
  71885. WindowsMotionController.prototype.createMeshInfo = function (rootNode) {
  71886. var loadedMeshInfo = new LoadedMeshInfo();
  71887. var i;
  71888. loadedMeshInfo.rootNode = rootNode;
  71889. // Reset the caches
  71890. loadedMeshInfo.buttonMeshes = {};
  71891. loadedMeshInfo.axisMeshes = {};
  71892. // Button Meshes
  71893. for (i = 0; i < this._mapping.buttons.length; i++) {
  71894. var buttonMeshName = this._mapping.buttonMeshNames[this._mapping.buttons[i]];
  71895. if (!buttonMeshName) {
  71896. BABYLON.Tools.Log('Skipping unknown button at index: ' + i + ' with mapped name: ' + this._mapping.buttons[i]);
  71897. continue;
  71898. }
  71899. var buttonMesh = getChildByName(rootNode, buttonMeshName);
  71900. if (!buttonMesh) {
  71901. BABYLON.Tools.Warn('Missing button mesh with name: ' + buttonMeshName);
  71902. continue;
  71903. }
  71904. var buttonMeshInfo = {
  71905. index: i,
  71906. value: getImmediateChildByName(buttonMesh, 'VALUE'),
  71907. pressed: getImmediateChildByName(buttonMesh, 'PRESSED'),
  71908. unpressed: getImmediateChildByName(buttonMesh, 'UNPRESSED')
  71909. };
  71910. if (buttonMeshInfo.value && buttonMeshInfo.pressed && buttonMeshInfo.unpressed) {
  71911. loadedMeshInfo.buttonMeshes[this._mapping.buttons[i]] = buttonMeshInfo;
  71912. }
  71913. else {
  71914. // If we didn't find the mesh, it simply means this button won't have transforms applied as mapped button value changes.
  71915. BABYLON.Tools.Warn('Missing button submesh under mesh with name: ' + buttonMeshName +
  71916. '(VALUE: ' + !!buttonMeshInfo.value +
  71917. ', PRESSED: ' + !!buttonMeshInfo.pressed +
  71918. ', UNPRESSED:' + !!buttonMeshInfo.unpressed +
  71919. ')');
  71920. }
  71921. }
  71922. // Axis Meshes
  71923. for (i = 0; i < this._mapping.axisMeshNames.length; i++) {
  71924. var axisMeshName = this._mapping.axisMeshNames[i];
  71925. if (!axisMeshName) {
  71926. BABYLON.Tools.Log('Skipping unknown axis at index: ' + i);
  71927. continue;
  71928. }
  71929. var axisMesh = getChildByName(rootNode, axisMeshName);
  71930. if (!axisMesh) {
  71931. BABYLON.Tools.Warn('Missing axis mesh with name: ' + axisMeshName);
  71932. continue;
  71933. }
  71934. var axisMeshInfo = {
  71935. index: i,
  71936. value: getImmediateChildByName(axisMesh, 'VALUE'),
  71937. min: getImmediateChildByName(axisMesh, 'MIN'),
  71938. max: getImmediateChildByName(axisMesh, 'MAX')
  71939. };
  71940. if (axisMeshInfo.value && axisMeshInfo.min && axisMeshInfo.max) {
  71941. loadedMeshInfo.axisMeshes[i] = axisMeshInfo;
  71942. }
  71943. else {
  71944. // If we didn't find the mesh, it simply means thit axis won't have transforms applied as mapped axis values change.
  71945. BABYLON.Tools.Warn('Missing axis submesh under mesh with name: ' + axisMeshName +
  71946. '(VALUE: ' + !!axisMeshInfo.value +
  71947. ', MIN: ' + !!axisMeshInfo.min +
  71948. ', MAX:' + !!axisMeshInfo.max +
  71949. ')');
  71950. }
  71951. }
  71952. // Pointing Ray
  71953. loadedMeshInfo.pointingPoseNode = getChildByName(rootNode, this._mapping.pointingPoseMeshName);
  71954. if (!loadedMeshInfo.pointingPoseNode) {
  71955. BABYLON.Tools.Warn('Missing pointing pose mesh with name: ' + this._mapping.pointingPoseMeshName);
  71956. }
  71957. return loadedMeshInfo;
  71958. // Look through all children recursively. This will return null if no mesh exists with the given name.
  71959. function getChildByName(node, name) {
  71960. return node.getChildMeshes(false, function (n) { return n.name === name; })[0];
  71961. }
  71962. // Look through only immediate children. This will return null if no mesh exists with the given name.
  71963. function getImmediateChildByName(node, name) {
  71964. return node.getChildMeshes(true, function (n) { return n.name == name; })[0];
  71965. }
  71966. };
  71967. /**
  71968. * Gets the ray of the controller in the direction the controller is pointing
  71969. * @param length the length the resulting ray should be
  71970. * @returns a ray in the direction the controller is pointing
  71971. */
  71972. WindowsMotionController.prototype.getForwardRay = function (length) {
  71973. if (length === void 0) { length = 100; }
  71974. if (!(this._loadedMeshInfo && this._loadedMeshInfo.pointingPoseNode)) {
  71975. return _super.prototype.getForwardRay.call(this, length);
  71976. }
  71977. var m = this._loadedMeshInfo.pointingPoseNode.getWorldMatrix();
  71978. var origin = m.getTranslation();
  71979. var forward = new BABYLON.Vector3(0, 0, -1);
  71980. var forwardWorld = BABYLON.Vector3.TransformNormal(forward, m);
  71981. var direction = BABYLON.Vector3.Normalize(forwardWorld);
  71982. return new BABYLON.Ray(origin, direction, length);
  71983. };
  71984. /**
  71985. * Disposes of the controller
  71986. */
  71987. WindowsMotionController.prototype.dispose = function () {
  71988. _super.prototype.dispose.call(this);
  71989. this.onTrackpadChangedObservable.clear();
  71990. };
  71991. /**
  71992. * The base url used to load the left and right controller models
  71993. */
  71994. WindowsMotionController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/microsoft/';
  71995. /**
  71996. * The name of the left controller model file
  71997. */
  71998. WindowsMotionController.MODEL_LEFT_FILENAME = 'left.glb';
  71999. /**
  72000. * The name of the right controller model file
  72001. */
  72002. WindowsMotionController.MODEL_RIGHT_FILENAME = 'right.glb';
  72003. /**
  72004. * The controller name prefix for this controller type
  72005. */
  72006. WindowsMotionController.GAMEPAD_ID_PREFIX = 'Spatial Controller (Spatial Interaction Source) ';
  72007. /**
  72008. * The controller id pattern for this controller type
  72009. */
  72010. WindowsMotionController.GAMEPAD_ID_PATTERN = /([0-9a-zA-Z]+-[0-9a-zA-Z]+)$/;
  72011. return WindowsMotionController;
  72012. }(BABYLON.WebVRController));
  72013. BABYLON.WindowsMotionController = WindowsMotionController;
  72014. })(BABYLON || (BABYLON = {}));
  72015. //# sourceMappingURL=babylon.windowsMotionController.js.map
  72016. var BABYLON;
  72017. (function (BABYLON) {
  72018. /**
  72019. * Gear VR Controller
  72020. */
  72021. var GearVRController = /** @class */ (function (_super) {
  72022. __extends(GearVRController, _super);
  72023. /**
  72024. * Creates a new GearVRController from a gamepad
  72025. * @param vrGamepad the gamepad that the controller should be created from
  72026. */
  72027. function GearVRController(vrGamepad) {
  72028. var _this = _super.call(this, vrGamepad) || this;
  72029. _this._buttonIndexToObservableNameMap = [
  72030. 'onTrackpadChangedObservable',
  72031. 'onTriggerStateChangedObservable' // Trigger
  72032. ];
  72033. _this.controllerType = BABYLON.PoseEnabledControllerType.GEAR_VR;
  72034. return _this;
  72035. }
  72036. /**
  72037. * Implements abstract method on WebVRController class, loading controller meshes and calling this.attachToMesh if successful.
  72038. * @param scene scene in which to add meshes
  72039. * @param meshLoaded optional callback function that will be called if the mesh loads successfully.
  72040. */
  72041. GearVRController.prototype.initControllerMesh = function (scene, meshLoaded) {
  72042. var _this = this;
  72043. BABYLON.SceneLoader.ImportMesh("", GearVRController.MODEL_BASE_URL, GearVRController.MODEL_FILENAME, scene, function (newMeshes) {
  72044. _this._defaultModel = newMeshes[1];
  72045. _this.attachToMesh(_this._defaultModel);
  72046. if (meshLoaded) {
  72047. meshLoaded(_this._defaultModel);
  72048. }
  72049. });
  72050. };
  72051. /**
  72052. * Called once for each button that changed state since the last frame
  72053. * @param buttonIdx Which button index changed
  72054. * @param state New state of the button
  72055. * @param changes Which properties on the state changed since last frame
  72056. */
  72057. GearVRController.prototype._handleButtonChange = function (buttonIdx, state, changes) {
  72058. if (buttonIdx < this._buttonIndexToObservableNameMap.length) {
  72059. var observableName = this._buttonIndexToObservableNameMap[buttonIdx];
  72060. // Only emit events for buttons that we know how to map from index to observable
  72061. var observable = this[observableName];
  72062. if (observable) {
  72063. observable.notifyObservers(state);
  72064. }
  72065. }
  72066. };
  72067. /**
  72068. * Base Url for the controller model.
  72069. */
  72070. GearVRController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/generic/';
  72071. /**
  72072. * File name for the controller model.
  72073. */
  72074. GearVRController.MODEL_FILENAME = 'generic.babylon';
  72075. /**
  72076. * Gamepad Id prefix used to identify this controller.
  72077. */
  72078. GearVRController.GAMEPAD_ID_PREFIX = 'Gear VR'; // id is 'Gear VR Controller'
  72079. return GearVRController;
  72080. }(BABYLON.WebVRController));
  72081. BABYLON.GearVRController = GearVRController;
  72082. })(BABYLON || (BABYLON = {}));
  72083. //# sourceMappingURL=babylon.gearVRController.js.map
  72084. var BABYLON;
  72085. (function (BABYLON) {
  72086. /**
  72087. * Google Daydream controller
  72088. */
  72089. var DaydreamController = /** @class */ (function (_super) {
  72090. __extends(DaydreamController, _super);
  72091. /**
  72092. * Creates a new DaydreamController from a gamepad
  72093. * @param vrGamepad the gamepad that the controller should be created from
  72094. */
  72095. function DaydreamController(vrGamepad) {
  72096. var _this = _super.call(this, vrGamepad) || this;
  72097. _this.controllerType = BABYLON.PoseEnabledControllerType.DAYDREAM;
  72098. return _this;
  72099. }
  72100. /**
  72101. * Implements abstract method on WebVRController class, loading controller meshes and calling this.attachToMesh if successful.
  72102. * @param scene scene in which to add meshes
  72103. * @param meshLoaded optional callback function that will be called if the mesh loads successfully.
  72104. */
  72105. DaydreamController.prototype.initControllerMesh = function (scene, meshLoaded) {
  72106. var _this = this;
  72107. BABYLON.SceneLoader.ImportMesh("", DaydreamController.MODEL_BASE_URL, DaydreamController.MODEL_FILENAME, scene, function (newMeshes) {
  72108. _this._defaultModel = newMeshes[1];
  72109. _this.attachToMesh(_this._defaultModel);
  72110. if (meshLoaded) {
  72111. meshLoaded(_this._defaultModel);
  72112. }
  72113. });
  72114. };
  72115. /**
  72116. * Called once for each button that changed state since the last frame
  72117. * @param buttonIdx Which button index changed
  72118. * @param state New state of the button
  72119. * @param changes Which properties on the state changed since last frame
  72120. */
  72121. DaydreamController.prototype._handleButtonChange = function (buttonIdx, state, changes) {
  72122. // Daydream controller only has 1 GamepadButton (on the trackpad).
  72123. if (buttonIdx === 0) {
  72124. var observable = this.onTriggerStateChangedObservable;
  72125. if (observable) {
  72126. observable.notifyObservers(state);
  72127. }
  72128. }
  72129. else {
  72130. // If the app or home buttons are ever made available
  72131. BABYLON.Tools.Warn("Unrecognized Daydream button index: " + buttonIdx);
  72132. }
  72133. };
  72134. /**
  72135. * Base Url for the controller model.
  72136. */
  72137. DaydreamController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/generic/';
  72138. /**
  72139. * File name for the controller model.
  72140. */
  72141. DaydreamController.MODEL_FILENAME = 'generic.babylon';
  72142. /**
  72143. * Gamepad Id prefix used to identify Daydream Controller.
  72144. */
  72145. DaydreamController.GAMEPAD_ID_PREFIX = 'Daydream'; // id is 'Daydream Controller'
  72146. return DaydreamController;
  72147. }(BABYLON.WebVRController));
  72148. BABYLON.DaydreamController = DaydreamController;
  72149. })(BABYLON || (BABYLON = {}));
  72150. //# sourceMappingURL=babylon.daydreamController.js.map
  72151. var BABYLON;
  72152. (function (BABYLON) {
  72153. var FollowCamera = /** @class */ (function (_super) {
  72154. __extends(FollowCamera, _super);
  72155. function FollowCamera(name, position, scene, lockedTarget) {
  72156. if (lockedTarget === void 0) { lockedTarget = null; }
  72157. var _this = _super.call(this, name, position, scene) || this;
  72158. _this.radius = 12;
  72159. _this.rotationOffset = 0;
  72160. _this.heightOffset = 4;
  72161. _this.cameraAcceleration = 0.05;
  72162. _this.maxCameraSpeed = 20;
  72163. _this.lockedTarget = lockedTarget;
  72164. return _this;
  72165. }
  72166. FollowCamera.prototype.getRadians = function (degrees) {
  72167. return degrees * Math.PI / 180;
  72168. };
  72169. FollowCamera.prototype.follow = function (cameraTarget) {
  72170. if (!cameraTarget)
  72171. return;
  72172. var yRotation;
  72173. if (cameraTarget.rotationQuaternion) {
  72174. var rotMatrix = new BABYLON.Matrix();
  72175. cameraTarget.rotationQuaternion.toRotationMatrix(rotMatrix);
  72176. yRotation = Math.atan2(rotMatrix.m[8], rotMatrix.m[10]);
  72177. }
  72178. else {
  72179. yRotation = cameraTarget.rotation.y;
  72180. }
  72181. var radians = this.getRadians(this.rotationOffset) + yRotation;
  72182. var targetPosition = cameraTarget.getAbsolutePosition();
  72183. var targetX = targetPosition.x + Math.sin(radians) * this.radius;
  72184. var targetZ = targetPosition.z + Math.cos(radians) * this.radius;
  72185. var dx = targetX - this.position.x;
  72186. var dy = (targetPosition.y + this.heightOffset) - this.position.y;
  72187. var dz = (targetZ) - this.position.z;
  72188. var vx = dx * this.cameraAcceleration * 2; //this is set to .05
  72189. var vy = dy * this.cameraAcceleration;
  72190. var vz = dz * this.cameraAcceleration * 2;
  72191. if (vx > this.maxCameraSpeed || vx < -this.maxCameraSpeed) {
  72192. vx = vx < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
  72193. }
  72194. if (vy > this.maxCameraSpeed || vy < -this.maxCameraSpeed) {
  72195. vy = vy < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
  72196. }
  72197. if (vz > this.maxCameraSpeed || vz < -this.maxCameraSpeed) {
  72198. vz = vz < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
  72199. }
  72200. this.position = new BABYLON.Vector3(this.position.x + vx, this.position.y + vy, this.position.z + vz);
  72201. this.setTarget(targetPosition);
  72202. };
  72203. FollowCamera.prototype._checkInputs = function () {
  72204. _super.prototype._checkInputs.call(this);
  72205. if (this.lockedTarget) {
  72206. this.follow(this.lockedTarget);
  72207. }
  72208. };
  72209. FollowCamera.prototype.getClassName = function () {
  72210. return "FollowCamera";
  72211. };
  72212. __decorate([
  72213. BABYLON.serialize()
  72214. ], FollowCamera.prototype, "radius", void 0);
  72215. __decorate([
  72216. BABYLON.serialize()
  72217. ], FollowCamera.prototype, "rotationOffset", void 0);
  72218. __decorate([
  72219. BABYLON.serialize()
  72220. ], FollowCamera.prototype, "heightOffset", void 0);
  72221. __decorate([
  72222. BABYLON.serialize()
  72223. ], FollowCamera.prototype, "cameraAcceleration", void 0);
  72224. __decorate([
  72225. BABYLON.serialize()
  72226. ], FollowCamera.prototype, "maxCameraSpeed", void 0);
  72227. __decorate([
  72228. BABYLON.serializeAsMeshReference("lockedTargetId")
  72229. ], FollowCamera.prototype, "lockedTarget", void 0);
  72230. return FollowCamera;
  72231. }(BABYLON.TargetCamera));
  72232. BABYLON.FollowCamera = FollowCamera;
  72233. var ArcFollowCamera = /** @class */ (function (_super) {
  72234. __extends(ArcFollowCamera, _super);
  72235. function ArcFollowCamera(name, alpha, beta, radius, target, scene) {
  72236. var _this = _super.call(this, name, BABYLON.Vector3.Zero(), scene) || this;
  72237. _this.alpha = alpha;
  72238. _this.beta = beta;
  72239. _this.radius = radius;
  72240. _this.target = target;
  72241. _this._cartesianCoordinates = BABYLON.Vector3.Zero();
  72242. _this.follow();
  72243. return _this;
  72244. }
  72245. ArcFollowCamera.prototype.follow = function () {
  72246. if (!this.target) {
  72247. return;
  72248. }
  72249. this._cartesianCoordinates.x = this.radius * Math.cos(this.alpha) * Math.cos(this.beta);
  72250. this._cartesianCoordinates.y = this.radius * Math.sin(this.beta);
  72251. this._cartesianCoordinates.z = this.radius * Math.sin(this.alpha) * Math.cos(this.beta);
  72252. var targetPosition = this.target.getAbsolutePosition();
  72253. this.position = targetPosition.add(this._cartesianCoordinates);
  72254. this.setTarget(targetPosition);
  72255. };
  72256. ArcFollowCamera.prototype._checkInputs = function () {
  72257. _super.prototype._checkInputs.call(this);
  72258. this.follow();
  72259. };
  72260. ArcFollowCamera.prototype.getClassName = function () {
  72261. return "ArcFollowCamera";
  72262. };
  72263. return ArcFollowCamera;
  72264. }(BABYLON.TargetCamera));
  72265. BABYLON.ArcFollowCamera = ArcFollowCamera;
  72266. })(BABYLON || (BABYLON = {}));
  72267. //# sourceMappingURL=babylon.followCamera.js.map
  72268. var BABYLON;
  72269. (function (BABYLON) {
  72270. // We're mainly based on the logic defined into the FreeCamera code
  72271. var UniversalCamera = /** @class */ (function (_super) {
  72272. __extends(UniversalCamera, _super);
  72273. //-- end properties for backward compatibility for inputs
  72274. function UniversalCamera(name, position, scene) {
  72275. var _this = _super.call(this, name, position, scene) || this;
  72276. _this.inputs.addGamepad();
  72277. return _this;
  72278. }
  72279. Object.defineProperty(UniversalCamera.prototype, "gamepadAngularSensibility", {
  72280. //-- Begin properties for backward compatibility for inputs
  72281. get: function () {
  72282. var gamepad = this.inputs.attached["gamepad"];
  72283. if (gamepad)
  72284. return gamepad.gamepadAngularSensibility;
  72285. return 0;
  72286. },
  72287. set: function (value) {
  72288. var gamepad = this.inputs.attached["gamepad"];
  72289. if (gamepad)
  72290. gamepad.gamepadAngularSensibility = value;
  72291. },
  72292. enumerable: true,
  72293. configurable: true
  72294. });
  72295. Object.defineProperty(UniversalCamera.prototype, "gamepadMoveSensibility", {
  72296. get: function () {
  72297. var gamepad = this.inputs.attached["gamepad"];
  72298. if (gamepad)
  72299. return gamepad.gamepadMoveSensibility;
  72300. return 0;
  72301. },
  72302. set: function (value) {
  72303. var gamepad = this.inputs.attached["gamepad"];
  72304. if (gamepad)
  72305. gamepad.gamepadMoveSensibility = value;
  72306. },
  72307. enumerable: true,
  72308. configurable: true
  72309. });
  72310. UniversalCamera.prototype.getClassName = function () {
  72311. return "UniversalCamera";
  72312. };
  72313. return UniversalCamera;
  72314. }(BABYLON.TouchCamera));
  72315. BABYLON.UniversalCamera = UniversalCamera;
  72316. })(BABYLON || (BABYLON = {}));
  72317. //# sourceMappingURL=babylon.universalCamera.js.map
  72318. var BABYLON;
  72319. (function (BABYLON) {
  72320. // We're mainly based on the logic defined into the FreeCamera code
  72321. var GamepadCamera = /** @class */ (function (_super) {
  72322. __extends(GamepadCamera, _super);
  72323. //-- end properties for backward compatibility for inputs
  72324. function GamepadCamera(name, position, scene) {
  72325. return _super.call(this, name, position, scene) || this;
  72326. }
  72327. Object.defineProperty(GamepadCamera.prototype, "gamepadAngularSensibility", {
  72328. //-- Begin properties for backward compatibility for inputs
  72329. get: function () {
  72330. var gamepad = this.inputs.attached["gamepad"];
  72331. if (gamepad)
  72332. return gamepad.gamepadAngularSensibility;
  72333. return 0;
  72334. },
  72335. set: function (value) {
  72336. var gamepad = this.inputs.attached["gamepad"];
  72337. if (gamepad)
  72338. gamepad.gamepadAngularSensibility = value;
  72339. },
  72340. enumerable: true,
  72341. configurable: true
  72342. });
  72343. Object.defineProperty(GamepadCamera.prototype, "gamepadMoveSensibility", {
  72344. get: function () {
  72345. var gamepad = this.inputs.attached["gamepad"];
  72346. if (gamepad)
  72347. return gamepad.gamepadMoveSensibility;
  72348. return 0;
  72349. },
  72350. set: function (value) {
  72351. var gamepad = this.inputs.attached["gamepad"];
  72352. if (gamepad)
  72353. gamepad.gamepadMoveSensibility = value;
  72354. },
  72355. enumerable: true,
  72356. configurable: true
  72357. });
  72358. GamepadCamera.prototype.getClassName = function () {
  72359. return "GamepadCamera";
  72360. };
  72361. return GamepadCamera;
  72362. }(BABYLON.UniversalCamera));
  72363. BABYLON.GamepadCamera = GamepadCamera;
  72364. })(BABYLON || (BABYLON = {}));
  72365. //# sourceMappingURL=babylon.gamepadCamera.js.map
  72366. var BABYLON;
  72367. (function (BABYLON) {
  72368. var PostProcessRenderPipelineManager = /** @class */ (function () {
  72369. function PostProcessRenderPipelineManager() {
  72370. this._renderPipelines = {};
  72371. }
  72372. PostProcessRenderPipelineManager.prototype.addPipeline = function (renderPipeline) {
  72373. this._renderPipelines[renderPipeline._name] = renderPipeline;
  72374. };
  72375. PostProcessRenderPipelineManager.prototype.attachCamerasToRenderPipeline = function (renderPipelineName, cameras, unique) {
  72376. if (unique === void 0) { unique = false; }
  72377. var renderPipeline = this._renderPipelines[renderPipelineName];
  72378. if (!renderPipeline) {
  72379. return;
  72380. }
  72381. renderPipeline._attachCameras(cameras, unique);
  72382. };
  72383. PostProcessRenderPipelineManager.prototype.detachCamerasFromRenderPipeline = function (renderPipelineName, cameras) {
  72384. var renderPipeline = this._renderPipelines[renderPipelineName];
  72385. if (!renderPipeline) {
  72386. return;
  72387. }
  72388. renderPipeline._detachCameras(cameras);
  72389. };
  72390. PostProcessRenderPipelineManager.prototype.enableEffectInPipeline = function (renderPipelineName, renderEffectName, cameras) {
  72391. var renderPipeline = this._renderPipelines[renderPipelineName];
  72392. if (!renderPipeline) {
  72393. return;
  72394. }
  72395. renderPipeline._enableEffect(renderEffectName, cameras);
  72396. };
  72397. PostProcessRenderPipelineManager.prototype.disableEffectInPipeline = function (renderPipelineName, renderEffectName, cameras) {
  72398. var renderPipeline = this._renderPipelines[renderPipelineName];
  72399. if (!renderPipeline) {
  72400. return;
  72401. }
  72402. renderPipeline._disableEffect(renderEffectName, cameras);
  72403. };
  72404. PostProcessRenderPipelineManager.prototype.update = function () {
  72405. for (var renderPipelineName in this._renderPipelines) {
  72406. if (this._renderPipelines.hasOwnProperty(renderPipelineName)) {
  72407. var pipeline = this._renderPipelines[renderPipelineName];
  72408. if (!pipeline.isSupported) {
  72409. pipeline.dispose();
  72410. delete this._renderPipelines[renderPipelineName];
  72411. }
  72412. else {
  72413. pipeline._update();
  72414. }
  72415. }
  72416. }
  72417. };
  72418. PostProcessRenderPipelineManager.prototype._rebuild = function () {
  72419. for (var renderPipelineName in this._renderPipelines) {
  72420. if (this._renderPipelines.hasOwnProperty(renderPipelineName)) {
  72421. var pipeline = this._renderPipelines[renderPipelineName];
  72422. pipeline._rebuild();
  72423. }
  72424. }
  72425. };
  72426. PostProcessRenderPipelineManager.prototype.dispose = function () {
  72427. for (var renderPipelineName in this._renderPipelines) {
  72428. if (this._renderPipelines.hasOwnProperty(renderPipelineName)) {
  72429. var pipeline = this._renderPipelines[renderPipelineName];
  72430. pipeline.dispose();
  72431. }
  72432. }
  72433. };
  72434. return PostProcessRenderPipelineManager;
  72435. }());
  72436. BABYLON.PostProcessRenderPipelineManager = PostProcessRenderPipelineManager;
  72437. })(BABYLON || (BABYLON = {}));
  72438. //# sourceMappingURL=babylon.postProcessRenderPipelineManager.js.map
  72439. var BABYLON;
  72440. (function (BABYLON) {
  72441. /**
  72442. * This represents a set of one or more post processes in Babylon.
  72443. * A post process can be used to apply a shader to a texture after it is rendered.
  72444. * @example https://doc.babylonjs.com/how_to/how_to_use_postprocessrenderpipeline
  72445. */
  72446. var PostProcessRenderEffect = /** @class */ (function () {
  72447. /**
  72448. * Instantiates a post process render effect.
  72449. * A post process can be used to apply a shader to a texture after it is rendered.
  72450. * @param engine The engine the effect is tied to
  72451. * @param name The name of the effect
  72452. * @param getPostProcesses A function that returns a set of post processes which the effect will run in order to be run.
  72453. * @param singleInstance False if this post process can be run on multiple cameras. (default: true)
  72454. */
  72455. function PostProcessRenderEffect(engine, name, getPostProcesses, singleInstance) {
  72456. this._name = name;
  72457. this._singleInstance = singleInstance || true;
  72458. this._getPostProcesses = getPostProcesses;
  72459. this._cameras = {};
  72460. this._indicesForCamera = {};
  72461. this._postProcesses = {};
  72462. }
  72463. Object.defineProperty(PostProcessRenderEffect.prototype, "isSupported", {
  72464. /**
  72465. * Checks if all the post processes in the effect are supported.
  72466. */
  72467. get: function () {
  72468. for (var index in this._postProcesses) {
  72469. if (this._postProcesses.hasOwnProperty(index)) {
  72470. var pps = this._postProcesses[index];
  72471. for (var ppIndex = 0; ppIndex < pps.length; ppIndex++) {
  72472. if (!pps[ppIndex].isSupported) {
  72473. return false;
  72474. }
  72475. }
  72476. }
  72477. }
  72478. return true;
  72479. },
  72480. enumerable: true,
  72481. configurable: true
  72482. });
  72483. /**
  72484. * Updates the current state of the effect
  72485. */
  72486. PostProcessRenderEffect.prototype._update = function () {
  72487. };
  72488. /**
  72489. * Attaches the effect on cameras
  72490. * @param cameras The camera to attach to.
  72491. */
  72492. PostProcessRenderEffect.prototype._attachCameras = function (cameras) {
  72493. var _this = this;
  72494. var cameraKey;
  72495. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  72496. if (!cams) {
  72497. return;
  72498. }
  72499. for (var i = 0; i < cams.length; i++) {
  72500. var camera = cams[i];
  72501. var cameraName = camera.name;
  72502. if (this._singleInstance) {
  72503. cameraKey = 0;
  72504. }
  72505. else {
  72506. cameraKey = cameraName;
  72507. }
  72508. if (!this._postProcesses[cameraKey]) {
  72509. var postProcess = this._getPostProcesses();
  72510. if (postProcess) {
  72511. this._postProcesses[cameraKey] = Array.isArray(postProcess) ? postProcess : [postProcess];
  72512. }
  72513. }
  72514. if (!this._indicesForCamera[cameraName]) {
  72515. this._indicesForCamera[cameraName] = [];
  72516. }
  72517. this._postProcesses[cameraKey].forEach(function (postProcess) {
  72518. var index = camera.attachPostProcess(postProcess);
  72519. _this._indicesForCamera[cameraName].push(index);
  72520. });
  72521. if (!this._cameras[cameraName]) {
  72522. this._cameras[cameraName] = camera;
  72523. }
  72524. }
  72525. };
  72526. /**
  72527. * Detatches the effect on cameras
  72528. * @param cameras The camera to detatch from.
  72529. */
  72530. PostProcessRenderEffect.prototype._detachCameras = function (cameras) {
  72531. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  72532. if (!cams) {
  72533. return;
  72534. }
  72535. for (var i = 0; i < cams.length; i++) {
  72536. var camera = cams[i];
  72537. var cameraName = camera.name;
  72538. this._postProcesses[this._singleInstance ? 0 : cameraName].forEach(function (postProcess) {
  72539. camera.detachPostProcess(postProcess);
  72540. });
  72541. if (this._cameras[cameraName]) {
  72542. //this._indicesForCamera.splice(index, 1);
  72543. this._cameras[cameraName] = null;
  72544. }
  72545. }
  72546. };
  72547. /**
  72548. * Enables the effect on given cameras
  72549. * @param cameras The camera to enable.
  72550. */
  72551. PostProcessRenderEffect.prototype._enable = function (cameras) {
  72552. var _this = this;
  72553. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  72554. if (!cams) {
  72555. return;
  72556. }
  72557. for (var i = 0; i < cams.length; i++) {
  72558. var camera = cams[i];
  72559. var cameraName = camera.name;
  72560. for (var j = 0; j < this._indicesForCamera[cameraName].length; j++) {
  72561. if (camera._postProcesses[this._indicesForCamera[cameraName][j]] === undefined || camera._postProcesses[this._indicesForCamera[cameraName][j]] === null) {
  72562. this._postProcesses[this._singleInstance ? 0 : cameraName].forEach(function (postProcess) {
  72563. cams[i].attachPostProcess(postProcess, _this._indicesForCamera[cameraName][j]);
  72564. });
  72565. }
  72566. }
  72567. }
  72568. };
  72569. /**
  72570. * Disables the effect on the given cameras
  72571. * @param cameras The camera to disable.
  72572. */
  72573. PostProcessRenderEffect.prototype._disable = function (cameras) {
  72574. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  72575. if (!cams) {
  72576. return;
  72577. }
  72578. for (var i = 0; i < cams.length; i++) {
  72579. var camera = cams[i];
  72580. var cameraName = camera.name;
  72581. this._postProcesses[this._singleInstance ? 0 : cameraName].forEach(function (postProcess) {
  72582. camera.detachPostProcess(postProcess);
  72583. });
  72584. }
  72585. };
  72586. /**
  72587. * Gets a list of the post processes contained in the effect.
  72588. * @param camera The camera to get the post processes on.
  72589. * @returns The list of the post processes in the effect.
  72590. */
  72591. PostProcessRenderEffect.prototype.getPostProcesses = function (camera) {
  72592. if (this._singleInstance) {
  72593. return this._postProcesses[0];
  72594. }
  72595. else {
  72596. if (!camera) {
  72597. return null;
  72598. }
  72599. return this._postProcesses[camera.name];
  72600. }
  72601. };
  72602. return PostProcessRenderEffect;
  72603. }());
  72604. BABYLON.PostProcessRenderEffect = PostProcessRenderEffect;
  72605. })(BABYLON || (BABYLON = {}));
  72606. //# sourceMappingURL=babylon.postProcessRenderEffect.js.map
  72607. var BABYLON;
  72608. (function (BABYLON) {
  72609. var PostProcessRenderPipeline = /** @class */ (function () {
  72610. function PostProcessRenderPipeline(engine, name) {
  72611. this.engine = engine;
  72612. this._name = name;
  72613. this._renderEffects = {};
  72614. this._renderEffectsForIsolatedPass = new Array();
  72615. this._cameras = [];
  72616. }
  72617. PostProcessRenderPipeline.prototype.getClassName = function () {
  72618. return "PostProcessRenderPipeline";
  72619. };
  72620. Object.defineProperty(PostProcessRenderPipeline.prototype, "isSupported", {
  72621. get: function () {
  72622. for (var renderEffectName in this._renderEffects) {
  72623. if (this._renderEffects.hasOwnProperty(renderEffectName)) {
  72624. if (!this._renderEffects[renderEffectName].isSupported) {
  72625. return false;
  72626. }
  72627. }
  72628. }
  72629. return true;
  72630. },
  72631. enumerable: true,
  72632. configurable: true
  72633. });
  72634. PostProcessRenderPipeline.prototype.addEffect = function (renderEffect) {
  72635. this._renderEffects[renderEffect._name] = renderEffect;
  72636. };
  72637. // private
  72638. PostProcessRenderPipeline.prototype._rebuild = function () {
  72639. };
  72640. PostProcessRenderPipeline.prototype._enableEffect = function (renderEffectName, cameras) {
  72641. var renderEffects = this._renderEffects[renderEffectName];
  72642. if (!renderEffects) {
  72643. return;
  72644. }
  72645. renderEffects._enable(BABYLON.Tools.MakeArray(cameras || this._cameras));
  72646. };
  72647. PostProcessRenderPipeline.prototype._disableEffect = function (renderEffectName, cameras) {
  72648. var renderEffects = this._renderEffects[renderEffectName];
  72649. if (!renderEffects) {
  72650. return;
  72651. }
  72652. renderEffects._disable(BABYLON.Tools.MakeArray(cameras || this._cameras));
  72653. };
  72654. PostProcessRenderPipeline.prototype._attachCameras = function (cameras, unique) {
  72655. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  72656. if (!cams) {
  72657. return;
  72658. }
  72659. var indicesToDelete = [];
  72660. var i;
  72661. for (i = 0; i < cams.length; i++) {
  72662. var camera = cams[i];
  72663. var cameraName = camera.name;
  72664. if (this._cameras.indexOf(camera) === -1) {
  72665. this._cameras[cameraName] = camera;
  72666. }
  72667. else if (unique) {
  72668. indicesToDelete.push(i);
  72669. }
  72670. }
  72671. for (i = 0; i < indicesToDelete.length; i++) {
  72672. cameras.splice(indicesToDelete[i], 1);
  72673. }
  72674. for (var renderEffectName in this._renderEffects) {
  72675. if (this._renderEffects.hasOwnProperty(renderEffectName)) {
  72676. this._renderEffects[renderEffectName]._attachCameras(cams);
  72677. }
  72678. }
  72679. };
  72680. PostProcessRenderPipeline.prototype._detachCameras = function (cameras) {
  72681. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  72682. if (!cams) {
  72683. return;
  72684. }
  72685. for (var renderEffectName in this._renderEffects) {
  72686. if (this._renderEffects.hasOwnProperty(renderEffectName)) {
  72687. this._renderEffects[renderEffectName]._detachCameras(cams);
  72688. }
  72689. }
  72690. for (var i = 0; i < cams.length; i++) {
  72691. this._cameras.splice(this._cameras.indexOf(cams[i]), 1);
  72692. }
  72693. };
  72694. PostProcessRenderPipeline.prototype._update = function () {
  72695. for (var renderEffectName in this._renderEffects) {
  72696. if (this._renderEffects.hasOwnProperty(renderEffectName)) {
  72697. this._renderEffects[renderEffectName]._update();
  72698. }
  72699. }
  72700. for (var i = 0; i < this._cameras.length; i++) {
  72701. var cameraName = this._cameras[i].name;
  72702. if (this._renderEffectsForIsolatedPass[cameraName]) {
  72703. this._renderEffectsForIsolatedPass[cameraName]._update();
  72704. }
  72705. }
  72706. };
  72707. PostProcessRenderPipeline.prototype._reset = function () {
  72708. this._renderEffects = {};
  72709. this._renderEffectsForIsolatedPass = new Array();
  72710. };
  72711. PostProcessRenderPipeline.prototype._enableMSAAOnFirstPostProcess = function (sampleCount) {
  72712. // 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)
  72713. var effectKeys = Object.keys(this._renderEffects);
  72714. if (this.engine.webGLVersion >= 2 && effectKeys.length > 0) {
  72715. var postProcesses = this._renderEffects[effectKeys[0]].getPostProcesses();
  72716. if (postProcesses) {
  72717. postProcesses[0].samples = sampleCount;
  72718. return true;
  72719. }
  72720. }
  72721. return false;
  72722. };
  72723. PostProcessRenderPipeline.prototype.dispose = function () {
  72724. // Must be implemented by children
  72725. };
  72726. __decorate([
  72727. BABYLON.serialize()
  72728. ], PostProcessRenderPipeline.prototype, "_name", void 0);
  72729. return PostProcessRenderPipeline;
  72730. }());
  72731. BABYLON.PostProcessRenderPipeline = PostProcessRenderPipeline;
  72732. })(BABYLON || (BABYLON = {}));
  72733. //# sourceMappingURL=babylon.postProcessRenderPipeline.js.map
  72734. var BABYLON;
  72735. (function (BABYLON) {
  72736. /**
  72737. * This represents a depth renderer in Babylon.
  72738. * A depth renderer will render to it's depth map every frame which can be displayed or used in post processing
  72739. */
  72740. var DepthRenderer = /** @class */ (function () {
  72741. /**
  72742. * Instantiates a depth renderer
  72743. * @param scene The scene the renderer belongs to
  72744. * @param type The texture type of the depth map (default: Engine.TEXTURETYPE_FLOAT)
  72745. * @param camera The camera to be used to render the depth map (default: scene's active camera)
  72746. */
  72747. function DepthRenderer(scene, type, camera) {
  72748. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_FLOAT; }
  72749. if (camera === void 0) { camera = null; }
  72750. var _this = this;
  72751. this._scene = scene;
  72752. this._camera = camera;
  72753. var engine = scene.getEngine();
  72754. // Render target
  72755. this._depthMap = new BABYLON.RenderTargetTexture("depthMap", { width: engine.getRenderWidth(), height: engine.getRenderHeight() }, this._scene, false, true, type);
  72756. this._depthMap.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  72757. this._depthMap.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  72758. this._depthMap.refreshRate = 1;
  72759. this._depthMap.renderParticles = false;
  72760. this._depthMap.renderList = null;
  72761. // Camera to get depth map from to support multiple concurrent cameras
  72762. this._depthMap.activeCamera = this._camera;
  72763. this._depthMap.ignoreCameraViewport = true;
  72764. this._depthMap.useCameraPostProcesses = false;
  72765. // set default depth value to 1.0 (far away)
  72766. this._depthMap.onClearObservable.add(function (engine) {
  72767. engine.clear(new BABYLON.Color4(1.0, 1.0, 1.0, 1.0), true, true, true);
  72768. });
  72769. // Custom render function
  72770. var renderSubMesh = function (subMesh) {
  72771. var mesh = subMesh.getRenderingMesh();
  72772. var scene = _this._scene;
  72773. var engine = scene.getEngine();
  72774. var material = subMesh.getMaterial();
  72775. if (!material) {
  72776. return;
  72777. }
  72778. // Culling and reverse (right handed system)
  72779. engine.setState(material.backFaceCulling, 0, false, scene.useRightHandedSystem);
  72780. // Managing instances
  72781. var batch = mesh._getInstancesRenderList(subMesh._id);
  72782. if (batch.mustReturn) {
  72783. return;
  72784. }
  72785. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null);
  72786. var camera = _this._camera || scene.activeCamera;
  72787. if (_this.isReady(subMesh, hardwareInstancedRendering) && camera) {
  72788. engine.enableEffect(_this._effect);
  72789. mesh._bind(subMesh, _this._effect, BABYLON.Material.TriangleFillMode);
  72790. _this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
  72791. _this._effect.setFloat2("depthValues", camera.minZ, camera.minZ + camera.maxZ);
  72792. // Alpha test
  72793. if (material && material.needAlphaTesting()) {
  72794. var alphaTexture = material.getAlphaTestTexture();
  72795. if (alphaTexture) {
  72796. _this._effect.setTexture("diffuseSampler", alphaTexture);
  72797. _this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  72798. }
  72799. }
  72800. // Bones
  72801. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  72802. _this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  72803. }
  72804. // Draw
  72805. mesh._processRendering(subMesh, _this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._effect.setMatrix("world", world); });
  72806. }
  72807. };
  72808. this._depthMap.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes, depthOnlySubMeshes) {
  72809. var index;
  72810. if (depthOnlySubMeshes.length) {
  72811. engine.setColorWrite(false);
  72812. for (index = 0; index < depthOnlySubMeshes.length; index++) {
  72813. renderSubMesh(depthOnlySubMeshes.data[index]);
  72814. }
  72815. engine.setColorWrite(true);
  72816. }
  72817. for (index = 0; index < opaqueSubMeshes.length; index++) {
  72818. renderSubMesh(opaqueSubMeshes.data[index]);
  72819. }
  72820. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  72821. renderSubMesh(alphaTestSubMeshes.data[index]);
  72822. }
  72823. };
  72824. }
  72825. /**
  72826. * Creates the depth rendering effect and checks if the effect is ready.
  72827. * @param subMesh The submesh to be used to render the depth map of
  72828. * @param useInstances If multiple world instances should be used
  72829. * @returns if the depth renderer is ready to render the depth map
  72830. */
  72831. DepthRenderer.prototype.isReady = function (subMesh, useInstances) {
  72832. var material = subMesh.getMaterial();
  72833. if (material.disableDepthWrite) {
  72834. return false;
  72835. }
  72836. var defines = [];
  72837. var attribs = [BABYLON.VertexBuffer.PositionKind];
  72838. var mesh = subMesh.getMesh();
  72839. // Alpha test
  72840. if (material && material.needAlphaTesting() && material.getAlphaTestTexture()) {
  72841. defines.push("#define ALPHATEST");
  72842. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  72843. attribs.push(BABYLON.VertexBuffer.UVKind);
  72844. defines.push("#define UV1");
  72845. }
  72846. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  72847. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  72848. defines.push("#define UV2");
  72849. }
  72850. }
  72851. // Bones
  72852. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  72853. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  72854. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  72855. if (mesh.numBoneInfluencers > 4) {
  72856. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  72857. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  72858. }
  72859. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  72860. defines.push("#define BonesPerMesh " + (mesh.skeleton ? mesh.skeleton.bones.length + 1 : 0));
  72861. }
  72862. else {
  72863. defines.push("#define NUM_BONE_INFLUENCERS 0");
  72864. }
  72865. // Instances
  72866. if (useInstances) {
  72867. defines.push("#define INSTANCES");
  72868. attribs.push("world0");
  72869. attribs.push("world1");
  72870. attribs.push("world2");
  72871. attribs.push("world3");
  72872. }
  72873. // Get correct effect
  72874. var join = defines.join("\n");
  72875. if (this._cachedDefines !== join) {
  72876. this._cachedDefines = join;
  72877. this._effect = this._scene.getEngine().createEffect("depth", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "depthValues"], ["diffuseSampler"], join);
  72878. }
  72879. return this._effect.isReady();
  72880. };
  72881. /**
  72882. * Gets the texture which the depth map will be written to.
  72883. * @returns The depth map texture
  72884. */
  72885. DepthRenderer.prototype.getDepthMap = function () {
  72886. return this._depthMap;
  72887. };
  72888. /**
  72889. * Disposes of the depth renderer.
  72890. */
  72891. DepthRenderer.prototype.dispose = function () {
  72892. this._depthMap.dispose();
  72893. };
  72894. return DepthRenderer;
  72895. }());
  72896. BABYLON.DepthRenderer = DepthRenderer;
  72897. })(BABYLON || (BABYLON = {}));
  72898. //# sourceMappingURL=babylon.depthRenderer.js.map
  72899. var BABYLON;
  72900. (function (BABYLON) {
  72901. var SSAORenderingPipeline = /** @class */ (function (_super) {
  72902. __extends(SSAORenderingPipeline, _super);
  72903. /**
  72904. * @constructor
  72905. * @param {string} name - The rendering pipeline name
  72906. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  72907. * @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 }
  72908. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  72909. */
  72910. function SSAORenderingPipeline(name, scene, ratio, cameras) {
  72911. var _this = _super.call(this, scene.getEngine(), name) || this;
  72912. // Members
  72913. /**
  72914. * The PassPostProcess id in the pipeline that contains the original scene color
  72915. */
  72916. _this.SSAOOriginalSceneColorEffect = "SSAOOriginalSceneColorEffect";
  72917. /**
  72918. * The SSAO PostProcess id in the pipeline
  72919. */
  72920. _this.SSAORenderEffect = "SSAORenderEffect";
  72921. /**
  72922. * The horizontal blur PostProcess id in the pipeline
  72923. */
  72924. _this.SSAOBlurHRenderEffect = "SSAOBlurHRenderEffect";
  72925. /**
  72926. * The vertical blur PostProcess id in the pipeline
  72927. */
  72928. _this.SSAOBlurVRenderEffect = "SSAOBlurVRenderEffect";
  72929. /**
  72930. * The PostProcess id in the pipeline that combines the SSAO-Blur output with the original scene color (SSAOOriginalSceneColorEffect)
  72931. */
  72932. _this.SSAOCombineRenderEffect = "SSAOCombineRenderEffect";
  72933. /**
  72934. * The output strength of the SSAO post-process. Default value is 1.0.
  72935. */
  72936. _this.totalStrength = 1.0;
  72937. /**
  72938. * The radius around the analyzed pixel used by the SSAO post-process. Default value is 0.0006
  72939. */
  72940. _this.radius = 0.0001;
  72941. /**
  72942. * Related to fallOff, used to interpolate SSAO samples (first interpolate function input) based on the occlusion difference of each pixel
  72943. * Must not be equal to fallOff and superior to fallOff.
  72944. * Default value is 0.975
  72945. */
  72946. _this.area = 0.0075;
  72947. /**
  72948. * Related to area, used to interpolate SSAO samples (second interpolate function input) based on the occlusion difference of each pixel
  72949. * Must not be equal to area and inferior to area.
  72950. * Default value is 0.0
  72951. */
  72952. _this.fallOff = 0.000001;
  72953. /**
  72954. * The base color of the SSAO post-process
  72955. * The final result is "base + ssao" between [0, 1]
  72956. */
  72957. _this.base = 0.5;
  72958. _this._firstUpdate = true;
  72959. _this._scene = scene;
  72960. // Set up assets
  72961. _this._createRandomTexture();
  72962. _this._depthTexture = scene.enableDepthRenderer().getDepthMap(); // Force depth renderer "on"
  72963. var ssaoRatio = ratio.ssaoRatio || ratio;
  72964. var combineRatio = ratio.combineRatio || ratio;
  72965. _this._originalColorPostProcess = new BABYLON.PassPostProcess("SSAOOriginalSceneColor", combineRatio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false);
  72966. _this._createSSAOPostProcess(ssaoRatio);
  72967. _this._createBlurPostProcess(ssaoRatio);
  72968. _this._createSSAOCombinePostProcess(combineRatio);
  72969. // Set up pipeline
  72970. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOOriginalSceneColorEffect, function () { return _this._originalColorPostProcess; }, true));
  72971. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAORenderEffect, function () { return _this._ssaoPostProcess; }, true));
  72972. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOBlurHRenderEffect, function () { return _this._blurHPostProcess; }, true));
  72973. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOBlurVRenderEffect, function () { return _this._blurVPostProcess; }, true));
  72974. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOCombineRenderEffect, function () { return _this._ssaoCombinePostProcess; }, true));
  72975. // Finish
  72976. scene.postProcessRenderPipelineManager.addPipeline(_this);
  72977. if (cameras)
  72978. scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(name, cameras);
  72979. return _this;
  72980. }
  72981. // Public Methods
  72982. /**
  72983. * Removes the internal pipeline assets and detatches the pipeline from the scene cameras
  72984. */
  72985. SSAORenderingPipeline.prototype.dispose = function (disableDepthRender) {
  72986. if (disableDepthRender === void 0) { disableDepthRender = false; }
  72987. for (var i = 0; i < this._scene.cameras.length; i++) {
  72988. var camera = this._scene.cameras[i];
  72989. this._originalColorPostProcess.dispose(camera);
  72990. this._ssaoPostProcess.dispose(camera);
  72991. this._blurHPostProcess.dispose(camera);
  72992. this._blurVPostProcess.dispose(camera);
  72993. this._ssaoCombinePostProcess.dispose(camera);
  72994. }
  72995. this._randomTexture.dispose();
  72996. if (disableDepthRender)
  72997. this._scene.disableDepthRenderer();
  72998. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._scene.cameras);
  72999. _super.prototype.dispose.call(this);
  73000. };
  73001. // Private Methods
  73002. SSAORenderingPipeline.prototype._createBlurPostProcess = function (ratio) {
  73003. var _this = this;
  73004. var size = 16;
  73005. 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);
  73006. 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);
  73007. this._blurHPostProcess.onActivateObservable.add(function () {
  73008. var dw = _this._blurHPostProcess.width / _this._scene.getEngine().getRenderWidth();
  73009. _this._blurHPostProcess.kernel = size * dw;
  73010. });
  73011. this._blurVPostProcess.onActivateObservable.add(function () {
  73012. var dw = _this._blurVPostProcess.height / _this._scene.getEngine().getRenderHeight();
  73013. _this._blurVPostProcess.kernel = size * dw;
  73014. });
  73015. };
  73016. SSAORenderingPipeline.prototype._rebuild = function () {
  73017. this._firstUpdate = true;
  73018. _super.prototype._rebuild.call(this);
  73019. };
  73020. SSAORenderingPipeline.prototype._createSSAOPostProcess = function (ratio) {
  73021. var _this = this;
  73022. var numSamples = 16;
  73023. var sampleSphere = [
  73024. 0.5381, 0.1856, -0.4319,
  73025. 0.1379, 0.2486, 0.4430,
  73026. 0.3371, 0.5679, -0.0057,
  73027. -0.6999, -0.0451, -0.0019,
  73028. 0.0689, -0.1598, -0.8547,
  73029. 0.0560, 0.0069, -0.1843,
  73030. -0.0146, 0.1402, 0.0762,
  73031. 0.0100, -0.1924, -0.0344,
  73032. -0.3577, -0.5301, -0.4358,
  73033. -0.3169, 0.1063, 0.0158,
  73034. 0.0103, -0.5869, 0.0046,
  73035. -0.0897, -0.4940, 0.3287,
  73036. 0.7119, -0.0154, -0.0918,
  73037. -0.0533, 0.0596, -0.5411,
  73038. 0.0352, -0.0631, 0.5460,
  73039. -0.4776, 0.2847, -0.0271
  73040. ];
  73041. var samplesFactor = 1.0 / numSamples;
  73042. this._ssaoPostProcess = new BABYLON.PostProcess("ssao", "ssao", [
  73043. "sampleSphere", "samplesFactor", "randTextureTiles", "totalStrength", "radius",
  73044. "area", "fallOff", "base", "range", "viewport"
  73045. ], ["randomSampler"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, "#define SAMPLES " + numSamples + "\n#define SSAO");
  73046. this._ssaoPostProcess.onApply = function (effect) {
  73047. if (_this._firstUpdate) {
  73048. effect.setArray3("sampleSphere", sampleSphere);
  73049. effect.setFloat("samplesFactor", samplesFactor);
  73050. effect.setFloat("randTextureTiles", 4.0);
  73051. }
  73052. effect.setFloat("totalStrength", _this.totalStrength);
  73053. effect.setFloat("radius", _this.radius);
  73054. effect.setFloat("area", _this.area);
  73055. effect.setFloat("fallOff", _this.fallOff);
  73056. effect.setFloat("base", _this.base);
  73057. effect.setTexture("textureSampler", _this._depthTexture);
  73058. effect.setTexture("randomSampler", _this._randomTexture);
  73059. };
  73060. };
  73061. SSAORenderingPipeline.prototype._createSSAOCombinePostProcess = function (ratio) {
  73062. var _this = this;
  73063. this._ssaoCombinePostProcess = new BABYLON.PostProcess("ssaoCombine", "ssaoCombine", [], ["originalColor"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  73064. this._ssaoCombinePostProcess.onApply = function (effect) {
  73065. effect.setTextureFromPostProcess("originalColor", _this._originalColorPostProcess);
  73066. };
  73067. };
  73068. SSAORenderingPipeline.prototype._createRandomTexture = function () {
  73069. var size = 512;
  73070. this._randomTexture = new BABYLON.DynamicTexture("SSAORandomTexture", size, this._scene, false, BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  73071. this._randomTexture.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  73072. this._randomTexture.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  73073. var context = this._randomTexture.getContext();
  73074. var rand = function (min, max) {
  73075. return Math.random() * (max - min) + min;
  73076. };
  73077. var randVector = BABYLON.Vector3.Zero();
  73078. for (var x = 0; x < size; x++) {
  73079. for (var y = 0; y < size; y++) {
  73080. randVector.x = Math.floor(rand(-1.0, 1.0) * 255);
  73081. randVector.y = Math.floor(rand(-1.0, 1.0) * 255);
  73082. randVector.z = Math.floor(rand(-1.0, 1.0) * 255);
  73083. context.fillStyle = 'rgb(' + randVector.x + ', ' + randVector.y + ', ' + randVector.z + ')';
  73084. context.fillRect(x, y, 1, 1);
  73085. }
  73086. }
  73087. this._randomTexture.update(false);
  73088. };
  73089. __decorate([
  73090. BABYLON.serialize()
  73091. ], SSAORenderingPipeline.prototype, "totalStrength", void 0);
  73092. __decorate([
  73093. BABYLON.serialize()
  73094. ], SSAORenderingPipeline.prototype, "radius", void 0);
  73095. __decorate([
  73096. BABYLON.serialize()
  73097. ], SSAORenderingPipeline.prototype, "area", void 0);
  73098. __decorate([
  73099. BABYLON.serialize()
  73100. ], SSAORenderingPipeline.prototype, "fallOff", void 0);
  73101. __decorate([
  73102. BABYLON.serialize()
  73103. ], SSAORenderingPipeline.prototype, "base", void 0);
  73104. return SSAORenderingPipeline;
  73105. }(BABYLON.PostProcessRenderPipeline));
  73106. BABYLON.SSAORenderingPipeline = SSAORenderingPipeline;
  73107. })(BABYLON || (BABYLON = {}));
  73108. //# sourceMappingURL=babylon.ssaoRenderingPipeline.js.map
  73109. var BABYLON;
  73110. (function (BABYLON) {
  73111. var SSAO2RenderingPipeline = /** @class */ (function (_super) {
  73112. __extends(SSAO2RenderingPipeline, _super);
  73113. /**
  73114. * @constructor
  73115. * @param {string} name - The rendering pipeline name
  73116. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  73117. * @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 }
  73118. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  73119. */
  73120. function SSAO2RenderingPipeline(name, scene, ratio, cameras) {
  73121. var _this = _super.call(this, scene.getEngine(), name) || this;
  73122. // Members
  73123. /**
  73124. * The PassPostProcess id in the pipeline that contains the original scene color
  73125. */
  73126. _this.SSAOOriginalSceneColorEffect = "SSAOOriginalSceneColorEffect";
  73127. /**
  73128. * The SSAO PostProcess id in the pipeline
  73129. */
  73130. _this.SSAORenderEffect = "SSAORenderEffect";
  73131. /**
  73132. * The horizontal blur PostProcess id in the pipeline
  73133. */
  73134. _this.SSAOBlurHRenderEffect = "SSAOBlurHRenderEffect";
  73135. /**
  73136. * The vertical blur PostProcess id in the pipeline
  73137. */
  73138. _this.SSAOBlurVRenderEffect = "SSAOBlurVRenderEffect";
  73139. /**
  73140. * The PostProcess id in the pipeline that combines the SSAO-Blur output with the original scene color (SSAOOriginalSceneColorEffect)
  73141. */
  73142. _this.SSAOCombineRenderEffect = "SSAOCombineRenderEffect";
  73143. /**
  73144. * The output strength of the SSAO post-process. Default value is 1.0.
  73145. */
  73146. _this.totalStrength = 1.0;
  73147. /**
  73148. * Maximum depth value to still render AO. A smooth falloff makes the dimming more natural, so there will be no abrupt shading change.
  73149. */
  73150. _this.maxZ = 100.0;
  73151. /**
  73152. * In order to save performances, SSAO radius is clamped on close geometry. This ratio changes by how much
  73153. */
  73154. _this.minZAspect = 0.2;
  73155. /**
  73156. * Number of samples used for the SSAO calculations. Default value is 8
  73157. */
  73158. _this._samples = 8;
  73159. /**
  73160. * Are we using bilateral blur ?
  73161. */
  73162. _this._expensiveBlur = true;
  73163. /**
  73164. * The radius around the analyzed pixel used by the SSAO post-process. Default value is 2.0
  73165. */
  73166. _this.radius = 2.0;
  73167. /**
  73168. * The base color of the SSAO post-process
  73169. * The final result is "base + ssao" between [0, 1]
  73170. */
  73171. _this.base = 0.1;
  73172. _this._firstUpdate = true;
  73173. _this._scene = scene;
  73174. if (!_this.isSupported) {
  73175. BABYLON.Tools.Error("SSAO 2 needs WebGL 2 support.");
  73176. return _this;
  73177. }
  73178. var ssaoRatio = ratio.ssaoRatio || ratio;
  73179. var blurRatio = ratio.blurRatio || ratio;
  73180. // Set up assets
  73181. var geometryBufferRenderer = scene.enableGeometryBufferRenderer();
  73182. _this._createRandomTexture();
  73183. _this._depthTexture = geometryBufferRenderer.getGBuffer().textures[0];
  73184. _this._normalTexture = geometryBufferRenderer.getGBuffer().textures[1];
  73185. _this._originalColorPostProcess = new BABYLON.PassPostProcess("SSAOOriginalSceneColor", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false);
  73186. _this._createSSAOPostProcess(1.0);
  73187. _this._createBlurPostProcess(ssaoRatio, blurRatio);
  73188. _this._createSSAOCombinePostProcess(blurRatio);
  73189. // Set up pipeline
  73190. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOOriginalSceneColorEffect, function () { return _this._originalColorPostProcess; }, true));
  73191. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAORenderEffect, function () { return _this._ssaoPostProcess; }, true));
  73192. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOBlurHRenderEffect, function () { return _this._blurHPostProcess; }, true));
  73193. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOBlurVRenderEffect, function () { return _this._blurVPostProcess; }, true));
  73194. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOCombineRenderEffect, function () { return _this._ssaoCombinePostProcess; }, true));
  73195. // Finish
  73196. scene.postProcessRenderPipelineManager.addPipeline(_this);
  73197. if (cameras)
  73198. scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(name, cameras);
  73199. return _this;
  73200. }
  73201. Object.defineProperty(SSAO2RenderingPipeline.prototype, "samples", {
  73202. get: function () {
  73203. return this._samples;
  73204. },
  73205. set: function (n) {
  73206. this._ssaoPostProcess.updateEffect("#define SAMPLES " + n + "\n#define SSAO");
  73207. this._samples = n;
  73208. this._sampleSphere = this._generateHemisphere();
  73209. this._firstUpdate = true;
  73210. },
  73211. enumerable: true,
  73212. configurable: true
  73213. });
  73214. Object.defineProperty(SSAO2RenderingPipeline.prototype, "expensiveBlur", {
  73215. get: function () {
  73216. return this._expensiveBlur;
  73217. },
  73218. set: function (b) {
  73219. 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"]);
  73220. this._blurVPostProcess.updateEffect("#define BILATERAL_BLUR\n#define SAMPLES 16\n#define EXPENSIVE " + (b ? "1" : "0") + "\n", null, ["textureSampler", "depthSampler"]);
  73221. this._expensiveBlur = b;
  73222. this._firstUpdate = true;
  73223. },
  73224. enumerable: true,
  73225. configurable: true
  73226. });
  73227. Object.defineProperty(SSAO2RenderingPipeline, "IsSupported", {
  73228. /**
  73229. * Support test.
  73230. */
  73231. get: function () {
  73232. var engine = BABYLON.Engine.LastCreatedEngine;
  73233. if (!engine) {
  73234. return false;
  73235. }
  73236. return engine.getCaps().drawBuffersExtension;
  73237. },
  73238. enumerable: true,
  73239. configurable: true
  73240. });
  73241. // Public Methods
  73242. /**
  73243. * Removes the internal pipeline assets and detatches the pipeline from the scene cameras
  73244. */
  73245. SSAO2RenderingPipeline.prototype.dispose = function (disableGeometryBufferRenderer) {
  73246. if (disableGeometryBufferRenderer === void 0) { disableGeometryBufferRenderer = false; }
  73247. for (var i = 0; i < this._scene.cameras.length; i++) {
  73248. var camera = this._scene.cameras[i];
  73249. this._originalColorPostProcess.dispose(camera);
  73250. this._ssaoPostProcess.dispose(camera);
  73251. this._blurHPostProcess.dispose(camera);
  73252. this._blurVPostProcess.dispose(camera);
  73253. this._ssaoCombinePostProcess.dispose(camera);
  73254. }
  73255. this._randomTexture.dispose();
  73256. if (disableGeometryBufferRenderer)
  73257. this._scene.disableGeometryBufferRenderer();
  73258. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._scene.cameras);
  73259. _super.prototype.dispose.call(this);
  73260. };
  73261. // Private Methods
  73262. SSAO2RenderingPipeline.prototype._createBlurPostProcess = function (ssaoRatio, blurRatio) {
  73263. var _this = this;
  73264. this._samplerOffsets = [];
  73265. var expensive = this.expensiveBlur;
  73266. for (var i = -8; i < 8; i++) {
  73267. this._samplerOffsets.push(i * 2 + 0.5);
  73268. }
  73269. 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");
  73270. this._blurHPostProcess.onApply = function (effect) {
  73271. if (!_this._scene.activeCamera) {
  73272. return;
  73273. }
  73274. effect.setFloat("outSize", _this._ssaoCombinePostProcess.width > 0 ? _this._ssaoCombinePostProcess.width : _this._originalColorPostProcess.width);
  73275. effect.setFloat("near", _this._scene.activeCamera.minZ);
  73276. effect.setFloat("far", _this._scene.activeCamera.maxZ);
  73277. effect.setFloat("radius", _this.radius);
  73278. effect.setTexture("depthSampler", _this._depthTexture);
  73279. if (_this._firstUpdate) {
  73280. effect.setArray("samplerOffsets", _this._samplerOffsets);
  73281. }
  73282. };
  73283. 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");
  73284. this._blurVPostProcess.onApply = function (effect) {
  73285. if (!_this._scene.activeCamera) {
  73286. return;
  73287. }
  73288. effect.setFloat("outSize", _this._ssaoCombinePostProcess.height > 0 ? _this._ssaoCombinePostProcess.height : _this._originalColorPostProcess.height);
  73289. effect.setFloat("near", _this._scene.activeCamera.minZ);
  73290. effect.setFloat("far", _this._scene.activeCamera.maxZ);
  73291. effect.setFloat("radius", _this.radius);
  73292. effect.setTexture("depthSampler", _this._depthTexture);
  73293. if (_this._firstUpdate) {
  73294. effect.setArray("samplerOffsets", _this._samplerOffsets);
  73295. _this._firstUpdate = false;
  73296. }
  73297. };
  73298. };
  73299. SSAO2RenderingPipeline.prototype._rebuild = function () {
  73300. this._firstUpdate = true;
  73301. _super.prototype._rebuild.call(this);
  73302. };
  73303. SSAO2RenderingPipeline.prototype._generateHemisphere = function () {
  73304. var numSamples = this.samples;
  73305. var result = [];
  73306. var vector, scale;
  73307. var rand = function (min, max) {
  73308. return Math.random() * (max - min) + min;
  73309. };
  73310. var i = 0;
  73311. while (i < numSamples) {
  73312. vector = new BABYLON.Vector3(rand(-1.0, 1.0), rand(-1.0, 1.0), rand(0.30, 1.0));
  73313. vector.normalize();
  73314. scale = i / numSamples;
  73315. scale = BABYLON.Scalar.Lerp(0.1, 1.0, scale * scale);
  73316. vector.scaleInPlace(scale);
  73317. result.push(vector.x, vector.y, vector.z);
  73318. i++;
  73319. }
  73320. return result;
  73321. };
  73322. SSAO2RenderingPipeline.prototype._createSSAOPostProcess = function (ratio) {
  73323. var _this = this;
  73324. var numSamples = this.samples;
  73325. this._sampleSphere = this._generateHemisphere();
  73326. this._ssaoPostProcess = new BABYLON.PostProcess("ssao2", "ssao2", [
  73327. "sampleSphere", "samplesFactor", "randTextureTiles", "totalStrength", "radius",
  73328. "base", "range", "projection", "near", "far", "texelSize",
  73329. "xViewport", "yViewport", "maxZ", "minZAspect"
  73330. ], ["randomSampler", "normalSampler"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, "#define SAMPLES " + numSamples + "\n#define SSAO");
  73331. this._ssaoPostProcess.onApply = function (effect) {
  73332. if (_this._firstUpdate) {
  73333. effect.setArray3("sampleSphere", _this._sampleSphere);
  73334. effect.setFloat("randTextureTiles", 4.0);
  73335. }
  73336. if (!_this._scene.activeCamera) {
  73337. return;
  73338. }
  73339. effect.setFloat("samplesFactor", 1 / _this.samples);
  73340. effect.setFloat("totalStrength", _this.totalStrength);
  73341. effect.setFloat2("texelSize", 1 / _this._ssaoPostProcess.width, 1 / _this._ssaoPostProcess.height);
  73342. effect.setFloat("radius", _this.radius);
  73343. effect.setFloat("maxZ", _this.maxZ);
  73344. effect.setFloat("minZAspect", _this.minZAspect);
  73345. effect.setFloat("base", _this.base);
  73346. effect.setFloat("near", _this._scene.activeCamera.minZ);
  73347. effect.setFloat("far", _this._scene.activeCamera.maxZ);
  73348. effect.setFloat("xViewport", Math.tan(_this._scene.activeCamera.fov / 2) * _this._scene.getEngine().getAspectRatio(_this._scene.activeCamera, true));
  73349. effect.setFloat("yViewport", Math.tan(_this._scene.activeCamera.fov / 2));
  73350. effect.setMatrix("projection", _this._scene.getProjectionMatrix());
  73351. effect.setTexture("textureSampler", _this._depthTexture);
  73352. effect.setTexture("normalSampler", _this._normalTexture);
  73353. effect.setTexture("randomSampler", _this._randomTexture);
  73354. };
  73355. };
  73356. SSAO2RenderingPipeline.prototype._createSSAOCombinePostProcess = function (ratio) {
  73357. var _this = this;
  73358. this._ssaoCombinePostProcess = new BABYLON.PostProcess("ssaoCombine", "ssaoCombine", [], ["originalColor"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  73359. this._ssaoCombinePostProcess.onApply = function (effect) {
  73360. effect.setTextureFromPostProcess("originalColor", _this._originalColorPostProcess);
  73361. };
  73362. };
  73363. SSAO2RenderingPipeline.prototype._createRandomTexture = function () {
  73364. var size = 512;
  73365. this._randomTexture = new BABYLON.DynamicTexture("SSAORandomTexture", size, this._scene, false, BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  73366. this._randomTexture.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  73367. this._randomTexture.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  73368. var context = this._randomTexture.getContext();
  73369. var rand = function (min, max) {
  73370. return Math.random() * (max - min) + min;
  73371. };
  73372. var randVector = BABYLON.Vector3.Zero();
  73373. for (var x = 0; x < size; x++) {
  73374. for (var y = 0; y < size; y++) {
  73375. randVector.x = rand(0.0, 1.0);
  73376. randVector.y = rand(0.0, 1.0);
  73377. randVector.z = 0.0;
  73378. randVector.normalize();
  73379. randVector.scaleInPlace(255);
  73380. randVector.x = Math.floor(randVector.x);
  73381. randVector.y = Math.floor(randVector.y);
  73382. context.fillStyle = 'rgb(' + randVector.x + ', ' + randVector.y + ', ' + randVector.z + ')';
  73383. context.fillRect(x, y, 1, 1);
  73384. }
  73385. }
  73386. this._randomTexture.update(false);
  73387. };
  73388. __decorate([
  73389. BABYLON.serialize()
  73390. ], SSAO2RenderingPipeline.prototype, "totalStrength", void 0);
  73391. __decorate([
  73392. BABYLON.serialize()
  73393. ], SSAO2RenderingPipeline.prototype, "maxZ", void 0);
  73394. __decorate([
  73395. BABYLON.serialize()
  73396. ], SSAO2RenderingPipeline.prototype, "minZAspect", void 0);
  73397. __decorate([
  73398. BABYLON.serialize("samples")
  73399. ], SSAO2RenderingPipeline.prototype, "_samples", void 0);
  73400. __decorate([
  73401. BABYLON.serialize("expensiveBlur")
  73402. ], SSAO2RenderingPipeline.prototype, "_expensiveBlur", void 0);
  73403. __decorate([
  73404. BABYLON.serialize()
  73405. ], SSAO2RenderingPipeline.prototype, "radius", void 0);
  73406. __decorate([
  73407. BABYLON.serialize()
  73408. ], SSAO2RenderingPipeline.prototype, "base", void 0);
  73409. return SSAO2RenderingPipeline;
  73410. }(BABYLON.PostProcessRenderPipeline));
  73411. BABYLON.SSAO2RenderingPipeline = SSAO2RenderingPipeline;
  73412. })(BABYLON || (BABYLON = {}));
  73413. //# sourceMappingURL=babylon.ssao2RenderingPipeline.js.map
  73414. // BABYLON.JS Chromatic Aberration GLSL Shader
  73415. // Author: Olivier Guyot
  73416. // Separates very slightly R, G and B colors on the edges of the screen
  73417. // Inspired by Francois Tarlier & Martins Upitis
  73418. var BABYLON;
  73419. (function (BABYLON) {
  73420. var LensRenderingPipeline = /** @class */ (function (_super) {
  73421. __extends(LensRenderingPipeline, _super);
  73422. /**
  73423. * @constructor
  73424. *
  73425. * Effect parameters are as follow:
  73426. * {
  73427. * chromatic_aberration: number; // from 0 to x (1 for realism)
  73428. * edge_blur: number; // from 0 to x (1 for realism)
  73429. * distortion: number; // from 0 to x (1 for realism)
  73430. * grain_amount: number; // from 0 to 1
  73431. * grain_texture: BABYLON.Texture; // texture to use for grain effect; if unset, use random B&W noise
  73432. * dof_focus_distance: number; // depth-of-field: focus distance; unset to disable (disabled by default)
  73433. * dof_aperture: number; // depth-of-field: focus blur bias (default: 1)
  73434. * dof_darken: number; // depth-of-field: darken that which is out of focus (from 0 to 1, disabled by default)
  73435. * dof_pentagon: boolean; // depth-of-field: makes a pentagon-like "bokeh" effect
  73436. * dof_gain: number; // depth-of-field: highlights gain; unset to disable (disabled by default)
  73437. * dof_threshold: number; // depth-of-field: highlights threshold (default: 1)
  73438. * blur_noise: boolean; // add a little bit of noise to the blur (default: true)
  73439. * }
  73440. * Note: if an effect parameter is unset, effect is disabled
  73441. *
  73442. * @param {string} name - The rendering pipeline name
  73443. * @param {object} parameters - An object containing all parameters (see above)
  73444. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  73445. * @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)
  73446. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  73447. */
  73448. function LensRenderingPipeline(name, parameters, scene, ratio, cameras) {
  73449. if (ratio === void 0) { ratio = 1.0; }
  73450. var _this = _super.call(this, scene.getEngine(), name) || this;
  73451. // Lens effects can be of the following:
  73452. // - chromatic aberration (slight shift of RGB colors)
  73453. // - blur on the edge of the lens
  73454. // - lens distortion
  73455. // - depth-of-field blur & highlights enhancing
  73456. // - depth-of-field 'bokeh' effect (shapes appearing in blurred areas)
  73457. // - grain effect (noise or custom texture)
  73458. // Two additional texture samplers are needed:
  73459. // - depth map (for depth-of-field)
  73460. // - grain texture
  73461. /**
  73462. * The chromatic aberration PostProcess id in the pipeline
  73463. */
  73464. _this.LensChromaticAberrationEffect = "LensChromaticAberrationEffect";
  73465. /**
  73466. * The highlights enhancing PostProcess id in the pipeline
  73467. */
  73468. _this.HighlightsEnhancingEffect = "HighlightsEnhancingEffect";
  73469. /**
  73470. * The depth-of-field PostProcess id in the pipeline
  73471. */
  73472. _this.LensDepthOfFieldEffect = "LensDepthOfFieldEffect";
  73473. _this._scene = scene;
  73474. // Fetch texture samplers
  73475. _this._depthTexture = scene.enableDepthRenderer().getDepthMap(); // Force depth renderer "on"
  73476. if (parameters.grain_texture) {
  73477. _this._grainTexture = parameters.grain_texture;
  73478. }
  73479. else {
  73480. _this._createGrainTexture();
  73481. }
  73482. // save parameters
  73483. _this._edgeBlur = parameters.edge_blur ? parameters.edge_blur : 0;
  73484. _this._grainAmount = parameters.grain_amount ? parameters.grain_amount : 0;
  73485. _this._chromaticAberration = parameters.chromatic_aberration ? parameters.chromatic_aberration : 0;
  73486. _this._distortion = parameters.distortion ? parameters.distortion : 0;
  73487. _this._highlightsGain = parameters.dof_gain !== undefined ? parameters.dof_gain : -1;
  73488. _this._highlightsThreshold = parameters.dof_threshold ? parameters.dof_threshold : 1;
  73489. _this._dofDistance = parameters.dof_focus_distance !== undefined ? parameters.dof_focus_distance : -1;
  73490. _this._dofAperture = parameters.dof_aperture ? parameters.dof_aperture : 1;
  73491. _this._dofDarken = parameters.dof_darken ? parameters.dof_darken : 0;
  73492. _this._dofPentagon = parameters.dof_pentagon !== undefined ? parameters.dof_pentagon : true;
  73493. _this._blurNoise = parameters.blur_noise !== undefined ? parameters.blur_noise : true;
  73494. // Create effects
  73495. _this._createChromaticAberrationPostProcess(ratio);
  73496. _this._createHighlightsPostProcess(ratio);
  73497. _this._createDepthOfFieldPostProcess(ratio / 4);
  73498. // Set up pipeline
  73499. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.LensChromaticAberrationEffect, function () { return _this._chromaticAberrationPostProcess; }, true));
  73500. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.HighlightsEnhancingEffect, function () { return _this._highlightsPostProcess; }, true));
  73501. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.LensDepthOfFieldEffect, function () { return _this._depthOfFieldPostProcess; }, true));
  73502. if (_this._highlightsGain === -1) {
  73503. _this._disableEffect(_this.HighlightsEnhancingEffect, null);
  73504. }
  73505. // Finish
  73506. scene.postProcessRenderPipelineManager.addPipeline(_this);
  73507. if (cameras) {
  73508. scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(name, cameras);
  73509. }
  73510. return _this;
  73511. }
  73512. // public methods (self explanatory)
  73513. LensRenderingPipeline.prototype.setEdgeBlur = function (amount) { this._edgeBlur = amount; };
  73514. LensRenderingPipeline.prototype.disableEdgeBlur = function () { this._edgeBlur = 0; };
  73515. LensRenderingPipeline.prototype.setGrainAmount = function (amount) { this._grainAmount = amount; };
  73516. LensRenderingPipeline.prototype.disableGrain = function () { this._grainAmount = 0; };
  73517. LensRenderingPipeline.prototype.setChromaticAberration = function (amount) { this._chromaticAberration = amount; };
  73518. LensRenderingPipeline.prototype.disableChromaticAberration = function () { this._chromaticAberration = 0; };
  73519. LensRenderingPipeline.prototype.setEdgeDistortion = function (amount) { this._distortion = amount; };
  73520. LensRenderingPipeline.prototype.disableEdgeDistortion = function () { this._distortion = 0; };
  73521. LensRenderingPipeline.prototype.setFocusDistance = function (amount) { this._dofDistance = amount; };
  73522. LensRenderingPipeline.prototype.disableDepthOfField = function () { this._dofDistance = -1; };
  73523. LensRenderingPipeline.prototype.setAperture = function (amount) { this._dofAperture = amount; };
  73524. LensRenderingPipeline.prototype.setDarkenOutOfFocus = function (amount) { this._dofDarken = amount; };
  73525. LensRenderingPipeline.prototype.enablePentagonBokeh = function () {
  73526. this._highlightsPostProcess.updateEffect("#define PENTAGON\n");
  73527. };
  73528. LensRenderingPipeline.prototype.disablePentagonBokeh = function () {
  73529. this._highlightsPostProcess.updateEffect();
  73530. };
  73531. LensRenderingPipeline.prototype.enableNoiseBlur = function () { this._blurNoise = true; };
  73532. LensRenderingPipeline.prototype.disableNoiseBlur = function () { this._blurNoise = false; };
  73533. LensRenderingPipeline.prototype.setHighlightsGain = function (amount) {
  73534. this._highlightsGain = amount;
  73535. };
  73536. LensRenderingPipeline.prototype.setHighlightsThreshold = function (amount) {
  73537. if (this._highlightsGain === -1) {
  73538. this._highlightsGain = 1.0;
  73539. }
  73540. this._highlightsThreshold = amount;
  73541. };
  73542. LensRenderingPipeline.prototype.disableHighlights = function () {
  73543. this._highlightsGain = -1;
  73544. };
  73545. /**
  73546. * Removes the internal pipeline assets and detaches the pipeline from the scene cameras
  73547. */
  73548. LensRenderingPipeline.prototype.dispose = function (disableDepthRender) {
  73549. if (disableDepthRender === void 0) { disableDepthRender = false; }
  73550. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._scene.cameras);
  73551. this._chromaticAberrationPostProcess = null;
  73552. this._highlightsPostProcess = null;
  73553. this._depthOfFieldPostProcess = null;
  73554. this._grainTexture.dispose();
  73555. if (disableDepthRender)
  73556. this._scene.disableDepthRenderer();
  73557. };
  73558. // colors shifting and distortion
  73559. LensRenderingPipeline.prototype._createChromaticAberrationPostProcess = function (ratio) {
  73560. var _this = this;
  73561. this._chromaticAberrationPostProcess = new BABYLON.PostProcess("LensChromaticAberration", "chromaticAberration", ["chromatic_aberration", "screen_width", "screen_height", "direction", "radialIntensity", "centerPosition"], // uniforms
  73562. [], // samplers
  73563. ratio, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  73564. this._chromaticAberrationPostProcess.onApply = function (effect) {
  73565. effect.setFloat('chromatic_aberration', _this._chromaticAberration);
  73566. effect.setFloat('screen_width', _this._scene.getEngine().getRenderWidth());
  73567. effect.setFloat('screen_height', _this._scene.getEngine().getRenderHeight());
  73568. effect.setFloat('radialIntensity', 1);
  73569. effect.setFloat2('direction', 17, 17);
  73570. effect.setFloat2('centerPosition', 0.5, 0.5);
  73571. };
  73572. };
  73573. // highlights enhancing
  73574. LensRenderingPipeline.prototype._createHighlightsPostProcess = function (ratio) {
  73575. var _this = this;
  73576. this._highlightsPostProcess = new BABYLON.PostProcess("LensHighlights", "lensHighlights", ["gain", "threshold", "screen_width", "screen_height"], // uniforms
  73577. [], // samplers
  73578. ratio, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, this._dofPentagon ? "#define PENTAGON\n" : "");
  73579. this._highlightsPostProcess.onApply = function (effect) {
  73580. effect.setFloat('gain', _this._highlightsGain);
  73581. effect.setFloat('threshold', _this._highlightsThreshold);
  73582. effect.setTextureFromPostProcess("textureSampler", _this._chromaticAberrationPostProcess);
  73583. effect.setFloat('screen_width', _this._scene.getEngine().getRenderWidth());
  73584. effect.setFloat('screen_height', _this._scene.getEngine().getRenderHeight());
  73585. };
  73586. };
  73587. // colors shifting and distortion
  73588. LensRenderingPipeline.prototype._createDepthOfFieldPostProcess = function (ratio) {
  73589. var _this = this;
  73590. this._depthOfFieldPostProcess = new BABYLON.PostProcess("LensDepthOfField", "depthOfField", [
  73591. "grain_amount", "blur_noise", "screen_width", "screen_height", "distortion", "dof_enabled",
  73592. "screen_distance", "aperture", "darken", "edge_blur", "highlights", "near", "far"
  73593. ], ["depthSampler", "grainSampler", "highlightsSampler"], ratio, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  73594. this._depthOfFieldPostProcess.onApply = function (effect) {
  73595. effect.setTexture("depthSampler", _this._depthTexture);
  73596. effect.setTexture("grainSampler", _this._grainTexture);
  73597. effect.setTextureFromPostProcess("textureSampler", _this._highlightsPostProcess);
  73598. effect.setTextureFromPostProcess("highlightsSampler", _this._depthOfFieldPostProcess);
  73599. effect.setFloat('grain_amount', _this._grainAmount);
  73600. effect.setBool('blur_noise', _this._blurNoise);
  73601. effect.setFloat('screen_width', _this._scene.getEngine().getRenderWidth());
  73602. effect.setFloat('screen_height', _this._scene.getEngine().getRenderHeight());
  73603. effect.setFloat('distortion', _this._distortion);
  73604. effect.setBool('dof_enabled', (_this._dofDistance !== -1));
  73605. effect.setFloat('screen_distance', 1.0 / (0.1 - 1.0 / _this._dofDistance));
  73606. effect.setFloat('aperture', _this._dofAperture);
  73607. effect.setFloat('darken', _this._dofDarken);
  73608. effect.setFloat('edge_blur', _this._edgeBlur);
  73609. effect.setBool('highlights', (_this._highlightsGain !== -1));
  73610. if (_this._scene.activeCamera) {
  73611. effect.setFloat('near', _this._scene.activeCamera.minZ);
  73612. effect.setFloat('far', _this._scene.activeCamera.maxZ);
  73613. }
  73614. };
  73615. };
  73616. // creates a black and white random noise texture, 512x512
  73617. LensRenderingPipeline.prototype._createGrainTexture = function () {
  73618. var size = 512;
  73619. this._grainTexture = new BABYLON.DynamicTexture("LensNoiseTexture", size, this._scene, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  73620. this._grainTexture.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  73621. this._grainTexture.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  73622. var context = this._grainTexture.getContext();
  73623. var rand = function (min, max) {
  73624. return Math.random() * (max - min) + min;
  73625. };
  73626. var value;
  73627. for (var x = 0; x < size; x++) {
  73628. for (var y = 0; y < size; y++) {
  73629. value = Math.floor(rand(0.42, 0.58) * 255);
  73630. context.fillStyle = 'rgb(' + value + ', ' + value + ', ' + value + ')';
  73631. context.fillRect(x, y, 1, 1);
  73632. }
  73633. }
  73634. this._grainTexture.update(false);
  73635. };
  73636. return LensRenderingPipeline;
  73637. }(BABYLON.PostProcessRenderPipeline));
  73638. BABYLON.LensRenderingPipeline = LensRenderingPipeline;
  73639. })(BABYLON || (BABYLON = {}));
  73640. //# sourceMappingURL=babylon.lensRenderingPipeline.js.map
  73641. var BABYLON;
  73642. (function (BABYLON) {
  73643. var StandardRenderingPipeline = /** @class */ (function (_super) {
  73644. __extends(StandardRenderingPipeline, _super);
  73645. /**
  73646. * @constructor
  73647. * @param {string} name - The rendering pipeline name
  73648. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  73649. * @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)
  73650. * @param {BABYLON.PostProcess} originalPostProcess - the custom original color post-process. Must be "reusable". Can be null.
  73651. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  73652. */
  73653. function StandardRenderingPipeline(name, scene, ratio, originalPostProcess, cameras) {
  73654. if (originalPostProcess === void 0) { originalPostProcess = null; }
  73655. var _this = _super.call(this, scene.getEngine(), name) || this;
  73656. _this.downSampleX4PostProcess = null;
  73657. _this.brightPassPostProcess = null;
  73658. _this.blurHPostProcesses = [];
  73659. _this.blurVPostProcesses = [];
  73660. _this.textureAdderPostProcess = null;
  73661. _this.volumetricLightPostProcess = null;
  73662. _this.volumetricLightSmoothXPostProcess = null;
  73663. _this.volumetricLightSmoothYPostProcess = null;
  73664. _this.volumetricLightMergePostProces = null;
  73665. _this.volumetricLightFinalPostProcess = null;
  73666. _this.luminancePostProcess = null;
  73667. _this.luminanceDownSamplePostProcesses = [];
  73668. _this.hdrPostProcess = null;
  73669. _this.textureAdderFinalPostProcess = null;
  73670. _this.lensFlareFinalPostProcess = null;
  73671. _this.hdrFinalPostProcess = null;
  73672. _this.lensFlarePostProcess = null;
  73673. _this.lensFlareComposePostProcess = null;
  73674. _this.motionBlurPostProcess = null;
  73675. _this.depthOfFieldPostProcess = null;
  73676. // Values
  73677. _this.brightThreshold = 1.0;
  73678. _this.blurWidth = 512.0;
  73679. _this.horizontalBlur = false;
  73680. _this.exposure = 1.0;
  73681. _this.lensTexture = null;
  73682. _this.volumetricLightCoefficient = 0.2;
  73683. _this.volumetricLightPower = 4.0;
  73684. _this.volumetricLightBlurScale = 64.0;
  73685. _this.sourceLight = null;
  73686. _this.hdrMinimumLuminance = 1.0;
  73687. _this.hdrDecreaseRate = 0.5;
  73688. _this.hdrIncreaseRate = 0.5;
  73689. _this.lensColorTexture = null;
  73690. _this.lensFlareStrength = 20.0;
  73691. _this.lensFlareGhostDispersal = 1.4;
  73692. _this.lensFlareHaloWidth = 0.7;
  73693. _this.lensFlareDistortionStrength = 16.0;
  73694. _this.lensStarTexture = null;
  73695. _this.lensFlareDirtTexture = null;
  73696. _this.depthOfFieldDistance = 10.0;
  73697. _this.depthOfFieldBlurWidth = 64.0;
  73698. _this.motionStrength = 1.0;
  73699. // IAnimatable
  73700. _this.animations = [];
  73701. _this._currentDepthOfFieldSource = null;
  73702. _this._hdrCurrentLuminance = 1.0;
  73703. // Getters and setters
  73704. _this._bloomEnabled = true;
  73705. _this._depthOfFieldEnabled = false;
  73706. _this._vlsEnabled = false;
  73707. _this._lensFlareEnabled = false;
  73708. _this._hdrEnabled = false;
  73709. _this._motionBlurEnabled = false;
  73710. _this._motionBlurSamples = 64.0;
  73711. _this._volumetricLightStepsCount = 50.0;
  73712. _this._cameras = cameras || [];
  73713. // Initialize
  73714. _this._scene = scene;
  73715. _this._basePostProcess = originalPostProcess;
  73716. _this._ratio = ratio;
  73717. // Misc
  73718. _this._floatTextureType = scene.getEngine().getCaps().textureFloatRender ? BABYLON.Engine.TEXTURETYPE_FLOAT : BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  73719. // Finish
  73720. scene.postProcessRenderPipelineManager.addPipeline(_this);
  73721. _this._buildPipeline();
  73722. return _this;
  73723. }
  73724. Object.defineProperty(StandardRenderingPipeline.prototype, "BloomEnabled", {
  73725. get: function () {
  73726. return this._bloomEnabled;
  73727. },
  73728. set: function (enabled) {
  73729. if (this._bloomEnabled === enabled) {
  73730. return;
  73731. }
  73732. this._bloomEnabled = enabled;
  73733. this._buildPipeline();
  73734. },
  73735. enumerable: true,
  73736. configurable: true
  73737. });
  73738. Object.defineProperty(StandardRenderingPipeline.prototype, "DepthOfFieldEnabled", {
  73739. get: function () {
  73740. return this._depthOfFieldEnabled;
  73741. },
  73742. set: function (enabled) {
  73743. if (this._depthOfFieldEnabled === enabled) {
  73744. return;
  73745. }
  73746. this._depthOfFieldEnabled = enabled;
  73747. this._buildPipeline();
  73748. },
  73749. enumerable: true,
  73750. configurable: true
  73751. });
  73752. Object.defineProperty(StandardRenderingPipeline.prototype, "LensFlareEnabled", {
  73753. get: function () {
  73754. return this._lensFlareEnabled;
  73755. },
  73756. set: function (enabled) {
  73757. if (this._lensFlareEnabled === enabled) {
  73758. return;
  73759. }
  73760. this._lensFlareEnabled = enabled;
  73761. this._buildPipeline();
  73762. },
  73763. enumerable: true,
  73764. configurable: true
  73765. });
  73766. Object.defineProperty(StandardRenderingPipeline.prototype, "HDREnabled", {
  73767. get: function () {
  73768. return this._hdrEnabled;
  73769. },
  73770. set: function (enabled) {
  73771. if (this._hdrEnabled === enabled) {
  73772. return;
  73773. }
  73774. this._hdrEnabled = enabled;
  73775. this._buildPipeline();
  73776. },
  73777. enumerable: true,
  73778. configurable: true
  73779. });
  73780. Object.defineProperty(StandardRenderingPipeline.prototype, "VLSEnabled", {
  73781. get: function () {
  73782. return this._vlsEnabled;
  73783. },
  73784. set: function (enabled) {
  73785. if (this._vlsEnabled === enabled) {
  73786. return;
  73787. }
  73788. if (enabled) {
  73789. var geometry = this._scene.enableGeometryBufferRenderer();
  73790. if (!geometry) {
  73791. BABYLON.Tools.Warn("Geometry renderer is not supported, cannot create volumetric lights in Standard Rendering Pipeline");
  73792. return;
  73793. }
  73794. }
  73795. this._vlsEnabled = enabled;
  73796. this._buildPipeline();
  73797. },
  73798. enumerable: true,
  73799. configurable: true
  73800. });
  73801. Object.defineProperty(StandardRenderingPipeline.prototype, "MotionBlurEnabled", {
  73802. get: function () {
  73803. return this._motionBlurEnabled;
  73804. },
  73805. set: function (enabled) {
  73806. if (this._motionBlurEnabled === enabled) {
  73807. return;
  73808. }
  73809. this._motionBlurEnabled = enabled;
  73810. this._buildPipeline();
  73811. },
  73812. enumerable: true,
  73813. configurable: true
  73814. });
  73815. Object.defineProperty(StandardRenderingPipeline.prototype, "volumetricLightStepsCount", {
  73816. get: function () {
  73817. return this._volumetricLightStepsCount;
  73818. },
  73819. set: function (count) {
  73820. if (this.volumetricLightPostProcess) {
  73821. this.volumetricLightPostProcess.updateEffect("#define VLS\n#define NB_STEPS " + count.toFixed(1));
  73822. }
  73823. this._volumetricLightStepsCount = count;
  73824. },
  73825. enumerable: true,
  73826. configurable: true
  73827. });
  73828. Object.defineProperty(StandardRenderingPipeline.prototype, "motionBlurSamples", {
  73829. get: function () {
  73830. return this._motionBlurSamples;
  73831. },
  73832. set: function (samples) {
  73833. if (this.motionBlurPostProcess) {
  73834. this.motionBlurPostProcess.updateEffect("#define MOTION_BLUR\n#define MAX_MOTION_SAMPLES " + samples.toFixed(1));
  73835. }
  73836. this._motionBlurSamples = samples;
  73837. },
  73838. enumerable: true,
  73839. configurable: true
  73840. });
  73841. StandardRenderingPipeline.prototype._buildPipeline = function () {
  73842. var _this = this;
  73843. var ratio = this._ratio;
  73844. var scene = this._scene;
  73845. this._disposePostProcesses();
  73846. this._reset();
  73847. // Create pass post-process
  73848. if (!this._basePostProcess) {
  73849. this.originalPostProcess = new BABYLON.PostProcess("HDRPass", "standard", [], [], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define PASS_POST_PROCESS", this._floatTextureType);
  73850. this.originalPostProcess.onApply = function (effect) {
  73851. _this._currentDepthOfFieldSource = _this.originalPostProcess;
  73852. };
  73853. }
  73854. else {
  73855. this.originalPostProcess = this._basePostProcess;
  73856. }
  73857. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRPassPostProcess", function () { return _this.originalPostProcess; }, true));
  73858. this._currentDepthOfFieldSource = this.originalPostProcess;
  73859. if (this._vlsEnabled) {
  73860. // Create volumetric light
  73861. this._createVolumetricLightPostProcess(scene, ratio);
  73862. // Create volumetric light final post-process
  73863. 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);
  73864. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRVLSFinal", function () { return _this.volumetricLightFinalPostProcess; }, true));
  73865. }
  73866. if (this._bloomEnabled) {
  73867. // Create down sample X4 post-process
  73868. this._createDownSampleX4PostProcess(scene, ratio / 2);
  73869. // Create bright pass post-process
  73870. this._createBrightPassPostProcess(scene, ratio / 2);
  73871. // Create gaussian blur post-processes (down sampling blurs)
  73872. this._createBlurPostProcesses(scene, ratio / 4, 1);
  73873. // Create texture adder post-process
  73874. this._createTextureAdderPostProcess(scene, ratio);
  73875. // Create depth-of-field source post-process
  73876. 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);
  73877. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRBaseDepthOfFieldSource", function () { return _this.textureAdderFinalPostProcess; }, true));
  73878. }
  73879. if (this._lensFlareEnabled) {
  73880. // Create lens flare post-process
  73881. this._createLensFlarePostProcess(scene, ratio);
  73882. // Create depth-of-field source post-process post lens-flare and disable it now
  73883. 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);
  73884. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRPostLensFlareDepthOfFieldSource", function () { return _this.lensFlareFinalPostProcess; }, true));
  73885. }
  73886. if (this._hdrEnabled) {
  73887. // Create luminance
  73888. this._createLuminancePostProcesses(scene, this._floatTextureType);
  73889. // Create HDR
  73890. this._createHdrPostProcess(scene, ratio);
  73891. // Create depth-of-field source post-process post hdr and disable it now
  73892. 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);
  73893. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRPostHDReDepthOfFieldSource", function () { return _this.hdrFinalPostProcess; }, true));
  73894. }
  73895. if (this._depthOfFieldEnabled) {
  73896. // Create gaussian blur used by depth-of-field
  73897. this._createBlurPostProcesses(scene, ratio / 2, 3, "depthOfFieldBlurWidth");
  73898. // Create depth-of-field post-process
  73899. this._createDepthOfFieldPostProcess(scene, ratio);
  73900. }
  73901. if (this._motionBlurEnabled) {
  73902. // Create motion blur post-process
  73903. this._createMotionBlurPostProcess(scene, ratio);
  73904. }
  73905. if (this._cameras !== null) {
  73906. this._scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(this._name, this._cameras);
  73907. }
  73908. };
  73909. // Down Sample X4 Post-Processs
  73910. StandardRenderingPipeline.prototype._createDownSampleX4PostProcess = function (scene, ratio) {
  73911. var _this = this;
  73912. var downSampleX4Offsets = new Array(32);
  73913. 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);
  73914. this.downSampleX4PostProcess.onApply = function (effect) {
  73915. var id = 0;
  73916. var width = _this.downSampleX4PostProcess.width;
  73917. var height = _this.downSampleX4PostProcess.height;
  73918. for (var i = -2; i < 2; i++) {
  73919. for (var j = -2; j < 2; j++) {
  73920. downSampleX4Offsets[id] = (i + 0.5) * (1.0 / width);
  73921. downSampleX4Offsets[id + 1] = (j + 0.5) * (1.0 / height);
  73922. id += 2;
  73923. }
  73924. }
  73925. effect.setArray2("dsOffsets", downSampleX4Offsets);
  73926. };
  73927. // Add to pipeline
  73928. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRDownSampleX4", function () { return _this.downSampleX4PostProcess; }, true));
  73929. };
  73930. // Brightpass Post-Process
  73931. StandardRenderingPipeline.prototype._createBrightPassPostProcess = function (scene, ratio) {
  73932. var _this = this;
  73933. var brightOffsets = new Array(8);
  73934. 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);
  73935. this.brightPassPostProcess.onApply = function (effect) {
  73936. var sU = (1.0 / _this.brightPassPostProcess.width);
  73937. var sV = (1.0 / _this.brightPassPostProcess.height);
  73938. brightOffsets[0] = -0.5 * sU;
  73939. brightOffsets[1] = 0.5 * sV;
  73940. brightOffsets[2] = 0.5 * sU;
  73941. brightOffsets[3] = 0.5 * sV;
  73942. brightOffsets[4] = -0.5 * sU;
  73943. brightOffsets[5] = -0.5 * sV;
  73944. brightOffsets[6] = 0.5 * sU;
  73945. brightOffsets[7] = -0.5 * sV;
  73946. effect.setArray2("dsOffsets", brightOffsets);
  73947. effect.setFloat("brightThreshold", _this.brightThreshold);
  73948. };
  73949. // Add to pipeline
  73950. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRBrightPass", function () { return _this.brightPassPostProcess; }, true));
  73951. };
  73952. // Create blur H&V post-processes
  73953. StandardRenderingPipeline.prototype._createBlurPostProcesses = function (scene, ratio, indice, blurWidthKey) {
  73954. var _this = this;
  73955. if (blurWidthKey === void 0) { blurWidthKey = "blurWidth"; }
  73956. var engine = scene.getEngine();
  73957. 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);
  73958. 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);
  73959. blurX.onActivateObservable.add(function () {
  73960. var dw = blurX.width / engine.getRenderWidth();
  73961. blurX.kernel = _this[blurWidthKey] * dw;
  73962. });
  73963. blurY.onActivateObservable.add(function () {
  73964. var dw = blurY.height / engine.getRenderHeight();
  73965. blurY.kernel = _this.horizontalBlur ? 64 * dw : _this[blurWidthKey] * dw;
  73966. });
  73967. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRBlurH" + indice, function () { return blurX; }, true));
  73968. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRBlurV" + indice, function () { return blurY; }, true));
  73969. this.blurHPostProcesses.push(blurX);
  73970. this.blurVPostProcesses.push(blurY);
  73971. };
  73972. // Create texture adder post-process
  73973. StandardRenderingPipeline.prototype._createTextureAdderPostProcess = function (scene, ratio) {
  73974. var _this = this;
  73975. 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);
  73976. this.textureAdderPostProcess.onApply = function (effect) {
  73977. effect.setTextureFromPostProcess("otherSampler", _this._vlsEnabled ? _this._currentDepthOfFieldSource : _this.originalPostProcess);
  73978. effect.setTexture("lensSampler", _this.lensTexture);
  73979. effect.setFloat("exposure", _this.exposure);
  73980. _this._currentDepthOfFieldSource = _this.textureAdderFinalPostProcess;
  73981. };
  73982. // Add to pipeline
  73983. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRTextureAdder", function () { return _this.textureAdderPostProcess; }, true));
  73984. };
  73985. StandardRenderingPipeline.prototype._createVolumetricLightPostProcess = function (scene, ratio) {
  73986. var _this = this;
  73987. var geometryRenderer = scene.enableGeometryBufferRenderer();
  73988. geometryRenderer.enablePosition = true;
  73989. var geometry = geometryRenderer.getGBuffer();
  73990. // Base post-process
  73991. 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));
  73992. var depthValues = BABYLON.Vector2.Zero();
  73993. this.volumetricLightPostProcess.onApply = function (effect) {
  73994. if (_this.sourceLight && _this.sourceLight.getShadowGenerator() && _this._scene.activeCamera) {
  73995. var generator = _this.sourceLight.getShadowGenerator();
  73996. effect.setTexture("shadowMapSampler", generator.getShadowMap());
  73997. effect.setTexture("positionSampler", geometry.textures[2]);
  73998. effect.setColor3("sunColor", _this.sourceLight.diffuse);
  73999. effect.setVector3("sunDirection", _this.sourceLight.getShadowDirection());
  74000. effect.setVector3("cameraPosition", _this._scene.activeCamera.globalPosition);
  74001. effect.setMatrix("shadowViewProjection", generator.getTransformMatrix());
  74002. effect.setFloat("scatteringCoefficient", _this.volumetricLightCoefficient);
  74003. effect.setFloat("scatteringPower", _this.volumetricLightPower);
  74004. depthValues.x = generator.getLight().getDepthMinZ(_this._scene.activeCamera);
  74005. depthValues.y = generator.getLight().getDepthMaxZ(_this._scene.activeCamera);
  74006. effect.setVector2("depthValues", depthValues);
  74007. }
  74008. };
  74009. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRVLS", function () { return _this.volumetricLightPostProcess; }, true));
  74010. // Smooth
  74011. this._createBlurPostProcesses(scene, ratio / 4, 0, "volumetricLightBlurScale");
  74012. // Merge
  74013. this.volumetricLightMergePostProces = new BABYLON.PostProcess("HDRVLSMerge", "standard", [], ["originalSampler"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define VLSMERGE");
  74014. this.volumetricLightMergePostProces.onApply = function (effect) {
  74015. effect.setTextureFromPostProcess("originalSampler", _this.originalPostProcess);
  74016. _this._currentDepthOfFieldSource = _this.volumetricLightFinalPostProcess;
  74017. };
  74018. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRVLSMerge", function () { return _this.volumetricLightMergePostProces; }, true));
  74019. };
  74020. // Create luminance
  74021. StandardRenderingPipeline.prototype._createLuminancePostProcesses = function (scene, textureType) {
  74022. var _this = this;
  74023. // Create luminance
  74024. var size = Math.pow(3, StandardRenderingPipeline.LuminanceSteps);
  74025. this.luminancePostProcess = new BABYLON.PostProcess("HDRLuminance", "standard", ["lumOffsets"], [], { width: size, height: size }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define LUMINANCE", textureType);
  74026. var offsets = [];
  74027. this.luminancePostProcess.onApply = function (effect) {
  74028. var sU = (1.0 / _this.luminancePostProcess.width);
  74029. var sV = (1.0 / _this.luminancePostProcess.height);
  74030. offsets[0] = -0.5 * sU;
  74031. offsets[1] = 0.5 * sV;
  74032. offsets[2] = 0.5 * sU;
  74033. offsets[3] = 0.5 * sV;
  74034. offsets[4] = -0.5 * sU;
  74035. offsets[5] = -0.5 * sV;
  74036. offsets[6] = 0.5 * sU;
  74037. offsets[7] = -0.5 * sV;
  74038. effect.setArray2("lumOffsets", offsets);
  74039. };
  74040. // Add to pipeline
  74041. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRLuminance", function () { return _this.luminancePostProcess; }, true));
  74042. // Create down sample luminance
  74043. for (var i = StandardRenderingPipeline.LuminanceSteps - 1; i >= 0; i--) {
  74044. var size = Math.pow(3, i);
  74045. var defines = "#define LUMINANCE_DOWN_SAMPLE\n";
  74046. if (i === 0) {
  74047. defines += "#define FINAL_DOWN_SAMPLER";
  74048. }
  74049. var postProcess = new BABYLON.PostProcess("HDRLuminanceDownSample" + i, "standard", ["dsOffsets", "halfDestPixelSize"], [], { width: size, height: size }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, defines, textureType);
  74050. this.luminanceDownSamplePostProcesses.push(postProcess);
  74051. }
  74052. // Create callbacks and add effects
  74053. var lastLuminance = this.luminancePostProcess;
  74054. this.luminanceDownSamplePostProcesses.forEach(function (pp, index) {
  74055. var downSampleOffsets = new Array(18);
  74056. pp.onApply = function (effect) {
  74057. if (!lastLuminance) {
  74058. return;
  74059. }
  74060. var id = 0;
  74061. for (var x = -1; x < 2; x++) {
  74062. for (var y = -1; y < 2; y++) {
  74063. downSampleOffsets[id] = x / lastLuminance.width;
  74064. downSampleOffsets[id + 1] = y / lastLuminance.height;
  74065. id += 2;
  74066. }
  74067. }
  74068. effect.setArray2("dsOffsets", downSampleOffsets);
  74069. effect.setFloat("halfDestPixelSize", 0.5 / lastLuminance.width);
  74070. if (index === _this.luminanceDownSamplePostProcesses.length - 1) {
  74071. lastLuminance = _this.luminancePostProcess;
  74072. }
  74073. else {
  74074. lastLuminance = pp;
  74075. }
  74076. };
  74077. if (index === _this.luminanceDownSamplePostProcesses.length - 1) {
  74078. pp.onAfterRender = function (effect) {
  74079. var pixel = scene.getEngine().readPixels(0, 0, 1, 1);
  74080. 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);
  74081. _this._hdrCurrentLuminance = (pixel[0] * bit_shift.x + pixel[1] * bit_shift.y + pixel[2] * bit_shift.z + pixel[3] * bit_shift.w) / 100.0;
  74082. };
  74083. }
  74084. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRLuminanceDownSample" + index, function () { return pp; }, true));
  74085. });
  74086. };
  74087. // Create HDR post-process
  74088. StandardRenderingPipeline.prototype._createHdrPostProcess = function (scene, ratio) {
  74089. var _this = this;
  74090. 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);
  74091. var outputLiminance = 1;
  74092. var time = 0;
  74093. var lastTime = 0;
  74094. this.hdrPostProcess.onApply = function (effect) {
  74095. effect.setTextureFromPostProcess("textureAdderSampler", _this._currentDepthOfFieldSource);
  74096. time += scene.getEngine().getDeltaTime();
  74097. if (outputLiminance < 0) {
  74098. outputLiminance = _this._hdrCurrentLuminance;
  74099. }
  74100. else {
  74101. var dt = (lastTime - time) / 1000.0;
  74102. if (_this._hdrCurrentLuminance < outputLiminance + _this.hdrDecreaseRate * dt) {
  74103. outputLiminance += _this.hdrDecreaseRate * dt;
  74104. }
  74105. else if (_this._hdrCurrentLuminance > outputLiminance - _this.hdrIncreaseRate * dt) {
  74106. outputLiminance -= _this.hdrIncreaseRate * dt;
  74107. }
  74108. else {
  74109. outputLiminance = _this._hdrCurrentLuminance;
  74110. }
  74111. }
  74112. outputLiminance = BABYLON.Scalar.Clamp(outputLiminance, _this.hdrMinimumLuminance, 1e20);
  74113. effect.setFloat("averageLuminance", outputLiminance);
  74114. lastTime = time;
  74115. _this._currentDepthOfFieldSource = _this.hdrFinalPostProcess;
  74116. };
  74117. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDR", function () { return _this.hdrPostProcess; }, true));
  74118. };
  74119. // Create lens flare post-process
  74120. StandardRenderingPipeline.prototype._createLensFlarePostProcess = function (scene, ratio) {
  74121. var _this = this;
  74122. 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);
  74123. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRLensFlare", function () { return _this.lensFlarePostProcess; }, true));
  74124. this._createBlurPostProcesses(scene, ratio / 4, 2);
  74125. 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);
  74126. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRLensFlareCompose", function () { return _this.lensFlareComposePostProcess; }, true));
  74127. var resolution = new BABYLON.Vector2(0, 0);
  74128. // Lens flare
  74129. this.lensFlarePostProcess.onApply = function (effect) {
  74130. effect.setTextureFromPostProcess("textureSampler", _this._bloomEnabled ? _this.blurHPostProcesses[0] : _this.originalPostProcess);
  74131. effect.setTexture("lensColorSampler", _this.lensColorTexture);
  74132. effect.setFloat("strength", _this.lensFlareStrength);
  74133. effect.setFloat("ghostDispersal", _this.lensFlareGhostDispersal);
  74134. effect.setFloat("haloWidth", _this.lensFlareHaloWidth);
  74135. // Shift
  74136. resolution.x = _this.lensFlarePostProcess.width;
  74137. resolution.y = _this.lensFlarePostProcess.height;
  74138. effect.setVector2("resolution", resolution);
  74139. effect.setFloat("distortionStrength", _this.lensFlareDistortionStrength);
  74140. };
  74141. // Compose
  74142. 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);
  74143. 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);
  74144. this.lensFlareComposePostProcess.onApply = function (effect) {
  74145. if (!_this._scene.activeCamera) {
  74146. return;
  74147. }
  74148. effect.setTextureFromPostProcess("otherSampler", _this._currentDepthOfFieldSource);
  74149. effect.setTexture("lensDirtSampler", _this.lensFlareDirtTexture);
  74150. effect.setTexture("lensStarSampler", _this.lensStarTexture);
  74151. // Lens start rotation matrix
  74152. var camerax = _this._scene.activeCamera.getViewMatrix().getRow(0);
  74153. var cameraz = _this._scene.activeCamera.getViewMatrix().getRow(2);
  74154. 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));
  74155. camRot *= 4.0;
  74156. 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);
  74157. var lensStarMatrix = scaleBias2.multiply(starRotation).multiply(scaleBias1);
  74158. effect.setMatrix("lensStarMatrix", lensStarMatrix);
  74159. _this._currentDepthOfFieldSource = _this.lensFlareFinalPostProcess;
  74160. };
  74161. };
  74162. // Create depth-of-field post-process
  74163. StandardRenderingPipeline.prototype._createDepthOfFieldPostProcess = function (scene, ratio) {
  74164. var _this = this;
  74165. 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);
  74166. this.depthOfFieldPostProcess.onApply = function (effect) {
  74167. effect.setTextureFromPostProcess("otherSampler", _this._currentDepthOfFieldSource);
  74168. effect.setTexture("depthSampler", _this._getDepthTexture());
  74169. effect.setFloat("distance", _this.depthOfFieldDistance);
  74170. };
  74171. // Add to pipeline
  74172. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRDepthOfField", function () { return _this.depthOfFieldPostProcess; }, true));
  74173. };
  74174. // Create motion blur post-process
  74175. StandardRenderingPipeline.prototype._createMotionBlurPostProcess = function (scene, ratio) {
  74176. var _this = this;
  74177. 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);
  74178. var motionScale = 0;
  74179. var prevViewProjection = BABYLON.Matrix.Identity();
  74180. var invViewProjection = BABYLON.Matrix.Identity();
  74181. var viewProjection = BABYLON.Matrix.Identity();
  74182. var screenSize = BABYLON.Vector2.Zero();
  74183. this.motionBlurPostProcess.onApply = function (effect) {
  74184. viewProjection = scene.getProjectionMatrix().multiply(scene.getViewMatrix());
  74185. viewProjection.invertToRef(invViewProjection);
  74186. effect.setMatrix("inverseViewProjection", invViewProjection);
  74187. effect.setMatrix("prevViewProjection", prevViewProjection);
  74188. prevViewProjection = viewProjection;
  74189. screenSize.x = _this.motionBlurPostProcess.width;
  74190. screenSize.y = _this.motionBlurPostProcess.height;
  74191. effect.setVector2("screenSize", screenSize);
  74192. motionScale = scene.getEngine().getFps() / 60.0;
  74193. effect.setFloat("motionScale", motionScale);
  74194. effect.setFloat("motionStrength", _this.motionStrength);
  74195. effect.setTexture("depthSampler", _this._getDepthTexture());
  74196. };
  74197. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRMotionBlur", function () { return _this.motionBlurPostProcess; }, true));
  74198. };
  74199. StandardRenderingPipeline.prototype._getDepthTexture = function () {
  74200. if (this._scene.getEngine().getCaps().drawBuffersExtension) {
  74201. var renderer = this._scene.enableGeometryBufferRenderer();
  74202. return renderer.getGBuffer().textures[0];
  74203. }
  74204. return this._scene.enableDepthRenderer().getDepthMap();
  74205. };
  74206. StandardRenderingPipeline.prototype._disposePostProcesses = function () {
  74207. for (var i = 0; i < this._cameras.length; i++) {
  74208. var camera = this._cameras[i];
  74209. if (this.originalPostProcess) {
  74210. this.originalPostProcess.dispose(camera);
  74211. }
  74212. if (this.downSampleX4PostProcess) {
  74213. this.downSampleX4PostProcess.dispose(camera);
  74214. }
  74215. if (this.brightPassPostProcess) {
  74216. this.brightPassPostProcess.dispose(camera);
  74217. }
  74218. if (this.textureAdderPostProcess) {
  74219. this.textureAdderPostProcess.dispose(camera);
  74220. }
  74221. if (this.textureAdderFinalPostProcess) {
  74222. this.textureAdderFinalPostProcess.dispose(camera);
  74223. }
  74224. if (this.volumetricLightPostProcess) {
  74225. this.volumetricLightPostProcess.dispose(camera);
  74226. }
  74227. if (this.volumetricLightSmoothXPostProcess) {
  74228. this.volumetricLightSmoothXPostProcess.dispose(camera);
  74229. }
  74230. if (this.volumetricLightSmoothYPostProcess) {
  74231. this.volumetricLightSmoothYPostProcess.dispose(camera);
  74232. }
  74233. if (this.volumetricLightMergePostProces) {
  74234. this.volumetricLightMergePostProces.dispose(camera);
  74235. }
  74236. if (this.volumetricLightFinalPostProcess) {
  74237. this.volumetricLightFinalPostProcess.dispose(camera);
  74238. }
  74239. if (this.lensFlarePostProcess) {
  74240. this.lensFlarePostProcess.dispose(camera);
  74241. }
  74242. if (this.lensFlareComposePostProcess) {
  74243. this.lensFlareComposePostProcess.dispose(camera);
  74244. }
  74245. for (var j = 0; j < this.luminanceDownSamplePostProcesses.length; j++) {
  74246. this.luminanceDownSamplePostProcesses[j].dispose(camera);
  74247. }
  74248. if (this.luminancePostProcess) {
  74249. this.luminancePostProcess.dispose(camera);
  74250. }
  74251. if (this.hdrPostProcess) {
  74252. this.hdrPostProcess.dispose(camera);
  74253. }
  74254. if (this.hdrFinalPostProcess) {
  74255. this.hdrFinalPostProcess.dispose(camera);
  74256. }
  74257. if (this.depthOfFieldPostProcess) {
  74258. this.depthOfFieldPostProcess.dispose(camera);
  74259. }
  74260. if (this.motionBlurPostProcess) {
  74261. this.motionBlurPostProcess.dispose(camera);
  74262. }
  74263. for (var j = 0; j < this.blurHPostProcesses.length; j++) {
  74264. this.blurHPostProcesses[j].dispose(camera);
  74265. }
  74266. for (var j = 0; j < this.blurVPostProcesses.length; j++) {
  74267. this.blurVPostProcesses[j].dispose(camera);
  74268. }
  74269. }
  74270. this.originalPostProcess = null;
  74271. this.downSampleX4PostProcess = null;
  74272. this.brightPassPostProcess = null;
  74273. this.textureAdderPostProcess = null;
  74274. this.textureAdderFinalPostProcess = null;
  74275. this.volumetricLightPostProcess = null;
  74276. this.volumetricLightSmoothXPostProcess = null;
  74277. this.volumetricLightSmoothYPostProcess = null;
  74278. this.volumetricLightMergePostProces = null;
  74279. this.volumetricLightFinalPostProcess = null;
  74280. this.lensFlarePostProcess = null;
  74281. this.lensFlareComposePostProcess = null;
  74282. this.luminancePostProcess = null;
  74283. this.hdrPostProcess = null;
  74284. this.hdrFinalPostProcess = null;
  74285. this.depthOfFieldPostProcess = null;
  74286. this.motionBlurPostProcess = null;
  74287. this.luminanceDownSamplePostProcesses = [];
  74288. this.blurHPostProcesses = [];
  74289. this.blurVPostProcesses = [];
  74290. };
  74291. // Dispose
  74292. StandardRenderingPipeline.prototype.dispose = function () {
  74293. this._disposePostProcesses();
  74294. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._cameras);
  74295. _super.prototype.dispose.call(this);
  74296. };
  74297. // Serialize rendering pipeline
  74298. StandardRenderingPipeline.prototype.serialize = function () {
  74299. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  74300. serializationObject.customType = "StandardRenderingPipeline";
  74301. return serializationObject;
  74302. };
  74303. /**
  74304. * Static members
  74305. */
  74306. // Parse serialized pipeline
  74307. StandardRenderingPipeline.Parse = function (source, scene, rootUrl) {
  74308. return BABYLON.SerializationHelper.Parse(function () { return new StandardRenderingPipeline(source._name, scene, source._ratio); }, source, scene, rootUrl);
  74309. };
  74310. // Luminance steps
  74311. StandardRenderingPipeline.LuminanceSteps = 6;
  74312. __decorate([
  74313. BABYLON.serialize()
  74314. ], StandardRenderingPipeline.prototype, "brightThreshold", void 0);
  74315. __decorate([
  74316. BABYLON.serialize()
  74317. ], StandardRenderingPipeline.prototype, "blurWidth", void 0);
  74318. __decorate([
  74319. BABYLON.serialize()
  74320. ], StandardRenderingPipeline.prototype, "horizontalBlur", void 0);
  74321. __decorate([
  74322. BABYLON.serialize()
  74323. ], StandardRenderingPipeline.prototype, "exposure", void 0);
  74324. __decorate([
  74325. BABYLON.serializeAsTexture("lensTexture")
  74326. ], StandardRenderingPipeline.prototype, "lensTexture", void 0);
  74327. __decorate([
  74328. BABYLON.serialize()
  74329. ], StandardRenderingPipeline.prototype, "volumetricLightCoefficient", void 0);
  74330. __decorate([
  74331. BABYLON.serialize()
  74332. ], StandardRenderingPipeline.prototype, "volumetricLightPower", void 0);
  74333. __decorate([
  74334. BABYLON.serialize()
  74335. ], StandardRenderingPipeline.prototype, "volumetricLightBlurScale", void 0);
  74336. __decorate([
  74337. BABYLON.serialize()
  74338. ], StandardRenderingPipeline.prototype, "hdrMinimumLuminance", void 0);
  74339. __decorate([
  74340. BABYLON.serialize()
  74341. ], StandardRenderingPipeline.prototype, "hdrDecreaseRate", void 0);
  74342. __decorate([
  74343. BABYLON.serialize()
  74344. ], StandardRenderingPipeline.prototype, "hdrIncreaseRate", void 0);
  74345. __decorate([
  74346. BABYLON.serializeAsTexture("lensColorTexture")
  74347. ], StandardRenderingPipeline.prototype, "lensColorTexture", void 0);
  74348. __decorate([
  74349. BABYLON.serialize()
  74350. ], StandardRenderingPipeline.prototype, "lensFlareStrength", void 0);
  74351. __decorate([
  74352. BABYLON.serialize()
  74353. ], StandardRenderingPipeline.prototype, "lensFlareGhostDispersal", void 0);
  74354. __decorate([
  74355. BABYLON.serialize()
  74356. ], StandardRenderingPipeline.prototype, "lensFlareHaloWidth", void 0);
  74357. __decorate([
  74358. BABYLON.serialize()
  74359. ], StandardRenderingPipeline.prototype, "lensFlareDistortionStrength", void 0);
  74360. __decorate([
  74361. BABYLON.serializeAsTexture("lensStarTexture")
  74362. ], StandardRenderingPipeline.prototype, "lensStarTexture", void 0);
  74363. __decorate([
  74364. BABYLON.serializeAsTexture("lensFlareDirtTexture")
  74365. ], StandardRenderingPipeline.prototype, "lensFlareDirtTexture", void 0);
  74366. __decorate([
  74367. BABYLON.serialize()
  74368. ], StandardRenderingPipeline.prototype, "depthOfFieldDistance", void 0);
  74369. __decorate([
  74370. BABYLON.serialize()
  74371. ], StandardRenderingPipeline.prototype, "depthOfFieldBlurWidth", void 0);
  74372. __decorate([
  74373. BABYLON.serialize()
  74374. ], StandardRenderingPipeline.prototype, "motionStrength", void 0);
  74375. __decorate([
  74376. BABYLON.serialize()
  74377. ], StandardRenderingPipeline.prototype, "_ratio", void 0);
  74378. __decorate([
  74379. BABYLON.serialize()
  74380. ], StandardRenderingPipeline.prototype, "BloomEnabled", null);
  74381. __decorate([
  74382. BABYLON.serialize()
  74383. ], StandardRenderingPipeline.prototype, "DepthOfFieldEnabled", null);
  74384. __decorate([
  74385. BABYLON.serialize()
  74386. ], StandardRenderingPipeline.prototype, "LensFlareEnabled", null);
  74387. __decorate([
  74388. BABYLON.serialize()
  74389. ], StandardRenderingPipeline.prototype, "HDREnabled", null);
  74390. __decorate([
  74391. BABYLON.serialize()
  74392. ], StandardRenderingPipeline.prototype, "VLSEnabled", null);
  74393. __decorate([
  74394. BABYLON.serialize()
  74395. ], StandardRenderingPipeline.prototype, "MotionBlurEnabled", null);
  74396. __decorate([
  74397. BABYLON.serialize()
  74398. ], StandardRenderingPipeline.prototype, "volumetricLightStepsCount", null);
  74399. __decorate([
  74400. BABYLON.serialize()
  74401. ], StandardRenderingPipeline.prototype, "motionBlurSamples", null);
  74402. return StandardRenderingPipeline;
  74403. }(BABYLON.PostProcessRenderPipeline));
  74404. BABYLON.StandardRenderingPipeline = StandardRenderingPipeline;
  74405. })(BABYLON || (BABYLON = {}));
  74406. //# sourceMappingURL=babylon.standardRenderingPipeline.js.map
  74407. var BABYLON;
  74408. (function (BABYLON) {
  74409. var FxaaPostProcess = /** @class */ (function (_super) {
  74410. __extends(FxaaPostProcess, _super);
  74411. function FxaaPostProcess(name, options, camera, samplingMode, engine, reusable, textureType) {
  74412. if (camera === void 0) { camera = null; }
  74413. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  74414. var _this = _super.call(this, name, "fxaa", ["texelSize"], null, options, camera, samplingMode || BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, reusable, null, textureType, "fxaa") || this;
  74415. _this.onApplyObservable.add(function (effect) {
  74416. var texelSize = _this.texelSize;
  74417. effect.setFloat2("texelSize", texelSize.x, texelSize.y);
  74418. });
  74419. return _this;
  74420. }
  74421. return FxaaPostProcess;
  74422. }(BABYLON.PostProcess));
  74423. BABYLON.FxaaPostProcess = FxaaPostProcess;
  74424. })(BABYLON || (BABYLON = {}));
  74425. //# sourceMappingURL=babylon.fxaaPostProcess.js.map
  74426. var BABYLON;
  74427. (function (BABYLON) {
  74428. /**
  74429. * The ChromaticAberrationPostProcess separates the rgb channels in an image to produce chromatic distortion around the edges of the screen
  74430. */
  74431. var ChromaticAberrationPostProcess = /** @class */ (function (_super) {
  74432. __extends(ChromaticAberrationPostProcess, _super);
  74433. /**
  74434. * Creates a new instance ChromaticAberrationPostProcess
  74435. * @param name The name of the effect.
  74436. * @param screenWidth The width of the screen to apply the effect on.
  74437. * @param screenHeight The height of the screen to apply the effect on.
  74438. * @param options The required width/height ratio to downsize to before computing the render pass.
  74439. * @param camera The camera to apply the render pass to.
  74440. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  74441. * @param engine The engine which the post process will be applied. (default: current engine)
  74442. * @param reusable If the post process can be reused on the same frame. (default: false)
  74443. * @param textureType Type of textures used when performing the post process. (default: 0)
  74444. * @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)
  74445. */
  74446. function ChromaticAberrationPostProcess(name, screenWidth, screenHeight, options, camera, samplingMode, engine, reusable, textureType, blockCompilation) {
  74447. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  74448. if (blockCompilation === void 0) { blockCompilation = false; }
  74449. 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;
  74450. /**
  74451. * The amount of seperation of rgb channels (default: 30)
  74452. */
  74453. _this.aberrationAmount = 30;
  74454. /**
  74455. * The amount the effect will increase for pixels closer to the edge of the screen. (default: 0)
  74456. */
  74457. _this.radialIntensity = 0;
  74458. /**
  74459. * 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))
  74460. */
  74461. _this.direction = new BABYLON.Vector2(0.707, 0.707);
  74462. /**
  74463. * 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))
  74464. */
  74465. _this.centerPosition = new BABYLON.Vector2(0.5, 0.5);
  74466. _this.onApplyObservable.add(function (effect) {
  74467. effect.setFloat('chromatic_aberration', _this.aberrationAmount);
  74468. effect.setFloat('screen_width', screenWidth);
  74469. effect.setFloat('screen_height', screenHeight);
  74470. effect.setFloat('radialIntensity', _this.radialIntensity);
  74471. effect.setFloat2('direction', _this.direction.x, _this.direction.y);
  74472. effect.setFloat2('centerPosition', _this.centerPosition.x, _this.centerPosition.y);
  74473. });
  74474. return _this;
  74475. }
  74476. return ChromaticAberrationPostProcess;
  74477. }(BABYLON.PostProcess));
  74478. BABYLON.ChromaticAberrationPostProcess = ChromaticAberrationPostProcess;
  74479. })(BABYLON || (BABYLON = {}));
  74480. //# sourceMappingURL=babylon.chromaticAberrationPostProcess.js.map
  74481. var BABYLON;
  74482. (function (BABYLON) {
  74483. /**
  74484. * The GrainPostProcess adds noise to the image at mid luminance levels
  74485. */
  74486. var GrainPostProcess = /** @class */ (function (_super) {
  74487. __extends(GrainPostProcess, _super);
  74488. /**
  74489. * Creates a new instance of @see GrainPostProcess
  74490. * @param name The name of the effect.
  74491. * @param options The required width/height ratio to downsize to before computing the render pass.
  74492. * @param camera The camera to apply the render pass to.
  74493. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  74494. * @param engine The engine which the post process will be applied. (default: current engine)
  74495. * @param reusable If the post process can be reused on the same frame. (default: false)
  74496. * @param textureType Type of textures used when performing the post process. (default: 0)
  74497. * @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)
  74498. */
  74499. function GrainPostProcess(name, options, camera, samplingMode, engine, reusable, textureType, blockCompilation) {
  74500. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  74501. if (blockCompilation === void 0) { blockCompilation = false; }
  74502. var _this = _super.call(this, name, "grain", ["intensity", "animatedSeed"], [], options, camera, samplingMode, engine, reusable, null, textureType, undefined, null, blockCompilation) || this;
  74503. /**
  74504. * The intensity of the grain added (default: 30)
  74505. */
  74506. _this.intensity = 30;
  74507. /**
  74508. * If the grain should be randomized on every frame
  74509. */
  74510. _this.animated = false;
  74511. _this.onApplyObservable.add(function (effect) {
  74512. effect.setFloat('intensity', _this.intensity);
  74513. effect.setFloat('animatedSeed', _this.animated ? Math.random() + 1 : 1);
  74514. });
  74515. return _this;
  74516. }
  74517. return GrainPostProcess;
  74518. }(BABYLON.PostProcess));
  74519. BABYLON.GrainPostProcess = GrainPostProcess;
  74520. })(BABYLON || (BABYLON = {}));
  74521. //# sourceMappingURL=babylon.grainPostProcess.js.map
  74522. var BABYLON;
  74523. (function (BABYLON) {
  74524. /**
  74525. * The SharpenPostProcess applies a sharpen kernel to every pixel
  74526. * See http://en.wikipedia.org/wiki/Kernel_(image_processing)
  74527. */
  74528. var SharpenPostProcess = /** @class */ (function (_super) {
  74529. __extends(SharpenPostProcess, _super);
  74530. /**
  74531. * Creates a new instance ConvolutionPostProcess
  74532. * @param name The name of the effect.
  74533. * @param options The required width/height ratio to downsize to before computing the render pass.
  74534. * @param camera The camera to apply the render pass to.
  74535. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  74536. * @param engine The engine which the post process will be applied. (default: current engine)
  74537. * @param reusable If the post process can be reused on the same frame. (default: false)
  74538. * @param textureType Type of textures used when performing the post process. (default: 0)
  74539. * @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)
  74540. */
  74541. function SharpenPostProcess(name, options, camera, samplingMode, engine, reusable, textureType, blockCompilation) {
  74542. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  74543. if (blockCompilation === void 0) { blockCompilation = false; }
  74544. var _this = _super.call(this, name, "sharpen", ["sharpnessAmounts", "screenSize"], null, options, camera, samplingMode, engine, reusable, null, textureType, undefined, null, blockCompilation) || this;
  74545. /**
  74546. * How much of the original color should be applied. Setting this to 0 will display edge detection. (default: 1)
  74547. */
  74548. _this.colorAmount = 1.0;
  74549. /**
  74550. * How much sharpness should be applied (default: 0.3)
  74551. */
  74552. _this.edgeAmount = 0.3;
  74553. _this.onApply = function (effect) {
  74554. effect.setFloat2("screenSize", _this.width, _this.height);
  74555. effect.setFloat2("sharpnessAmounts", _this.edgeAmount, _this.colorAmount);
  74556. };
  74557. return _this;
  74558. }
  74559. return SharpenPostProcess;
  74560. }(BABYLON.PostProcess));
  74561. BABYLON.SharpenPostProcess = SharpenPostProcess;
  74562. })(BABYLON || (BABYLON = {}));
  74563. //# sourceMappingURL=babylon.sharpenPostProcess.js.map
  74564. var BABYLON;
  74565. (function (BABYLON) {
  74566. /**
  74567. * The Blur Post Process which blurs an image based on a kernel and direction.
  74568. * Can be used twice in x and y directions to perform a guassian blur in two passes.
  74569. */
  74570. var BlurPostProcess = /** @class */ (function (_super) {
  74571. __extends(BlurPostProcess, _super);
  74572. /**
  74573. * Creates a new instance BlurPostProcess
  74574. * @param name The name of the effect.
  74575. * @param direction The direction in which to blur the image.
  74576. * @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.
  74577. * @param options The required width/height ratio to downsize to before computing the render pass. (Use 1.0 for full size)
  74578. * @param camera The camera to apply the render pass to.
  74579. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  74580. * @param engine The engine which the post process will be applied. (default: current engine)
  74581. * @param reusable If the post process can be reused on the same frame. (default: false)
  74582. * @param textureType Type of textures used when performing the post process. (default: 0)
  74583. * @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)
  74584. */
  74585. function BlurPostProcess(name, /** The direction in which to blur the image. */ direction, kernel, options, camera, samplingMode, engine, reusable, textureType, defines, blockCompilation) {
  74586. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  74587. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  74588. if (defines === void 0) { defines = ""; }
  74589. if (blockCompilation === void 0) { blockCompilation = false; }
  74590. 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;
  74591. _this.direction = direction;
  74592. _this.blockCompilation = blockCompilation;
  74593. _this._packedFloat = false;
  74594. _this._staticDefines = "";
  74595. _this._staticDefines = defines;
  74596. _this.onApplyObservable.add(function (effect) {
  74597. if (_this._outputTexture) {
  74598. effect.setFloat2('delta', (1 / _this._outputTexture.width) * _this.direction.x, (1 / _this._outputTexture.height) * _this.direction.y);
  74599. }
  74600. else {
  74601. effect.setFloat2('delta', (1 / _this.width) * _this.direction.x, (1 / _this.height) * _this.direction.y);
  74602. }
  74603. });
  74604. _this.kernel = kernel;
  74605. return _this;
  74606. }
  74607. Object.defineProperty(BlurPostProcess.prototype, "kernel", {
  74608. /**
  74609. * Gets the length in pixels of the blur sample region
  74610. */
  74611. get: function () {
  74612. return this._idealKernel;
  74613. },
  74614. /**
  74615. * Sets the length in pixels of the blur sample region
  74616. */
  74617. set: function (v) {
  74618. if (this._idealKernel === v) {
  74619. return;
  74620. }
  74621. v = Math.max(v, 1);
  74622. this._idealKernel = v;
  74623. this._kernel = this._nearestBestKernel(v);
  74624. if (!this.blockCompilation) {
  74625. this._updateParameters();
  74626. }
  74627. },
  74628. enumerable: true,
  74629. configurable: true
  74630. });
  74631. Object.defineProperty(BlurPostProcess.prototype, "packedFloat", {
  74632. /**
  74633. * Gets wether or not the blur is unpacking/repacking floats
  74634. */
  74635. get: function () {
  74636. return this._packedFloat;
  74637. },
  74638. /**
  74639. * Sets wether or not the blur needs to unpack/repack floats
  74640. */
  74641. set: function (v) {
  74642. if (this._packedFloat === v) {
  74643. return;
  74644. }
  74645. this._packedFloat = v;
  74646. if (!this.blockCompilation) {
  74647. this._updateParameters();
  74648. }
  74649. },
  74650. enumerable: true,
  74651. configurable: true
  74652. });
  74653. /**
  74654. * Updates the effect with the current post process compile time values and recompiles the shader.
  74655. * @param defines Define statements that should be added at the beginning of the shader. (default: null)
  74656. * @param uniforms Set of uniform variables that will be passed to the shader. (default: null)
  74657. * @param samplers Set of Texture2D variables that will be passed to the shader. (default: null)
  74658. * @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
  74659. * @param onCompiled Called when the shader has been compiled.
  74660. * @param onError Called if there is an error when compiling a shader.
  74661. */
  74662. BlurPostProcess.prototype.updateEffect = function (defines, uniforms, samplers, indexParameters, onCompiled, onError) {
  74663. if (defines === void 0) { defines = null; }
  74664. if (uniforms === void 0) { uniforms = null; }
  74665. if (samplers === void 0) { samplers = null; }
  74666. this._updateParameters(onCompiled, onError);
  74667. };
  74668. BlurPostProcess.prototype._updateParameters = function (onCompiled, onError) {
  74669. // Generate sampling offsets and weights
  74670. var N = this._kernel;
  74671. var centerIndex = (N - 1) / 2;
  74672. // Generate Gaussian sampling weights over kernel
  74673. var offsets = [];
  74674. var weights = [];
  74675. var totalWeight = 0;
  74676. for (var i = 0; i < N; i++) {
  74677. var u = i / (N - 1);
  74678. var w = this._gaussianWeight(u * 2.0 - 1);
  74679. offsets[i] = (i - centerIndex);
  74680. weights[i] = w;
  74681. totalWeight += w;
  74682. }
  74683. // Normalize weights
  74684. for (var i = 0; i < weights.length; i++) {
  74685. weights[i] /= totalWeight;
  74686. }
  74687. // Optimize: combine samples to take advantage of hardware linear sampling
  74688. // Walk from left to center, combining pairs (symmetrically)
  74689. var linearSamplingWeights = [];
  74690. var linearSamplingOffsets = [];
  74691. var linearSamplingMap = [];
  74692. for (var i = 0; i <= centerIndex; i += 2) {
  74693. var j = Math.min(i + 1, Math.floor(centerIndex));
  74694. var singleCenterSample = i === j;
  74695. if (singleCenterSample) {
  74696. linearSamplingMap.push({ o: offsets[i], w: weights[i] });
  74697. }
  74698. else {
  74699. var sharedCell = j === centerIndex;
  74700. var weightLinear = (weights[i] + weights[j] * (sharedCell ? .5 : 1.));
  74701. var offsetLinear = offsets[i] + 1 / (1 + weights[i] / weights[j]);
  74702. if (offsetLinear === 0) {
  74703. linearSamplingMap.push({ o: offsets[i], w: weights[i] });
  74704. linearSamplingMap.push({ o: offsets[i + 1], w: weights[i + 1] });
  74705. }
  74706. else {
  74707. linearSamplingMap.push({ o: offsetLinear, w: weightLinear });
  74708. linearSamplingMap.push({ o: -offsetLinear, w: weightLinear });
  74709. }
  74710. }
  74711. }
  74712. for (var i = 0; i < linearSamplingMap.length; i++) {
  74713. linearSamplingOffsets[i] = linearSamplingMap[i].o;
  74714. linearSamplingWeights[i] = linearSamplingMap[i].w;
  74715. }
  74716. // Replace with optimized
  74717. offsets = linearSamplingOffsets;
  74718. weights = linearSamplingWeights;
  74719. // Generate shaders
  74720. var maxVaryingRows = this.getEngine().getCaps().maxVaryingVectors;
  74721. var freeVaryingVec2 = Math.max(maxVaryingRows, 0.) - 1; // Because of sampleCenter
  74722. var varyingCount = Math.min(offsets.length, freeVaryingVec2);
  74723. var defines = "";
  74724. defines += this._staticDefines;
  74725. // The DOF fragment should ignore the center pixel when looping as it is handled manualy in the fragment shader.
  74726. if (this._staticDefines.indexOf("DOF") != -1) {
  74727. defines += "#define CENTER_WEIGHT " + this._glslFloat(weights[varyingCount - 1]) + "\r\n";
  74728. varyingCount--;
  74729. }
  74730. for (var i = 0; i < varyingCount; i++) {
  74731. defines += "#define KERNEL_OFFSET" + i + " " + this._glslFloat(offsets[i]) + "\r\n";
  74732. defines += "#define KERNEL_WEIGHT" + i + " " + this._glslFloat(weights[i]) + "\r\n";
  74733. }
  74734. var depCount = 0;
  74735. for (var i = freeVaryingVec2; i < offsets.length; i++) {
  74736. defines += "#define KERNEL_DEP_OFFSET" + depCount + " " + this._glslFloat(offsets[i]) + "\r\n";
  74737. defines += "#define KERNEL_DEP_WEIGHT" + depCount + " " + this._glslFloat(weights[i]) + "\r\n";
  74738. depCount++;
  74739. }
  74740. if (this.packedFloat) {
  74741. defines += "#define PACKEDFLOAT 1";
  74742. }
  74743. this.blockCompilation = false;
  74744. _super.prototype.updateEffect.call(this, defines, null, null, {
  74745. varyingCount: varyingCount,
  74746. depCount: depCount
  74747. }, onCompiled, onError);
  74748. };
  74749. /**
  74750. * Best kernels are odd numbers that when divided by 2, their integer part is even, so 5, 9 or 13.
  74751. * Other odd kernels optimize correctly but require proportionally more samples, even kernels are
  74752. * possible but will produce minor visual artifacts. Since each new kernel requires a new shader we
  74753. * want to minimize kernel changes, having gaps between physical kernels is helpful in that regard.
  74754. * The gaps between physical kernels are compensated for in the weighting of the samples
  74755. * @param idealKernel Ideal blur kernel.
  74756. * @return Nearest best kernel.
  74757. */
  74758. BlurPostProcess.prototype._nearestBestKernel = function (idealKernel) {
  74759. var v = Math.round(idealKernel);
  74760. for (var _i = 0, _a = [v, v - 1, v + 1, v - 2, v + 2]; _i < _a.length; _i++) {
  74761. var k = _a[_i];
  74762. if (((k % 2) !== 0) && ((Math.floor(k / 2) % 2) === 0) && k > 0) {
  74763. return Math.max(k, 3);
  74764. }
  74765. }
  74766. return Math.max(v, 3);
  74767. };
  74768. /**
  74769. * Calculates the value of a Gaussian distribution with sigma 3 at a given point.
  74770. * @param x The point on the Gaussian distribution to sample.
  74771. * @return the value of the Gaussian function at x.
  74772. */
  74773. BlurPostProcess.prototype._gaussianWeight = function (x) {
  74774. //reference: Engine/ImageProcessingBlur.cpp #dcc760
  74775. // We are evaluating the Gaussian (normal) distribution over a kernel parameter space of [-1,1],
  74776. // so we truncate at three standard deviations by setting stddev (sigma) to 1/3.
  74777. // The choice of 3-sigma truncation is common but arbitrary, and means that the signal is
  74778. // truncated at around 1.3% of peak strength.
  74779. //the distribution is scaled to account for the difference between the actual kernel size and the requested kernel size
  74780. var sigma = (1 / 3);
  74781. var denominator = Math.sqrt(2.0 * Math.PI) * sigma;
  74782. var exponent = -((x * x) / (2.0 * sigma * sigma));
  74783. var weight = (1.0 / denominator) * Math.exp(exponent);
  74784. return weight;
  74785. };
  74786. /**
  74787. * Generates a string that can be used as a floating point number in GLSL.
  74788. * @param x Value to print.
  74789. * @param decimalFigures Number of decimal places to print the number to (excluding trailing 0s).
  74790. * @return GLSL float string.
  74791. */
  74792. BlurPostProcess.prototype._glslFloat = function (x, decimalFigures) {
  74793. if (decimalFigures === void 0) { decimalFigures = 8; }
  74794. return x.toFixed(decimalFigures).replace(/0+$/, '');
  74795. };
  74796. return BlurPostProcess;
  74797. }(BABYLON.PostProcess));
  74798. BABYLON.BlurPostProcess = BlurPostProcess;
  74799. })(BABYLON || (BABYLON = {}));
  74800. //# sourceMappingURL=babylon.blurPostProcess.js.map
  74801. var BABYLON;
  74802. (function (BABYLON) {
  74803. /**
  74804. * The DepthOfFieldBlurPostProcess applied a blur in a give direction.
  74805. * This blur differs from the standard BlurPostProcess as it attempts to avoid blurring pixels
  74806. * based on samples that have a large difference in distance than the center pixel.
  74807. * See section 2.6.2 http://fileadmin.cs.lth.se/cs/education/edan35/lectures/12dof.pdf
  74808. */
  74809. var DepthOfFieldBlurPostProcess = /** @class */ (function (_super) {
  74810. __extends(DepthOfFieldBlurPostProcess, _super);
  74811. /**
  74812. * Creates a new instance CircleOfConfusionPostProcess
  74813. * @param name The name of the effect.
  74814. * @param scene The scene the effect belongs to.
  74815. * @param direction The direction the blur should be applied.
  74816. * @param kernel The size of the kernel used to blur.
  74817. * @param options The required width/height ratio to downsize to before computing the render pass.
  74818. * @param camera The camera to apply the render pass to.
  74819. * @param circleOfConfusion The circle of confusion + depth map to be used to avoid blurring accross edges
  74820. * @param imageToBlur The image to apply the blur to (default: Current rendered frame)
  74821. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  74822. * @param engine The engine which the post process will be applied. (default: current engine)
  74823. * @param reusable If the post process can be reused on the same frame. (default: false)
  74824. * @param textureType Type of textures used when performing the post process. (default: 0)
  74825. * @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)
  74826. */
  74827. function DepthOfFieldBlurPostProcess(name, scene, direction, kernel, options, camera, circleOfConfusion, imageToBlur, samplingMode, engine, reusable, textureType, blockCompilation) {
  74828. if (imageToBlur === void 0) { imageToBlur = null; }
  74829. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  74830. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  74831. if (blockCompilation === void 0) { blockCompilation = false; }
  74832. 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;
  74833. _this.direction = direction;
  74834. _this.onApplyObservable.add(function (effect) {
  74835. if (imageToBlur != null) {
  74836. effect.setTextureFromPostProcess("textureSampler", imageToBlur);
  74837. }
  74838. effect.setTextureFromPostProcessOutput("circleOfConfusionSampler", circleOfConfusion);
  74839. if (scene.activeCamera) {
  74840. effect.setFloat2('cameraMinMaxZ', scene.activeCamera.minZ, scene.activeCamera.maxZ);
  74841. }
  74842. });
  74843. return _this;
  74844. }
  74845. return DepthOfFieldBlurPostProcess;
  74846. }(BABYLON.BlurPostProcess));
  74847. BABYLON.DepthOfFieldBlurPostProcess = DepthOfFieldBlurPostProcess;
  74848. })(BABYLON || (BABYLON = {}));
  74849. //# sourceMappingURL=babylon.depthOfFieldBlurPostProcess.js.map
  74850. var BABYLON;
  74851. (function (BABYLON) {
  74852. /**
  74853. * Options to be set when merging outputs from the default pipeline.
  74854. */
  74855. var DepthOfFieldMergePostProcessOptions = /** @class */ (function () {
  74856. function DepthOfFieldMergePostProcessOptions() {
  74857. }
  74858. return DepthOfFieldMergePostProcessOptions;
  74859. }());
  74860. BABYLON.DepthOfFieldMergePostProcessOptions = DepthOfFieldMergePostProcessOptions;
  74861. /**
  74862. * The DepthOfFieldMergePostProcess merges blurred images with the original based on the values of the circle of confusion.
  74863. */
  74864. var DepthOfFieldMergePostProcess = /** @class */ (function (_super) {
  74865. __extends(DepthOfFieldMergePostProcess, _super);
  74866. /**
  74867. * Creates a new instance of DepthOfFieldMergePostProcess
  74868. * @param name The name of the effect.
  74869. * @param originalFromInput Post process which's input will be used for the merge.
  74870. * @param circleOfConfusion Circle of confusion post process which's output will be used to blur each pixel.
  74871. * @param blurSteps Blur post processes from low to high which will be mixed with the original image.
  74872. * @param options The required width/height ratio to downsize to before computing the render pass.
  74873. * @param camera The camera to apply the render pass to.
  74874. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  74875. * @param engine The engine which the post process will be applied. (default: current engine)
  74876. * @param reusable If the post process can be reused on the same frame. (default: false)
  74877. * @param textureType Type of textures used when performing the post process. (default: 0)
  74878. * @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)
  74879. */
  74880. function DepthOfFieldMergePostProcess(name, originalFromInput, circleOfConfusion, blurSteps, options, camera, samplingMode, engine, reusable, textureType, blockCompilation) {
  74881. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  74882. if (blockCompilation === void 0) { blockCompilation = false; }
  74883. var _this = _super.call(this, name, "depthOfFieldMerge", [], ["circleOfConfusionSampler", "blurStep0", "blurStep1", "blurStep2"], options, camera, samplingMode, engine, reusable, null, textureType, undefined, null, true) || this;
  74884. _this.blurSteps = blurSteps;
  74885. _this.onApplyObservable.add(function (effect) {
  74886. effect.setTextureFromPostProcess("textureSampler", originalFromInput);
  74887. effect.setTextureFromPostProcessOutput("circleOfConfusionSampler", circleOfConfusion);
  74888. blurSteps.forEach(function (step, index) {
  74889. effect.setTextureFromPostProcessOutput("blurStep" + (blurSteps.length - index - 1), step);
  74890. });
  74891. });
  74892. if (!blockCompilation) {
  74893. _this.updateEffect();
  74894. }
  74895. return _this;
  74896. }
  74897. /**
  74898. * Updates the effect with the current post process compile time values and recompiles the shader.
  74899. * @param defines Define statements that should be added at the beginning of the shader. (default: null)
  74900. * @param uniforms Set of uniform variables that will be passed to the shader. (default: null)
  74901. * @param samplers Set of Texture2D variables that will be passed to the shader. (default: null)
  74902. * @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
  74903. * @param onCompiled Called when the shader has been compiled.
  74904. * @param onError Called if there is an error when compiling a shader.
  74905. */
  74906. DepthOfFieldMergePostProcess.prototype.updateEffect = function (defines, uniforms, samplers, indexParameters, onCompiled, onError) {
  74907. if (defines === void 0) { defines = null; }
  74908. if (uniforms === void 0) { uniforms = null; }
  74909. if (samplers === void 0) { samplers = null; }
  74910. if (!defines) {
  74911. defines = "";
  74912. defines += "#define BLUR_LEVEL " + (this.blurSteps.length - 1) + "\n";
  74913. }
  74914. _super.prototype.updateEffect.call(this, defines, uniforms, samplers, indexParameters, onCompiled, onError);
  74915. };
  74916. return DepthOfFieldMergePostProcess;
  74917. }(BABYLON.PostProcess));
  74918. BABYLON.DepthOfFieldMergePostProcess = DepthOfFieldMergePostProcess;
  74919. })(BABYLON || (BABYLON = {}));
  74920. //# sourceMappingURL=babylon.depthOfFieldMergePostProcess.js.map
  74921. var BABYLON;
  74922. (function (BABYLON) {
  74923. /**
  74924. * The CircleOfConfusionPostProcess computes the circle of confusion value for each pixel given required lens parameters. See https://en.wikipedia.org/wiki/Circle_of_confusion
  74925. */
  74926. var CircleOfConfusionPostProcess = /** @class */ (function (_super) {
  74927. __extends(CircleOfConfusionPostProcess, _super);
  74928. /**
  74929. * Creates a new instance CircleOfConfusionPostProcess
  74930. * @param name The name of the effect.
  74931. * @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.
  74932. * @param options The required width/height ratio to downsize to before computing the render pass.
  74933. * @param camera The camera to apply the render pass to.
  74934. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  74935. * @param engine The engine which the post process will be applied. (default: current engine)
  74936. * @param reusable If the post process can be reused on the same frame. (default: false)
  74937. * @param textureType Type of textures used when performing the post process. (default: 0)
  74938. * @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)
  74939. */
  74940. function CircleOfConfusionPostProcess(name, depthTexture, options, camera, samplingMode, engine, reusable, textureType, blockCompilation) {
  74941. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  74942. if (blockCompilation === void 0) { blockCompilation = false; }
  74943. var _this = _super.call(this, name, "circleOfConfusion", ["cameraMinMaxZ", "focusDistance", "cocPrecalculation"], ["depthSampler"], options, camera, samplingMode, engine, reusable, null, textureType, undefined, null, blockCompilation) || this;
  74944. /**
  74945. * 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.
  74946. */
  74947. _this.lensSize = 50;
  74948. /**
  74949. * F-Stop of the effect's camera. The diamater of the resulting aperture can be computed by lensSize/fStop. (default: 1.4)
  74950. */
  74951. _this.fStop = 1.4;
  74952. /**
  74953. * Distance away from the camera to focus on in scene units/1000 (eg. millimeter). (default: 2000)
  74954. */
  74955. _this.focusDistance = 2000;
  74956. /**
  74957. * Focal length of the effect's camera in scene units/1000 (eg. millimeter). (default: 50)
  74958. */
  74959. _this.focalLength = 50;
  74960. _this._depthTexture = null;
  74961. _this._depthTexture = depthTexture;
  74962. _this.onApplyObservable.add(function (effect) {
  74963. if (!_this._depthTexture) {
  74964. BABYLON.Tools.Warn("No depth texture set on CircleOfConfusionPostProcess");
  74965. return;
  74966. }
  74967. effect.setTexture("depthSampler", _this._depthTexture);
  74968. // Circle of confusion calculation, See https://developer.nvidia.com/gpugems/GPUGems/gpugems_ch23.html
  74969. var aperture = _this.lensSize / _this.fStop;
  74970. var cocPrecalculation = ((aperture * _this.focalLength) / ((_this.focusDistance - _this.focalLength))); // * ((this.focusDistance - pixelDistance)/pixelDistance) [This part is done in shader]
  74971. effect.setFloat('focusDistance', _this.focusDistance);
  74972. effect.setFloat('cocPrecalculation', cocPrecalculation);
  74973. effect.setFloat2('cameraMinMaxZ', _this._depthTexture.activeCamera.minZ, _this._depthTexture.activeCamera.maxZ);
  74974. });
  74975. return _this;
  74976. }
  74977. Object.defineProperty(CircleOfConfusionPostProcess.prototype, "depthTexture", {
  74978. /**
  74979. * 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.
  74980. */
  74981. set: function (value) {
  74982. this._depthTexture = value;
  74983. },
  74984. enumerable: true,
  74985. configurable: true
  74986. });
  74987. return CircleOfConfusionPostProcess;
  74988. }(BABYLON.PostProcess));
  74989. BABYLON.CircleOfConfusionPostProcess = CircleOfConfusionPostProcess;
  74990. })(BABYLON || (BABYLON = {}));
  74991. //# sourceMappingURL=babylon.circleOfConfusionPostProcess.js.map
  74992. var BABYLON;
  74993. (function (BABYLON) {
  74994. /**
  74995. * Specifies the level of max blur that should be applied when using the depth of field effect
  74996. */
  74997. var DepthOfFieldEffectBlurLevel;
  74998. (function (DepthOfFieldEffectBlurLevel) {
  74999. /**
  75000. * Subtle blur
  75001. */
  75002. DepthOfFieldEffectBlurLevel[DepthOfFieldEffectBlurLevel["Low"] = 0] = "Low";
  75003. /**
  75004. * Medium blur
  75005. */
  75006. DepthOfFieldEffectBlurLevel[DepthOfFieldEffectBlurLevel["Medium"] = 1] = "Medium";
  75007. /**
  75008. * Large blur
  75009. */
  75010. DepthOfFieldEffectBlurLevel[DepthOfFieldEffectBlurLevel["High"] = 2] = "High";
  75011. })(DepthOfFieldEffectBlurLevel = BABYLON.DepthOfFieldEffectBlurLevel || (BABYLON.DepthOfFieldEffectBlurLevel = {}));
  75012. ;
  75013. /**
  75014. * The depth of field effect applies a blur to objects that are closer or further from where the camera is focusing.
  75015. */
  75016. var DepthOfFieldEffect = /** @class */ (function (_super) {
  75017. __extends(DepthOfFieldEffect, _super);
  75018. /**
  75019. * Creates a new instance DepthOfFieldEffect
  75020. * @param scene The scene the effect belongs to.
  75021. * @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.
  75022. * @param pipelineTextureType The type of texture to be used when performing the post processing.
  75023. * @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)
  75024. */
  75025. function DepthOfFieldEffect(scene, depthTexture, blurLevel, pipelineTextureType, blockCompilation) {
  75026. if (blurLevel === void 0) { blurLevel = DepthOfFieldEffectBlurLevel.Low; }
  75027. if (pipelineTextureType === void 0) { pipelineTextureType = 0; }
  75028. if (blockCompilation === void 0) { blockCompilation = false; }
  75029. var _this = _super.call(this, scene.getEngine(), "depth of field", function () {
  75030. return _this._effects;
  75031. }, true) || this;
  75032. /**
  75033. * Internal post processes in depth of field effect
  75034. */
  75035. _this._effects = [];
  75036. // Circle of confusion value for each pixel is used to determine how much to blur that pixel
  75037. _this._circleOfConfusion = new BABYLON.CircleOfConfusionPostProcess("circleOfConfusion", depthTexture, 1, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, pipelineTextureType, blockCompilation);
  75038. // 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)
  75039. // Blur the image but do not blur on sharp far to near distance changes to avoid bleeding artifacts
  75040. // See section 2.6.2 http://fileadmin.cs.lth.se/cs/education/edan35/lectures/12dof.pdf
  75041. _this._depthOfFieldBlurY = [];
  75042. _this._depthOfFieldBlurX = [];
  75043. var blurCount = 1;
  75044. var kernelSize = 15;
  75045. switch (blurLevel) {
  75046. case DepthOfFieldEffectBlurLevel.High: {
  75047. blurCount = 3;
  75048. kernelSize = 51;
  75049. break;
  75050. }
  75051. case DepthOfFieldEffectBlurLevel.Medium: {
  75052. blurCount = 2;
  75053. kernelSize = 31;
  75054. break;
  75055. }
  75056. default: {
  75057. kernelSize = 15;
  75058. blurCount = 1;
  75059. break;
  75060. }
  75061. }
  75062. var adjustedKernelSize = kernelSize / Math.pow(2, blurCount - 1);
  75063. var ratio = 1.0;
  75064. for (var i = 0; i < blurCount; i++) {
  75065. 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);
  75066. blurY.autoClear = false;
  75067. ratio = 0.75 / Math.pow(2, i);
  75068. 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);
  75069. blurX.autoClear = false;
  75070. _this._depthOfFieldBlurY.push(blurY);
  75071. _this._depthOfFieldBlurX.push(blurX);
  75072. }
  75073. // Set all post processes on the effect.
  75074. _this._effects = [_this._circleOfConfusion];
  75075. for (var i = 0; i < _this._depthOfFieldBlurX.length; i++) {
  75076. _this._effects.push(_this._depthOfFieldBlurY[i]);
  75077. _this._effects.push(_this._depthOfFieldBlurX[i]);
  75078. }
  75079. // Merge blurred images with original image based on circleOfConfusion
  75080. _this._dofMerge = new BABYLON.DepthOfFieldMergePostProcess("dofMerge", _this._circleOfConfusion, _this._circleOfConfusion, _this._depthOfFieldBlurX, ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, pipelineTextureType, blockCompilation);
  75081. _this._dofMerge.autoClear = false;
  75082. _this._effects.push(_this._dofMerge);
  75083. return _this;
  75084. }
  75085. Object.defineProperty(DepthOfFieldEffect.prototype, "focalLength", {
  75086. get: function () {
  75087. return this._circleOfConfusion.focalLength;
  75088. },
  75089. /**
  75090. * The focal the length of the camera used in the effect in scene units/1000 (eg. millimeter)
  75091. */
  75092. set: function (value) {
  75093. this._circleOfConfusion.focalLength = value;
  75094. },
  75095. enumerable: true,
  75096. configurable: true
  75097. });
  75098. Object.defineProperty(DepthOfFieldEffect.prototype, "fStop", {
  75099. get: function () {
  75100. return this._circleOfConfusion.fStop;
  75101. },
  75102. /**
  75103. * F-Stop of the effect's camera. The diamater of the resulting aperture can be computed by lensSize/fStop. (default: 1.4)
  75104. */
  75105. set: function (value) {
  75106. this._circleOfConfusion.fStop = value;
  75107. },
  75108. enumerable: true,
  75109. configurable: true
  75110. });
  75111. Object.defineProperty(DepthOfFieldEffect.prototype, "focusDistance", {
  75112. get: function () {
  75113. return this._circleOfConfusion.focusDistance;
  75114. },
  75115. /**
  75116. * Distance away from the camera to focus on in scene units/1000 (eg. millimeter). (default: 2000)
  75117. */
  75118. set: function (value) {
  75119. this._circleOfConfusion.focusDistance = value;
  75120. },
  75121. enumerable: true,
  75122. configurable: true
  75123. });
  75124. Object.defineProperty(DepthOfFieldEffect.prototype, "lensSize", {
  75125. get: function () {
  75126. return this._circleOfConfusion.lensSize;
  75127. },
  75128. /**
  75129. * 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.
  75130. */
  75131. set: function (value) {
  75132. this._circleOfConfusion.lensSize = value;
  75133. },
  75134. enumerable: true,
  75135. configurable: true
  75136. });
  75137. Object.defineProperty(DepthOfFieldEffect.prototype, "depthTexture", {
  75138. /**
  75139. * 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.
  75140. */
  75141. set: function (value) {
  75142. this._circleOfConfusion.depthTexture = value;
  75143. },
  75144. enumerable: true,
  75145. configurable: true
  75146. });
  75147. /**
  75148. * Disposes each of the internal effects for a given camera.
  75149. * @param camera The camera to dispose the effect on.
  75150. */
  75151. DepthOfFieldEffect.prototype.disposeEffects = function (camera) {
  75152. for (var effectIndex = 0; effectIndex < this._effects.length; effectIndex++) {
  75153. this._effects[effectIndex].dispose(camera);
  75154. }
  75155. };
  75156. /**
  75157. * Internal
  75158. */
  75159. DepthOfFieldEffect.prototype._updateEffects = function () {
  75160. for (var effectIndex = 0; effectIndex < this._effects.length; effectIndex++) {
  75161. this._effects[effectIndex].updateEffect();
  75162. }
  75163. };
  75164. /**
  75165. * Internal
  75166. * @returns if all the contained post processes are ready.
  75167. */
  75168. DepthOfFieldEffect.prototype._isReady = function () {
  75169. for (var effectIndex = 0; effectIndex < this._effects.length; effectIndex++) {
  75170. if (!this._effects[effectIndex].isReady()) {
  75171. return false;
  75172. }
  75173. }
  75174. return true;
  75175. };
  75176. return DepthOfFieldEffect;
  75177. }(BABYLON.PostProcessRenderEffect));
  75178. BABYLON.DepthOfFieldEffect = DepthOfFieldEffect;
  75179. })(BABYLON || (BABYLON = {}));
  75180. //# sourceMappingURL=babylon.depthOfFieldEffect.js.map
  75181. var BABYLON;
  75182. (function (BABYLON) {
  75183. /**
  75184. * The BloomMergePostProcess merges blurred images with the original based on the values of the circle of confusion.
  75185. */
  75186. var BloomMergePostProcess = /** @class */ (function (_super) {
  75187. __extends(BloomMergePostProcess, _super);
  75188. /**
  75189. * Creates a new instance of @see BloomMergePostProcess
  75190. * @param name The name of the effect.
  75191. * @param originalFromInput Post process which's input will be used for the merge.
  75192. * @param blurred Blurred highlights post process which's output will be used.
  75193. * @param weight Weight of the bloom to be added to the original input.
  75194. * @param options The required width/height ratio to downsize to before computing the render pass.
  75195. * @param camera The camera to apply the render pass to.
  75196. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  75197. * @param engine The engine which the post process will be applied. (default: current engine)
  75198. * @param reusable If the post process can be reused on the same frame. (default: false)
  75199. * @param textureType Type of textures used when performing the post process. (default: 0)
  75200. * @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)
  75201. */
  75202. function BloomMergePostProcess(name, originalFromInput, blurred, /** Weight of the bloom to be added to the original input. */ weight, options, camera, samplingMode, engine, reusable, textureType, blockCompilation) {
  75203. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  75204. if (blockCompilation === void 0) { blockCompilation = false; }
  75205. var _this = _super.call(this, name, "bloomMerge", ["bloomWeight"], ["circleOfConfusionSampler", "blurStep0", "blurStep1", "blurStep2", "bloomBlur"], options, camera, samplingMode, engine, reusable, null, textureType, undefined, null, true) || this;
  75206. _this.weight = weight;
  75207. _this.onApplyObservable.add(function (effect) {
  75208. effect.setTextureFromPostProcess("textureSampler", originalFromInput);
  75209. effect.setTextureFromPostProcessOutput("bloomBlur", blurred);
  75210. effect.setFloat("bloomWeight", _this.weight);
  75211. });
  75212. if (!blockCompilation) {
  75213. _this.updateEffect();
  75214. }
  75215. return _this;
  75216. }
  75217. return BloomMergePostProcess;
  75218. }(BABYLON.PostProcess));
  75219. BABYLON.BloomMergePostProcess = BloomMergePostProcess;
  75220. })(BABYLON || (BABYLON = {}));
  75221. //# sourceMappingURL=babylon.bloomMergePostProcess.js.map
  75222. var BABYLON;
  75223. (function (BABYLON) {
  75224. /**
  75225. * 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.
  75226. */
  75227. var ExtractHighlightsPostProcess = /** @class */ (function (_super) {
  75228. __extends(ExtractHighlightsPostProcess, _super);
  75229. function ExtractHighlightsPostProcess(name, options, camera, samplingMode, engine, reusable, textureType, blockCompilation) {
  75230. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  75231. if (blockCompilation === void 0) { blockCompilation = false; }
  75232. var _this = _super.call(this, name, "extractHighlights", ["threshold", "exposure"], null, options, camera, samplingMode, engine, reusable, null, textureType, undefined, null, blockCompilation) || this;
  75233. /**
  75234. * The luminance threshold, pixels below this value will be set to black.
  75235. */
  75236. _this.threshold = 0.9;
  75237. /**
  75238. * Internal
  75239. */
  75240. _this._exposure = 1;
  75241. /**
  75242. * Post process which has the input texture to be used when performing highlight extraction
  75243. */
  75244. _this._inputPostProcess = null;
  75245. _this.onApplyObservable.add(function (effect) {
  75246. if (_this._inputPostProcess) {
  75247. effect.setTextureFromPostProcess("textureSampler", _this._inputPostProcess);
  75248. }
  75249. effect.setFloat('threshold', Math.pow(_this.threshold, BABYLON.ToGammaSpace));
  75250. effect.setFloat('exposure', _this._exposure);
  75251. });
  75252. return _this;
  75253. }
  75254. return ExtractHighlightsPostProcess;
  75255. }(BABYLON.PostProcess));
  75256. BABYLON.ExtractHighlightsPostProcess = ExtractHighlightsPostProcess;
  75257. })(BABYLON || (BABYLON = {}));
  75258. //# sourceMappingURL=babylon.extractHighlightsPostProcess.js.map
  75259. var BABYLON;
  75260. (function (BABYLON) {
  75261. /**
  75262. * The bloom effect spreads bright areas of an image to simulate artifacts seen in cameras
  75263. */
  75264. var BloomEffect = /** @class */ (function (_super) {
  75265. __extends(BloomEffect, _super);
  75266. /**
  75267. * Creates a new instance of @see BloomEffect
  75268. * @param scene The scene the effect belongs to.
  75269. * @param bloomScale The ratio of the blur texture to the input texture that should be used to compute the bloom.
  75270. * @param bloomKernel The size of the kernel to be used when applying the blur.
  75271. * @param bloomWeight The the strength of bloom.
  75272. * @param pipelineTextureType The type of texture to be used when performing the post processing.
  75273. * @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)
  75274. */
  75275. function BloomEffect(scene, bloomScale, bloomWeight, bloomKernel, pipelineTextureType, blockCompilation) {
  75276. if (pipelineTextureType === void 0) { pipelineTextureType = 0; }
  75277. if (blockCompilation === void 0) { blockCompilation = false; }
  75278. var _this = _super.call(this, scene.getEngine(), "bloom", function () {
  75279. return _this._effects;
  75280. }, true) || this;
  75281. _this.bloomScale = bloomScale;
  75282. /**
  75283. * Internal
  75284. */
  75285. _this._effects = [];
  75286. _this._downscale = new BABYLON.ExtractHighlightsPostProcess("highlights", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, pipelineTextureType, blockCompilation);
  75287. _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);
  75288. _this._blurX.alwaysForcePOT = true;
  75289. _this._blurX.autoClear = false;
  75290. _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);
  75291. _this._blurY.alwaysForcePOT = true;
  75292. _this._blurY.autoClear = false;
  75293. _this.kernel = bloomKernel;
  75294. _this._effects = [_this._downscale, _this._blurX, _this._blurY];
  75295. _this._merge = new BABYLON.BloomMergePostProcess("bloomMerge", _this._downscale, _this._blurY, bloomWeight, bloomScale, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, pipelineTextureType, blockCompilation);
  75296. _this._merge.autoClear = false;
  75297. _this._effects.push(_this._merge);
  75298. return _this;
  75299. }
  75300. Object.defineProperty(BloomEffect.prototype, "threshold", {
  75301. /**
  75302. * The luminance threshold to find bright areas of the image to bloom.
  75303. */
  75304. get: function () {
  75305. return this._downscale.threshold;
  75306. },
  75307. set: function (value) {
  75308. this._downscale.threshold = value;
  75309. },
  75310. enumerable: true,
  75311. configurable: true
  75312. });
  75313. Object.defineProperty(BloomEffect.prototype, "weight", {
  75314. /**
  75315. * The strength of the bloom.
  75316. */
  75317. get: function () {
  75318. return this._merge.weight;
  75319. },
  75320. set: function (value) {
  75321. this._merge.weight = value;
  75322. },
  75323. enumerable: true,
  75324. configurable: true
  75325. });
  75326. Object.defineProperty(BloomEffect.prototype, "kernel", {
  75327. /**
  75328. * Specifies the size of the bloom blur kernel, relative to the final output size
  75329. */
  75330. get: function () {
  75331. return this._blurX.kernel / this.bloomScale;
  75332. },
  75333. set: function (value) {
  75334. this._blurX.kernel = value * this.bloomScale;
  75335. this._blurY.kernel = value * this.bloomScale;
  75336. },
  75337. enumerable: true,
  75338. configurable: true
  75339. });
  75340. /**
  75341. * Disposes each of the internal effects for a given camera.
  75342. * @param camera The camera to dispose the effect on.
  75343. */
  75344. BloomEffect.prototype.disposeEffects = function (camera) {
  75345. for (var effectIndex = 0; effectIndex < this._effects.length; effectIndex++) {
  75346. this._effects[effectIndex].dispose(camera);
  75347. }
  75348. };
  75349. /**
  75350. * Internal
  75351. */
  75352. BloomEffect.prototype._updateEffects = function () {
  75353. for (var effectIndex = 0; effectIndex < this._effects.length; effectIndex++) {
  75354. this._effects[effectIndex].updateEffect();
  75355. }
  75356. };
  75357. /**
  75358. * Internal
  75359. * @returns if all the contained post processes are ready.
  75360. */
  75361. BloomEffect.prototype._isReady = function () {
  75362. for (var effectIndex = 0; effectIndex < this._effects.length; effectIndex++) {
  75363. if (!this._effects[effectIndex].isReady()) {
  75364. return false;
  75365. }
  75366. }
  75367. return true;
  75368. };
  75369. return BloomEffect;
  75370. }(BABYLON.PostProcessRenderEffect));
  75371. BABYLON.BloomEffect = BloomEffect;
  75372. })(BABYLON || (BABYLON = {}));
  75373. //# sourceMappingURL=babylon.bloomEffect.js.map
  75374. var BABYLON;
  75375. (function (BABYLON) {
  75376. /**
  75377. * The default rendering pipeline can be added to a scene to apply common post processing effects such as anti-aliasing or depth of field.
  75378. * See https://doc.babylonjs.com/how_to/using_default_rendering_pipeline
  75379. */
  75380. var DefaultRenderingPipeline = /** @class */ (function (_super) {
  75381. __extends(DefaultRenderingPipeline, _super);
  75382. /**
  75383. * @constructor
  75384. * @param {string} name - The rendering pipeline name
  75385. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  75386. * @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)
  75387. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  75388. * @param {boolean} automaticBuild - if false, you will have to manually call prepare() to update the pipeline
  75389. */
  75390. function DefaultRenderingPipeline(name, hdr, scene, cameras, automaticBuild) {
  75391. if (automaticBuild === void 0) { automaticBuild = true; }
  75392. var _this = _super.call(this, scene.getEngine(), name) || this;
  75393. _this._originalCameras = [];
  75394. /**
  75395. * ID of the sharpen post process,
  75396. */
  75397. _this.SharpenPostProcessId = "SharpenPostProcessEffect";
  75398. /**
  75399. * ID of the image processing post process;
  75400. */
  75401. _this.ImageProcessingPostProcessId = "ImageProcessingPostProcessEffect";
  75402. /**
  75403. * ID of the Fast Approximate Anti-Aliasing post process;
  75404. */
  75405. _this.FxaaPostProcessId = "FxaaPostProcessEffect";
  75406. /**
  75407. * ID of the chromatic aberration post process,
  75408. */
  75409. _this.ChromaticAberrationPostProcessId = "ChromaticAberrationPostProcessEffect";
  75410. /**
  75411. * ID of the grain post process
  75412. */
  75413. _this.GrainPostProcessId = "GrainPostProcessEffect";
  75414. /**
  75415. * Animations which can be used to tweak settings over a period of time
  75416. */
  75417. _this.animations = [];
  75418. _this._imageProcessingConfigurationObserver = null;
  75419. // Values
  75420. _this._sharpenEnabled = false;
  75421. _this._bloomEnabled = false;
  75422. _this._depthOfFieldEnabled = false;
  75423. _this._depthOfFieldBlurLevel = BABYLON.DepthOfFieldEffectBlurLevel.Low;
  75424. _this._fxaaEnabled = false;
  75425. _this._imageProcessingEnabled = true;
  75426. _this._bloomScale = 0.5;
  75427. _this._chromaticAberrationEnabled = false;
  75428. _this._grainEnabled = false;
  75429. _this._buildAllowed = true;
  75430. _this._resizeObserver = null;
  75431. _this._hardwareScaleLevel = 1.0;
  75432. _this._bloomKernel = 64;
  75433. /**
  75434. * Specifies the weight of the bloom in the final rendering
  75435. */
  75436. _this._bloomWeight = 0.15;
  75437. /**
  75438. * Specifies the luma threshold for the area that will be blurred by the bloom
  75439. */
  75440. _this._bloomThreshold = 0.9;
  75441. _this._samples = 1;
  75442. _this._hasCleared = false;
  75443. _this._prevPostProcess = null;
  75444. _this._prevPrevPostProcess = null;
  75445. _this._cameras = cameras || [];
  75446. _this._originalCameras = _this._cameras.slice();
  75447. _this._buildAllowed = automaticBuild;
  75448. // Initialize
  75449. _this._scene = scene;
  75450. var caps = _this._scene.getEngine().getCaps();
  75451. _this._hdr = hdr && (caps.textureHalfFloatRender || caps.textureFloatRender);
  75452. // Misc
  75453. if (_this._hdr) {
  75454. if (caps.textureHalfFloatRender) {
  75455. _this._defaultPipelineTextureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  75456. }
  75457. else if (caps.textureFloatRender) {
  75458. _this._defaultPipelineTextureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  75459. }
  75460. }
  75461. else {
  75462. _this._defaultPipelineTextureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  75463. }
  75464. // Attach
  75465. scene.postProcessRenderPipelineManager.addPipeline(_this);
  75466. var engine = _this._scene.getEngine();
  75467. // Create post processes before hand so they can be modified before enabled.
  75468. // Block compilation flag is set to true to avoid compilation prior to use, these will be updated on first use in build pipeline.
  75469. _this.sharpen = new BABYLON.SharpenPostProcess("sharpen", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, _this._defaultPipelineTextureType, true);
  75470. _this._sharpenEffect = new BABYLON.PostProcessRenderEffect(engine, _this.SharpenPostProcessId, function () { return _this.sharpen; }, true);
  75471. _this.depthOfField = new BABYLON.DepthOfFieldEffect(_this._scene, null, _this._depthOfFieldBlurLevel, _this._defaultPipelineTextureType, true);
  75472. _this.bloom = new BABYLON.BloomEffect(_this._scene, _this._bloomScale, _this._bloomWeight, _this.bloomKernel, _this._defaultPipelineTextureType, true);
  75473. _this.chromaticAberration = new BABYLON.ChromaticAberrationPostProcess("ChromaticAberration", engine.getRenderWidth(), engine.getRenderHeight(), 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, _this._defaultPipelineTextureType, true);
  75474. _this._chromaticAberrationEffect = new BABYLON.PostProcessRenderEffect(engine, _this.ChromaticAberrationPostProcessId, function () { return _this.chromaticAberration; }, true);
  75475. _this.grain = new BABYLON.GrainPostProcess("Grain", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, _this._defaultPipelineTextureType, true);
  75476. _this._grainEffect = new BABYLON.PostProcessRenderEffect(engine, _this.GrainPostProcessId, function () { return _this.grain; }, true);
  75477. _this._resizeObserver = engine.onResizeObservable.add(function () {
  75478. _this._hardwareScaleLevel = engine.getHardwareScalingLevel();
  75479. _this.bloomKernel = _this.bloomKernel;
  75480. });
  75481. _this._imageProcessingConfigurationObserver = _this._scene.imageProcessingConfiguration.onUpdateParameters.add(function () {
  75482. _this.bloom._downscale._exposure = _this._scene.imageProcessingConfiguration.exposure;
  75483. });
  75484. _this._buildPipeline();
  75485. return _this;
  75486. }
  75487. Object.defineProperty(DefaultRenderingPipeline.prototype, "sharpenEnabled", {
  75488. get: function () {
  75489. return this._sharpenEnabled;
  75490. },
  75491. /**
  75492. * Enable or disable the sharpen process from the pipeline
  75493. */
  75494. set: function (enabled) {
  75495. if (this._sharpenEnabled === enabled) {
  75496. return;
  75497. }
  75498. this._sharpenEnabled = enabled;
  75499. this._buildPipeline();
  75500. },
  75501. enumerable: true,
  75502. configurable: true
  75503. });
  75504. Object.defineProperty(DefaultRenderingPipeline.prototype, "bloomKernel", {
  75505. /**
  75506. * Specifies the size of the bloom blur kernel, relative to the final output size
  75507. */
  75508. get: function () {
  75509. return this._bloomKernel;
  75510. },
  75511. set: function (value) {
  75512. this._bloomKernel = value;
  75513. this.bloom.kernel = value / this._hardwareScaleLevel;
  75514. },
  75515. enumerable: true,
  75516. configurable: true
  75517. });
  75518. Object.defineProperty(DefaultRenderingPipeline.prototype, "bloomWeight", {
  75519. get: function () {
  75520. return this._bloomWeight;
  75521. },
  75522. /**
  75523. * The strength of the bloom.
  75524. */
  75525. set: function (value) {
  75526. if (this._bloomWeight === value) {
  75527. return;
  75528. }
  75529. this.bloom.weight = value;
  75530. this._bloomWeight = value;
  75531. },
  75532. enumerable: true,
  75533. configurable: true
  75534. });
  75535. Object.defineProperty(DefaultRenderingPipeline.prototype, "bloomThreshold", {
  75536. get: function () {
  75537. return this._bloomThreshold;
  75538. },
  75539. /**
  75540. * The strength of the bloom.
  75541. */
  75542. set: function (value) {
  75543. if (this._bloomThreshold === value) {
  75544. return;
  75545. }
  75546. this.bloom.threshold = value;
  75547. this._bloomThreshold = value;
  75548. },
  75549. enumerable: true,
  75550. configurable: true
  75551. });
  75552. Object.defineProperty(DefaultRenderingPipeline.prototype, "bloomScale", {
  75553. get: function () {
  75554. return this._bloomScale;
  75555. },
  75556. /**
  75557. * The scale of the bloom, lower value will provide better performance.
  75558. */
  75559. set: function (value) {
  75560. if (this._bloomScale === value) {
  75561. return;
  75562. }
  75563. this._bloomScale = value;
  75564. // recreate bloom and dispose old as this setting is not dynamic
  75565. this._rebuildBloom();
  75566. this._buildPipeline();
  75567. },
  75568. enumerable: true,
  75569. configurable: true
  75570. });
  75571. Object.defineProperty(DefaultRenderingPipeline.prototype, "bloomEnabled", {
  75572. get: function () {
  75573. return this._bloomEnabled;
  75574. },
  75575. /**
  75576. * Enable or disable the bloom from the pipeline
  75577. */
  75578. set: function (enabled) {
  75579. if (this._bloomEnabled === enabled) {
  75580. return;
  75581. }
  75582. this._bloomEnabled = enabled;
  75583. this._buildPipeline();
  75584. },
  75585. enumerable: true,
  75586. configurable: true
  75587. });
  75588. DefaultRenderingPipeline.prototype._rebuildBloom = function () {
  75589. // recreate bloom and dispose old as this setting is not dynamic
  75590. var oldBloom = this.bloom;
  75591. this.bloom = new BABYLON.BloomEffect(this._scene, this.bloomScale, this._bloomWeight, this.bloomKernel, this._defaultPipelineTextureType, false);
  75592. this.bloom.threshold = oldBloom.threshold;
  75593. for (var i = 0; i < this._cameras.length; i++) {
  75594. oldBloom.disposeEffects(this._cameras[i]);
  75595. }
  75596. };
  75597. Object.defineProperty(DefaultRenderingPipeline.prototype, "depthOfFieldEnabled", {
  75598. /**
  75599. * If the depth of field is enabled.
  75600. */
  75601. get: function () {
  75602. return this._depthOfFieldEnabled;
  75603. },
  75604. set: function (enabled) {
  75605. if (this._depthOfFieldEnabled === enabled) {
  75606. return;
  75607. }
  75608. this._depthOfFieldEnabled = enabled;
  75609. this._buildPipeline();
  75610. },
  75611. enumerable: true,
  75612. configurable: true
  75613. });
  75614. Object.defineProperty(DefaultRenderingPipeline.prototype, "depthOfFieldBlurLevel", {
  75615. /**
  75616. * Blur level of the depth of field effect. (Higher blur will effect performance)
  75617. */
  75618. get: function () {
  75619. return this._depthOfFieldBlurLevel;
  75620. },
  75621. set: function (value) {
  75622. if (this._depthOfFieldBlurLevel === value) {
  75623. return;
  75624. }
  75625. this._depthOfFieldBlurLevel = value;
  75626. // recreate dof and dispose old as this setting is not dynamic
  75627. var oldDof = this.depthOfField;
  75628. this.depthOfField = new BABYLON.DepthOfFieldEffect(this._scene, null, this._depthOfFieldBlurLevel, this._defaultPipelineTextureType, false);
  75629. this.depthOfField.focalLength = oldDof.focalLength;
  75630. this.depthOfField.focusDistance = oldDof.focusDistance;
  75631. this.depthOfField.fStop = oldDof.fStop;
  75632. this.depthOfField.lensSize = oldDof.lensSize;
  75633. for (var i = 0; i < this._cameras.length; i++) {
  75634. oldDof.disposeEffects(this._cameras[i]);
  75635. }
  75636. this._buildPipeline();
  75637. },
  75638. enumerable: true,
  75639. configurable: true
  75640. });
  75641. Object.defineProperty(DefaultRenderingPipeline.prototype, "fxaaEnabled", {
  75642. get: function () {
  75643. return this._fxaaEnabled;
  75644. },
  75645. /**
  75646. * If the anti aliasing is enabled.
  75647. */
  75648. set: function (enabled) {
  75649. if (this._fxaaEnabled === enabled) {
  75650. return;
  75651. }
  75652. this._fxaaEnabled = enabled;
  75653. this._buildPipeline();
  75654. },
  75655. enumerable: true,
  75656. configurable: true
  75657. });
  75658. Object.defineProperty(DefaultRenderingPipeline.prototype, "samples", {
  75659. get: function () {
  75660. return this._samples;
  75661. },
  75662. /**
  75663. * MSAA sample count, setting this to 4 will provide 4x anti aliasing. (default: 1)
  75664. */
  75665. set: function (sampleCount) {
  75666. if (this._samples === sampleCount) {
  75667. return;
  75668. }
  75669. this._samples = sampleCount;
  75670. this._buildPipeline();
  75671. },
  75672. enumerable: true,
  75673. configurable: true
  75674. });
  75675. Object.defineProperty(DefaultRenderingPipeline.prototype, "imageProcessingEnabled", {
  75676. get: function () {
  75677. return this._imageProcessingEnabled;
  75678. },
  75679. /**
  75680. * If image processing is enabled.
  75681. */
  75682. set: function (enabled) {
  75683. if (this._imageProcessingEnabled === enabled) {
  75684. return;
  75685. }
  75686. this._imageProcessingEnabled = enabled;
  75687. this._buildPipeline();
  75688. },
  75689. enumerable: true,
  75690. configurable: true
  75691. });
  75692. Object.defineProperty(DefaultRenderingPipeline.prototype, "chromaticAberrationEnabled", {
  75693. get: function () {
  75694. return this._chromaticAberrationEnabled;
  75695. },
  75696. /**
  75697. * Enable or disable the chromaticAberration process from the pipeline
  75698. */
  75699. set: function (enabled) {
  75700. if (this._chromaticAberrationEnabled === enabled) {
  75701. return;
  75702. }
  75703. this._chromaticAberrationEnabled = enabled;
  75704. this._buildPipeline();
  75705. },
  75706. enumerable: true,
  75707. configurable: true
  75708. });
  75709. Object.defineProperty(DefaultRenderingPipeline.prototype, "grainEnabled", {
  75710. get: function () {
  75711. return this._grainEnabled;
  75712. },
  75713. /**
  75714. * Enable or disable the grain process from the pipeline
  75715. */
  75716. set: function (enabled) {
  75717. if (this._grainEnabled === enabled) {
  75718. return;
  75719. }
  75720. this._grainEnabled = enabled;
  75721. this._buildPipeline();
  75722. },
  75723. enumerable: true,
  75724. configurable: true
  75725. });
  75726. /**
  75727. * Force the compilation of the entire pipeline.
  75728. */
  75729. DefaultRenderingPipeline.prototype.prepare = function () {
  75730. var previousState = this._buildAllowed;
  75731. this._buildAllowed = true;
  75732. this._buildPipeline();
  75733. this._buildAllowed = previousState;
  75734. };
  75735. DefaultRenderingPipeline.prototype._setAutoClearAndTextureSharing = function (postProcess, skipTextureSharing) {
  75736. if (skipTextureSharing === void 0) { skipTextureSharing = false; }
  75737. if (this._hasCleared) {
  75738. postProcess.autoClear = false;
  75739. }
  75740. else {
  75741. postProcess.autoClear = true;
  75742. this._scene.autoClear = false;
  75743. this._hasCleared = true;
  75744. }
  75745. if (!skipTextureSharing) {
  75746. if (this._prevPrevPostProcess) {
  75747. postProcess.shareOutputWith(this._prevPrevPostProcess);
  75748. }
  75749. else {
  75750. postProcess.useOwnOutput();
  75751. }
  75752. if (this._prevPostProcess) {
  75753. this._prevPrevPostProcess = this._prevPostProcess;
  75754. }
  75755. this._prevPostProcess = postProcess;
  75756. }
  75757. };
  75758. DefaultRenderingPipeline.prototype._buildPipeline = function () {
  75759. var _this = this;
  75760. if (!this._buildAllowed) {
  75761. return;
  75762. }
  75763. this._scene.autoClear = true;
  75764. var engine = this._scene.getEngine();
  75765. this._disposePostProcesses();
  75766. if (this._cameras !== null) {
  75767. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._cameras);
  75768. // get back cameras to be used to reattach pipeline
  75769. this._cameras = this._originalCameras.slice();
  75770. }
  75771. this._reset();
  75772. this._prevPostProcess = null;
  75773. this._prevPrevPostProcess = null;
  75774. this._hasCleared = false;
  75775. if (this.depthOfFieldEnabled) {
  75776. var depthTexture = this._scene.enableDepthRenderer(this._cameras[0]).getDepthMap();
  75777. this.depthOfField.depthTexture = depthTexture;
  75778. if (!this.depthOfField._isReady()) {
  75779. this.depthOfField._updateEffects();
  75780. }
  75781. this.addEffect(this.depthOfField);
  75782. this._setAutoClearAndTextureSharing(this.depthOfField._effects[0], true);
  75783. }
  75784. if (this.bloomEnabled) {
  75785. if (!this.bloom._isReady()) {
  75786. this.bloom._updateEffects();
  75787. }
  75788. this.addEffect(this.bloom);
  75789. this._setAutoClearAndTextureSharing(this.bloom._effects[0], true);
  75790. }
  75791. if (this._imageProcessingEnabled) {
  75792. this.imageProcessing = new BABYLON.ImageProcessingPostProcess("imageProcessing", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, this._defaultPipelineTextureType);
  75793. if (this._hdr) {
  75794. this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.ImageProcessingPostProcessId, function () { return _this.imageProcessing; }, true));
  75795. this._setAutoClearAndTextureSharing(this.imageProcessing);
  75796. }
  75797. else {
  75798. this._scene.imageProcessingConfiguration.applyByPostProcess = false;
  75799. }
  75800. }
  75801. if (this.sharpenEnabled) {
  75802. if (!this.sharpen.isReady()) {
  75803. this.sharpen.updateEffect();
  75804. }
  75805. this.addEffect(this._sharpenEffect);
  75806. this._setAutoClearAndTextureSharing(this.sharpen);
  75807. }
  75808. if (this.grainEnabled) {
  75809. if (!this.grain.isReady()) {
  75810. this.grain.updateEffect();
  75811. }
  75812. this.addEffect(this._grainEffect);
  75813. this._setAutoClearAndTextureSharing(this.grain);
  75814. }
  75815. if (this.chromaticAberrationEnabled) {
  75816. if (!this.chromaticAberration.isReady()) {
  75817. this.chromaticAberration.updateEffect();
  75818. }
  75819. this.addEffect(this._chromaticAberrationEffect);
  75820. this._setAutoClearAndTextureSharing(this.chromaticAberration);
  75821. }
  75822. if (this.fxaaEnabled) {
  75823. this.fxaa = new BABYLON.FxaaPostProcess("fxaa", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, this._defaultPipelineTextureType);
  75824. this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.FxaaPostProcessId, function () { return _this.fxaa; }, true));
  75825. this._setAutoClearAndTextureSharing(this.fxaa, true);
  75826. }
  75827. if (this._cameras !== null) {
  75828. this._scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(this._name, this._cameras);
  75829. }
  75830. if (!this._enableMSAAOnFirstPostProcess(this.samples) && this.samples > 1) {
  75831. BABYLON.Tools.Warn("MSAA failed to enable, MSAA is only supported in browsers that support webGL >= 2.0");
  75832. }
  75833. };
  75834. DefaultRenderingPipeline.prototype._disposePostProcesses = function (disposeNonRecreated) {
  75835. if (disposeNonRecreated === void 0) { disposeNonRecreated = false; }
  75836. for (var i = 0; i < this._cameras.length; i++) {
  75837. var camera = this._cameras[i];
  75838. if (this.imageProcessing) {
  75839. this.imageProcessing.dispose(camera);
  75840. }
  75841. if (this.fxaa) {
  75842. this.fxaa.dispose(camera);
  75843. }
  75844. // These are created in the constructor and should not be disposed on every pipeline change
  75845. if (disposeNonRecreated) {
  75846. if (this.sharpen) {
  75847. this.sharpen.dispose(camera);
  75848. }
  75849. if (this.depthOfField) {
  75850. this.depthOfField.disposeEffects(camera);
  75851. }
  75852. if (this.bloom) {
  75853. this.bloom.disposeEffects(camera);
  75854. }
  75855. if (this.chromaticAberration) {
  75856. this.chromaticAberration.dispose(camera);
  75857. }
  75858. if (this.grain) {
  75859. this.grain.dispose(camera);
  75860. }
  75861. }
  75862. }
  75863. this.imageProcessing = null;
  75864. this.fxaa = null;
  75865. if (disposeNonRecreated) {
  75866. this.sharpen = null;
  75867. this._sharpenEffect = null;
  75868. this.depthOfField = null;
  75869. this.bloom = null;
  75870. this.chromaticAberration = null;
  75871. this._chromaticAberrationEffect = null;
  75872. this.grain = null;
  75873. this._grainEffect = null;
  75874. }
  75875. };
  75876. /**
  75877. * Dispose of the pipeline and stop all post processes
  75878. */
  75879. DefaultRenderingPipeline.prototype.dispose = function () {
  75880. this._disposePostProcesses(true);
  75881. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._cameras);
  75882. this._scene.autoClear = true;
  75883. if (this._resizeObserver) {
  75884. this._scene.getEngine().onResizeObservable.remove(this._resizeObserver);
  75885. this._resizeObserver = null;
  75886. }
  75887. this._scene.imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingConfigurationObserver);
  75888. _super.prototype.dispose.call(this);
  75889. };
  75890. /**
  75891. * Serialize the rendering pipeline (Used when exporting)
  75892. * @returns the serialized object
  75893. */
  75894. DefaultRenderingPipeline.prototype.serialize = function () {
  75895. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  75896. serializationObject.customType = "DefaultRenderingPipeline";
  75897. return serializationObject;
  75898. };
  75899. /**
  75900. * Parse the serialized pipeline
  75901. * @param source Source pipeline.
  75902. * @param scene The scene to load the pipeline to.
  75903. * @param rootUrl The URL of the serialized pipeline.
  75904. * @returns An instantiated pipeline from the serialized object.
  75905. */
  75906. DefaultRenderingPipeline.Parse = function (source, scene, rootUrl) {
  75907. return BABYLON.SerializationHelper.Parse(function () { return new DefaultRenderingPipeline(source._name, source._name._hdr, scene); }, source, scene, rootUrl);
  75908. };
  75909. __decorate([
  75910. BABYLON.serialize()
  75911. ], DefaultRenderingPipeline.prototype, "sharpenEnabled", null);
  75912. __decorate([
  75913. BABYLON.serialize()
  75914. ], DefaultRenderingPipeline.prototype, "bloomKernel", null);
  75915. __decorate([
  75916. BABYLON.serialize()
  75917. ], DefaultRenderingPipeline.prototype, "_bloomWeight", void 0);
  75918. __decorate([
  75919. BABYLON.serialize()
  75920. ], DefaultRenderingPipeline.prototype, "_bloomThreshold", void 0);
  75921. __decorate([
  75922. BABYLON.serialize()
  75923. ], DefaultRenderingPipeline.prototype, "_hdr", void 0);
  75924. __decorate([
  75925. BABYLON.serialize()
  75926. ], DefaultRenderingPipeline.prototype, "bloomWeight", null);
  75927. __decorate([
  75928. BABYLON.serialize()
  75929. ], DefaultRenderingPipeline.prototype, "bloomThreshold", null);
  75930. __decorate([
  75931. BABYLON.serialize()
  75932. ], DefaultRenderingPipeline.prototype, "bloomScale", null);
  75933. __decorate([
  75934. BABYLON.serialize()
  75935. ], DefaultRenderingPipeline.prototype, "bloomEnabled", null);
  75936. __decorate([
  75937. BABYLON.serialize()
  75938. ], DefaultRenderingPipeline.prototype, "depthOfFieldEnabled", null);
  75939. __decorate([
  75940. BABYLON.serialize()
  75941. ], DefaultRenderingPipeline.prototype, "depthOfFieldBlurLevel", null);
  75942. __decorate([
  75943. BABYLON.serialize()
  75944. ], DefaultRenderingPipeline.prototype, "fxaaEnabled", null);
  75945. __decorate([
  75946. BABYLON.serialize()
  75947. ], DefaultRenderingPipeline.prototype, "samples", null);
  75948. __decorate([
  75949. BABYLON.serialize()
  75950. ], DefaultRenderingPipeline.prototype, "imageProcessingEnabled", null);
  75951. __decorate([
  75952. BABYLON.serialize()
  75953. ], DefaultRenderingPipeline.prototype, "chromaticAberrationEnabled", null);
  75954. __decorate([
  75955. BABYLON.serialize()
  75956. ], DefaultRenderingPipeline.prototype, "grainEnabled", null);
  75957. return DefaultRenderingPipeline;
  75958. }(BABYLON.PostProcessRenderPipeline));
  75959. BABYLON.DefaultRenderingPipeline = DefaultRenderingPipeline;
  75960. })(BABYLON || (BABYLON = {}));
  75961. //# sourceMappingURL=babylon.defaultRenderingPipeline.js.map
  75962. var BABYLON;
  75963. (function (BABYLON) {
  75964. /**
  75965. * This renderer is helpfull to fill one of the render target with a geometry buffer.
  75966. */
  75967. var GeometryBufferRenderer = /** @class */ (function () {
  75968. /**
  75969. * Creates a new G Buffer for the scene
  75970. * @param scene The scene the buffer belongs to
  75971. * @param ratio How big is the buffer related to the main canvas.
  75972. */
  75973. function GeometryBufferRenderer(scene, ratio) {
  75974. if (ratio === void 0) { ratio = 1; }
  75975. this._enablePosition = false;
  75976. this._scene = scene;
  75977. this._ratio = ratio;
  75978. // Render target
  75979. this._createRenderTargets();
  75980. }
  75981. Object.defineProperty(GeometryBufferRenderer.prototype, "renderList", {
  75982. /**
  75983. * Set the render list (meshes to be rendered) used in the G buffer.
  75984. */
  75985. set: function (meshes) {
  75986. this._multiRenderTarget.renderList = meshes;
  75987. },
  75988. enumerable: true,
  75989. configurable: true
  75990. });
  75991. Object.defineProperty(GeometryBufferRenderer.prototype, "isSupported", {
  75992. /**
  75993. * Gets wether or not G buffer are supported by the running hardware.
  75994. * This requires draw buffer supports
  75995. */
  75996. get: function () {
  75997. return this._multiRenderTarget.isSupported;
  75998. },
  75999. enumerable: true,
  76000. configurable: true
  76001. });
  76002. Object.defineProperty(GeometryBufferRenderer.prototype, "enablePosition", {
  76003. /**
  76004. * Gets wether or not position are enabled for the G buffer.
  76005. */
  76006. get: function () {
  76007. return this._enablePosition;
  76008. },
  76009. /**
  76010. * Sets wether or not position are enabled for the G buffer.
  76011. */
  76012. set: function (enable) {
  76013. this._enablePosition = enable;
  76014. this.dispose();
  76015. this._createRenderTargets();
  76016. },
  76017. enumerable: true,
  76018. configurable: true
  76019. });
  76020. Object.defineProperty(GeometryBufferRenderer.prototype, "scene", {
  76021. /**
  76022. * Gets the scene associated with the buffer.
  76023. */
  76024. get: function () {
  76025. return this._scene;
  76026. },
  76027. enumerable: true,
  76028. configurable: true
  76029. });
  76030. Object.defineProperty(GeometryBufferRenderer.prototype, "ratio", {
  76031. /**
  76032. * Gets the ratio used by the buffer during its creation.
  76033. * How big is the buffer related to the main canvas.
  76034. */
  76035. get: function () {
  76036. return this._ratio;
  76037. },
  76038. enumerable: true,
  76039. configurable: true
  76040. });
  76041. /**
  76042. * Checks wether everything is ready to render a submesh to the G buffer.
  76043. * @param subMesh the submesh to check readiness for
  76044. * @param useInstances is the mesh drawn using instance or not
  76045. * @returns true if ready otherwise false
  76046. */
  76047. GeometryBufferRenderer.prototype.isReady = function (subMesh, useInstances) {
  76048. var material = subMesh.getMaterial();
  76049. if (material && material.disableDepthWrite) {
  76050. return false;
  76051. }
  76052. var defines = [];
  76053. var attribs = [BABYLON.VertexBuffer.PositionKind, BABYLON.VertexBuffer.NormalKind];
  76054. var mesh = subMesh.getMesh();
  76055. // Alpha test
  76056. if (material && material.needAlphaTesting()) {
  76057. defines.push("#define ALPHATEST");
  76058. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  76059. attribs.push(BABYLON.VertexBuffer.UVKind);
  76060. defines.push("#define UV1");
  76061. }
  76062. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  76063. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  76064. defines.push("#define UV2");
  76065. }
  76066. }
  76067. // Buffers
  76068. if (this._enablePosition) {
  76069. defines.push("#define POSITION");
  76070. }
  76071. // Bones
  76072. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  76073. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  76074. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  76075. if (mesh.numBoneInfluencers > 4) {
  76076. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  76077. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  76078. }
  76079. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  76080. defines.push("#define BonesPerMesh " + (mesh.skeleton ? mesh.skeleton.bones.length + 1 : 0));
  76081. }
  76082. else {
  76083. defines.push("#define NUM_BONE_INFLUENCERS 0");
  76084. }
  76085. // Instances
  76086. if (useInstances) {
  76087. defines.push("#define INSTANCES");
  76088. attribs.push("world0");
  76089. attribs.push("world1");
  76090. attribs.push("world2");
  76091. attribs.push("world3");
  76092. }
  76093. // Get correct effect
  76094. var join = defines.join("\n");
  76095. if (this._cachedDefines !== join) {
  76096. this._cachedDefines = join;
  76097. this._effect = this._scene.getEngine().createEffect("geometry", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "view"], ["diffuseSampler"], join, undefined, undefined, undefined, { buffersCount: this._enablePosition ? 3 : 2 });
  76098. }
  76099. return this._effect.isReady();
  76100. };
  76101. /**
  76102. * Gets the current underlying G Buffer.
  76103. * @returns the buffer
  76104. */
  76105. GeometryBufferRenderer.prototype.getGBuffer = function () {
  76106. return this._multiRenderTarget;
  76107. };
  76108. Object.defineProperty(GeometryBufferRenderer.prototype, "samples", {
  76109. /**
  76110. * Gets the number of samples used to render the buffer (anti aliasing).
  76111. */
  76112. get: function () {
  76113. return this._multiRenderTarget.samples;
  76114. },
  76115. /**
  76116. * Sets the number of samples used to render the buffer (anti aliasing).
  76117. */
  76118. set: function (value) {
  76119. this._multiRenderTarget.samples = value;
  76120. },
  76121. enumerable: true,
  76122. configurable: true
  76123. });
  76124. /**
  76125. * Disposes the renderer and frees up associated resources.
  76126. */
  76127. GeometryBufferRenderer.prototype.dispose = function () {
  76128. this.getGBuffer().dispose();
  76129. };
  76130. GeometryBufferRenderer.prototype._createRenderTargets = function () {
  76131. var _this = this;
  76132. var engine = this._scene.getEngine();
  76133. var count = this._enablePosition ? 3 : 2;
  76134. 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 });
  76135. if (!this.isSupported) {
  76136. return;
  76137. }
  76138. this._multiRenderTarget.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  76139. this._multiRenderTarget.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  76140. this._multiRenderTarget.refreshRate = 1;
  76141. this._multiRenderTarget.renderParticles = false;
  76142. this._multiRenderTarget.renderList = null;
  76143. // set default depth value to 1.0 (far away)
  76144. this._multiRenderTarget.onClearObservable.add(function (engine) {
  76145. engine.clear(new BABYLON.Color4(0.0, 0.0, 0.0, 1.0), true, true, true);
  76146. });
  76147. // Custom render function
  76148. var renderSubMesh = function (subMesh) {
  76149. var mesh = subMesh.getRenderingMesh();
  76150. var scene = _this._scene;
  76151. var engine = scene.getEngine();
  76152. var material = subMesh.getMaterial();
  76153. if (!material) {
  76154. return;
  76155. }
  76156. // Culling
  76157. engine.setState(material.backFaceCulling, 0, false, scene.useRightHandedSystem);
  76158. // Managing instances
  76159. var batch = mesh._getInstancesRenderList(subMesh._id);
  76160. if (batch.mustReturn) {
  76161. return;
  76162. }
  76163. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null);
  76164. if (_this.isReady(subMesh, hardwareInstancedRendering)) {
  76165. engine.enableEffect(_this._effect);
  76166. mesh._bind(subMesh, _this._effect, BABYLON.Material.TriangleFillMode);
  76167. _this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
  76168. _this._effect.setMatrix("view", scene.getViewMatrix());
  76169. // Alpha test
  76170. if (material && material.needAlphaTesting()) {
  76171. var alphaTexture = material.getAlphaTestTexture();
  76172. if (alphaTexture) {
  76173. _this._effect.setTexture("diffuseSampler", alphaTexture);
  76174. _this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  76175. }
  76176. }
  76177. // Bones
  76178. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  76179. _this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  76180. }
  76181. // Draw
  76182. mesh._processRendering(subMesh, _this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._effect.setMatrix("world", world); });
  76183. }
  76184. };
  76185. this._multiRenderTarget.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes, depthOnlySubMeshes) {
  76186. var index;
  76187. if (depthOnlySubMeshes.length) {
  76188. engine.setColorWrite(false);
  76189. for (index = 0; index < depthOnlySubMeshes.length; index++) {
  76190. renderSubMesh(depthOnlySubMeshes.data[index]);
  76191. }
  76192. engine.setColorWrite(true);
  76193. }
  76194. for (index = 0; index < opaqueSubMeshes.length; index++) {
  76195. renderSubMesh(opaqueSubMeshes.data[index]);
  76196. }
  76197. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  76198. renderSubMesh(alphaTestSubMeshes.data[index]);
  76199. }
  76200. };
  76201. };
  76202. return GeometryBufferRenderer;
  76203. }());
  76204. BABYLON.GeometryBufferRenderer = GeometryBufferRenderer;
  76205. })(BABYLON || (BABYLON = {}));
  76206. //# sourceMappingURL=babylon.geometryBufferRenderer.js.map
  76207. var BABYLON;
  76208. (function (BABYLON) {
  76209. var RefractionPostProcess = /** @class */ (function (_super) {
  76210. __extends(RefractionPostProcess, _super);
  76211. function RefractionPostProcess(name, refractionTextureUrl, color, depth, colorLevel, options, camera, samplingMode, engine, reusable) {
  76212. var _this = _super.call(this, name, "refraction", ["baseColor", "depth", "colorLevel"], ["refractionSampler"], options, camera, samplingMode, engine, reusable) || this;
  76213. _this.color = color;
  76214. _this.depth = depth;
  76215. _this.colorLevel = colorLevel;
  76216. _this._ownRefractionTexture = true;
  76217. _this.onActivateObservable.add(function (cam) {
  76218. _this._refTexture = _this._refTexture || new BABYLON.Texture(refractionTextureUrl, cam.getScene());
  76219. });
  76220. _this.onApplyObservable.add(function (effect) {
  76221. effect.setColor3("baseColor", _this.color);
  76222. effect.setFloat("depth", _this.depth);
  76223. effect.setFloat("colorLevel", _this.colorLevel);
  76224. effect.setTexture("refractionSampler", _this._refTexture);
  76225. });
  76226. return _this;
  76227. }
  76228. Object.defineProperty(RefractionPostProcess.prototype, "refractionTexture", {
  76229. /**
  76230. * Gets or sets the refraction texture
  76231. * Please note that you are responsible for disposing the texture if you set it manually
  76232. */
  76233. get: function () {
  76234. return this._refTexture;
  76235. },
  76236. set: function (value) {
  76237. if (this._refTexture && this._ownRefractionTexture) {
  76238. this._refTexture.dispose();
  76239. }
  76240. this._refTexture = value;
  76241. this._ownRefractionTexture = false;
  76242. },
  76243. enumerable: true,
  76244. configurable: true
  76245. });
  76246. // Methods
  76247. RefractionPostProcess.prototype.dispose = function (camera) {
  76248. if (this._refTexture && this._ownRefractionTexture) {
  76249. this._refTexture.dispose();
  76250. this._refTexture = null;
  76251. }
  76252. _super.prototype.dispose.call(this, camera);
  76253. };
  76254. return RefractionPostProcess;
  76255. }(BABYLON.PostProcess));
  76256. BABYLON.RefractionPostProcess = RefractionPostProcess;
  76257. })(BABYLON || (BABYLON = {}));
  76258. //# sourceMappingURL=babylon.refractionPostProcess.js.map
  76259. var BABYLON;
  76260. (function (BABYLON) {
  76261. var BlackAndWhitePostProcess = /** @class */ (function (_super) {
  76262. __extends(BlackAndWhitePostProcess, _super);
  76263. function BlackAndWhitePostProcess(name, options, camera, samplingMode, engine, reusable) {
  76264. var _this = _super.call(this, name, "blackAndWhite", ["degree"], null, options, camera, samplingMode, engine, reusable) || this;
  76265. _this.degree = 1;
  76266. _this.onApplyObservable.add(function (effect) {
  76267. effect.setFloat("degree", _this.degree);
  76268. });
  76269. return _this;
  76270. }
  76271. return BlackAndWhitePostProcess;
  76272. }(BABYLON.PostProcess));
  76273. BABYLON.BlackAndWhitePostProcess = BlackAndWhitePostProcess;
  76274. })(BABYLON || (BABYLON = {}));
  76275. //# sourceMappingURL=babylon.blackAndWhitePostProcess.js.map
  76276. var BABYLON;
  76277. (function (BABYLON) {
  76278. /**
  76279. * The ConvolutionPostProcess applies a 3x3 kernel to every pixel of the
  76280. * input texture to perform effects such as edge detection or sharpening
  76281. * See http://en.wikipedia.org/wiki/Kernel_(image_processing)
  76282. */
  76283. var ConvolutionPostProcess = /** @class */ (function (_super) {
  76284. __extends(ConvolutionPostProcess, _super);
  76285. /**
  76286. * Creates a new instance ConvolutionPostProcess
  76287. * @param name The name of the effect.
  76288. * @param kernel Array of 9 values corrisponding to the 3x3 kernel to be applied
  76289. * @param options The required width/height ratio to downsize to before computing the render pass.
  76290. * @param camera The camera to apply the render pass to.
  76291. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  76292. * @param engine The engine which the post process will be applied. (default: current engine)
  76293. * @param reusable If the post process can be reused on the same frame. (default: false)
  76294. * @param textureType Type of textures used when performing the post process. (default: 0)
  76295. */
  76296. function ConvolutionPostProcess(name, /** Array of 9 values corrisponding to the 3x3 kernel to be applied */ kernel, options, camera, samplingMode, engine, reusable, textureType) {
  76297. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  76298. var _this = _super.call(this, name, "convolution", ["kernel", "screenSize"], null, options, camera, samplingMode, engine, reusable, null, textureType) || this;
  76299. _this.kernel = kernel;
  76300. _this.onApply = function (effect) {
  76301. effect.setFloat2("screenSize", _this.width, _this.height);
  76302. effect.setArray("kernel", _this.kernel);
  76303. };
  76304. return _this;
  76305. }
  76306. // Statics
  76307. /**
  76308. * Edge detection 0 see https://en.wikipedia.org/wiki/Kernel_(image_processing)
  76309. */
  76310. ConvolutionPostProcess.EdgeDetect0Kernel = [1, 0, -1, 0, 0, 0, -1, 0, 1];
  76311. /**
  76312. * Edge detection 1 see https://en.wikipedia.org/wiki/Kernel_(image_processing)
  76313. */
  76314. ConvolutionPostProcess.EdgeDetect1Kernel = [0, 1, 0, 1, -4, 1, 0, 1, 0];
  76315. /**
  76316. * Edge detection 2 see https://en.wikipedia.org/wiki/Kernel_(image_processing)
  76317. */
  76318. ConvolutionPostProcess.EdgeDetect2Kernel = [-1, -1, -1, -1, 8, -1, -1, -1, -1];
  76319. /**
  76320. * Kernel to sharpen an image see https://en.wikipedia.org/wiki/Kernel_(image_processing)
  76321. */
  76322. ConvolutionPostProcess.SharpenKernel = [0, -1, 0, -1, 5, -1, 0, -1, 0];
  76323. /**
  76324. * Kernel to emboss an image see https://en.wikipedia.org/wiki/Kernel_(image_processing)
  76325. */
  76326. ConvolutionPostProcess.EmbossKernel = [-2, -1, 0, -1, 1, 1, 0, 1, 2];
  76327. /**
  76328. * Kernel to blur an image see https://en.wikipedia.org/wiki/Kernel_(image_processing)
  76329. */
  76330. ConvolutionPostProcess.GaussianKernel = [0, 1, 0, 1, 1, 1, 0, 1, 0];
  76331. return ConvolutionPostProcess;
  76332. }(BABYLON.PostProcess));
  76333. BABYLON.ConvolutionPostProcess = ConvolutionPostProcess;
  76334. })(BABYLON || (BABYLON = {}));
  76335. //# sourceMappingURL=babylon.convolutionPostProcess.js.map
  76336. var BABYLON;
  76337. (function (BABYLON) {
  76338. var FilterPostProcess = /** @class */ (function (_super) {
  76339. __extends(FilterPostProcess, _super);
  76340. function FilterPostProcess(name, kernelMatrix, options, camera, samplingMode, engine, reusable) {
  76341. var _this = _super.call(this, name, "filter", ["kernelMatrix"], null, options, camera, samplingMode, engine, reusable) || this;
  76342. _this.kernelMatrix = kernelMatrix;
  76343. _this.onApply = function (effect) {
  76344. effect.setMatrix("kernelMatrix", _this.kernelMatrix);
  76345. };
  76346. return _this;
  76347. }
  76348. return FilterPostProcess;
  76349. }(BABYLON.PostProcess));
  76350. BABYLON.FilterPostProcess = FilterPostProcess;
  76351. })(BABYLON || (BABYLON = {}));
  76352. //# sourceMappingURL=babylon.filterPostProcess.js.map
  76353. var BABYLON;
  76354. (function (BABYLON) {
  76355. // Inspired by http://http.developer.nvidia.com/GPUGems3/gpugems3_ch13.html
  76356. var VolumetricLightScatteringPostProcess = /** @class */ (function (_super) {
  76357. __extends(VolumetricLightScatteringPostProcess, _super);
  76358. /**
  76359. * @constructor
  76360. * @param {string} name - The post-process name
  76361. * @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)
  76362. * @param {BABYLON.Camera} camera - The camera that the post-process will be attached to
  76363. * @param {BABYLON.Mesh} mesh - The mesh used to create the light scattering
  76364. * @param {number} samples - The post-process quality, default 100
  76365. * @param {number} samplingMode - The post-process filtering mode
  76366. * @param {BABYLON.Engine} engine - The babylon engine
  76367. * @param {boolean} reusable - If the post-process is reusable
  76368. * @param {BABYLON.Scene} scene - The constructor needs a scene reference to initialize internal components. If "camera" is null (RenderPipelineà, "scene" must be provided
  76369. */
  76370. function VolumetricLightScatteringPostProcess(name, ratio, camera, mesh, samples, samplingMode, engine, reusable, scene) {
  76371. if (samples === void 0) { samples = 100; }
  76372. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  76373. 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;
  76374. _this._screenCoordinates = BABYLON.Vector2.Zero();
  76375. /**
  76376. * Custom position of the mesh. Used if "useCustomMeshPosition" is set to "true"
  76377. */
  76378. _this.customMeshPosition = BABYLON.Vector3.Zero();
  76379. /**
  76380. * Set if the post-process should use a custom position for the light source (true) or the internal mesh position (false)
  76381. */
  76382. _this.useCustomMeshPosition = false;
  76383. /**
  76384. * If the post-process should inverse the light scattering direction
  76385. */
  76386. _this.invert = true;
  76387. /**
  76388. * Array containing the excluded meshes not rendered in the internal pass
  76389. */
  76390. _this.excludedMeshes = new Array();
  76391. /**
  76392. * Controls the overall intensity of the post-process
  76393. */
  76394. _this.exposure = 0.3;
  76395. /**
  76396. * Dissipates each sample's contribution in range [0, 1]
  76397. */
  76398. _this.decay = 0.96815;
  76399. /**
  76400. * Controls the overall intensity of each sample
  76401. */
  76402. _this.weight = 0.58767;
  76403. /**
  76404. * Controls the density of each sample
  76405. */
  76406. _this.density = 0.926;
  76407. scene = ((camera === null) ? scene : camera.getScene()); // parameter "scene" can be null.
  76408. engine = scene.getEngine();
  76409. _this._viewPort = new BABYLON.Viewport(0, 0, 1, 1).toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
  76410. // Configure mesh
  76411. _this.mesh = ((mesh !== null) ? mesh : VolumetricLightScatteringPostProcess.CreateDefaultMesh("VolumetricLightScatteringMesh", scene));
  76412. // Configure
  76413. _this._createPass(scene, ratio.passRatio || ratio);
  76414. _this.onActivate = function (camera) {
  76415. if (!_this.isSupported) {
  76416. _this.dispose(camera);
  76417. }
  76418. _this.onActivate = null;
  76419. };
  76420. _this.onApplyObservable.add(function (effect) {
  76421. _this._updateMeshScreenCoordinates(scene);
  76422. effect.setTexture("lightScatteringSampler", _this._volumetricLightScatteringRTT);
  76423. effect.setFloat("exposure", _this.exposure);
  76424. effect.setFloat("decay", _this.decay);
  76425. effect.setFloat("weight", _this.weight);
  76426. effect.setFloat("density", _this.density);
  76427. effect.setVector2("meshPositionOnScreen", _this._screenCoordinates);
  76428. });
  76429. return _this;
  76430. }
  76431. Object.defineProperty(VolumetricLightScatteringPostProcess.prototype, "useDiffuseColor", {
  76432. get: function () {
  76433. BABYLON.Tools.Warn("VolumetricLightScatteringPostProcess.useDiffuseColor is no longer used, use the mesh material directly instead");
  76434. return false;
  76435. },
  76436. set: function (useDiffuseColor) {
  76437. BABYLON.Tools.Warn("VolumetricLightScatteringPostProcess.useDiffuseColor is no longer used, use the mesh material directly instead");
  76438. },
  76439. enumerable: true,
  76440. configurable: true
  76441. });
  76442. VolumetricLightScatteringPostProcess.prototype.getClassName = function () {
  76443. return "VolumetricLightScatteringPostProcess";
  76444. };
  76445. VolumetricLightScatteringPostProcess.prototype._isReady = function (subMesh, useInstances) {
  76446. var mesh = subMesh.getMesh();
  76447. // Render this.mesh as default
  76448. if (mesh === this.mesh && mesh.material) {
  76449. return mesh.material.isReady(mesh);
  76450. }
  76451. var defines = [];
  76452. var attribs = [BABYLON.VertexBuffer.PositionKind];
  76453. var material = subMesh.getMaterial();
  76454. // Alpha test
  76455. if (material) {
  76456. if (material.needAlphaTesting()) {
  76457. defines.push("#define ALPHATEST");
  76458. }
  76459. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  76460. attribs.push(BABYLON.VertexBuffer.UVKind);
  76461. defines.push("#define UV1");
  76462. }
  76463. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  76464. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  76465. defines.push("#define UV2");
  76466. }
  76467. }
  76468. // Bones
  76469. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  76470. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  76471. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  76472. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  76473. defines.push("#define BonesPerMesh " + (mesh.skeleton ? (mesh.skeleton.bones.length + 1) : 0));
  76474. }
  76475. else {
  76476. defines.push("#define NUM_BONE_INFLUENCERS 0");
  76477. }
  76478. // Instances
  76479. if (useInstances) {
  76480. defines.push("#define INSTANCES");
  76481. attribs.push("world0");
  76482. attribs.push("world1");
  76483. attribs.push("world2");
  76484. attribs.push("world3");
  76485. }
  76486. // Get correct effect
  76487. var join = defines.join("\n");
  76488. if (this._cachedDefines !== join) {
  76489. this._cachedDefines = join;
  76490. this._volumetricLightScatteringPass = mesh.getScene().getEngine().createEffect({ vertexElement: "depth", fragmentElement: "volumetricLightScatteringPass" }, attribs, ["world", "mBones", "viewProjection", "diffuseMatrix"], ["diffuseSampler"], join);
  76491. }
  76492. return this._volumetricLightScatteringPass.isReady();
  76493. };
  76494. /**
  76495. * Sets the new light position for light scattering effect
  76496. * @param {BABYLON.Vector3} The new custom light position
  76497. */
  76498. VolumetricLightScatteringPostProcess.prototype.setCustomMeshPosition = function (position) {
  76499. this.customMeshPosition = position;
  76500. };
  76501. /**
  76502. * Returns the light position for light scattering effect
  76503. * @return {BABYLON.Vector3} The custom light position
  76504. */
  76505. VolumetricLightScatteringPostProcess.prototype.getCustomMeshPosition = function () {
  76506. return this.customMeshPosition;
  76507. };
  76508. /**
  76509. * Disposes the internal assets and detaches the post-process from the camera
  76510. */
  76511. VolumetricLightScatteringPostProcess.prototype.dispose = function (camera) {
  76512. var rttIndex = camera.getScene().customRenderTargets.indexOf(this._volumetricLightScatteringRTT);
  76513. if (rttIndex !== -1) {
  76514. camera.getScene().customRenderTargets.splice(rttIndex, 1);
  76515. }
  76516. this._volumetricLightScatteringRTT.dispose();
  76517. _super.prototype.dispose.call(this, camera);
  76518. };
  76519. /**
  76520. * Returns the render target texture used by the post-process
  76521. * @return {BABYLON.RenderTargetTexture} The render target texture used by the post-process
  76522. */
  76523. VolumetricLightScatteringPostProcess.prototype.getPass = function () {
  76524. return this._volumetricLightScatteringRTT;
  76525. };
  76526. // Private methods
  76527. VolumetricLightScatteringPostProcess.prototype._meshExcluded = function (mesh) {
  76528. if (this.excludedMeshes.length > 0 && this.excludedMeshes.indexOf(mesh) !== -1) {
  76529. return true;
  76530. }
  76531. return false;
  76532. };
  76533. VolumetricLightScatteringPostProcess.prototype._createPass = function (scene, ratio) {
  76534. var _this = this;
  76535. var engine = scene.getEngine();
  76536. this._volumetricLightScatteringRTT = new BABYLON.RenderTargetTexture("volumetricLightScatteringMap", { width: engine.getRenderWidth() * ratio, height: engine.getRenderHeight() * ratio }, scene, false, true, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  76537. this._volumetricLightScatteringRTT.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  76538. this._volumetricLightScatteringRTT.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  76539. this._volumetricLightScatteringRTT.renderList = null;
  76540. this._volumetricLightScatteringRTT.renderParticles = false;
  76541. this._volumetricLightScatteringRTT.ignoreCameraViewport = true;
  76542. var camera = this.getCamera();
  76543. if (camera) {
  76544. camera.customRenderTargets.push(this._volumetricLightScatteringRTT);
  76545. }
  76546. else {
  76547. scene.customRenderTargets.push(this._volumetricLightScatteringRTT);
  76548. }
  76549. // Custom render function for submeshes
  76550. var renderSubMesh = function (subMesh) {
  76551. var mesh = subMesh.getRenderingMesh();
  76552. if (_this._meshExcluded(mesh)) {
  76553. return;
  76554. }
  76555. var material = subMesh.getMaterial();
  76556. if (!material) {
  76557. return;
  76558. }
  76559. var scene = mesh.getScene();
  76560. var engine = scene.getEngine();
  76561. // Culling
  76562. engine.setState(material.backFaceCulling);
  76563. // Managing instances
  76564. var batch = mesh._getInstancesRenderList(subMesh._id);
  76565. if (batch.mustReturn) {
  76566. return;
  76567. }
  76568. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null);
  76569. if (_this._isReady(subMesh, hardwareInstancedRendering)) {
  76570. var effect = _this._volumetricLightScatteringPass;
  76571. if (mesh === _this.mesh) {
  76572. if (subMesh.effect) {
  76573. effect = subMesh.effect;
  76574. }
  76575. else {
  76576. effect = material.getEffect();
  76577. }
  76578. }
  76579. engine.enableEffect(effect);
  76580. mesh._bind(subMesh, effect, BABYLON.Material.TriangleFillMode);
  76581. if (mesh === _this.mesh) {
  76582. material.bind(mesh.getWorldMatrix(), mesh);
  76583. }
  76584. else {
  76585. _this._volumetricLightScatteringPass.setMatrix("viewProjection", scene.getTransformMatrix());
  76586. // Alpha test
  76587. if (material && material.needAlphaTesting()) {
  76588. var alphaTexture = material.getAlphaTestTexture();
  76589. _this._volumetricLightScatteringPass.setTexture("diffuseSampler", alphaTexture);
  76590. if (alphaTexture) {
  76591. _this._volumetricLightScatteringPass.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  76592. }
  76593. }
  76594. // Bones
  76595. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  76596. _this._volumetricLightScatteringPass.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  76597. }
  76598. }
  76599. // Draw
  76600. mesh._processRendering(subMesh, _this._volumetricLightScatteringPass, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return effect.setMatrix("world", world); });
  76601. }
  76602. };
  76603. // Render target texture callbacks
  76604. var savedSceneClearColor;
  76605. var sceneClearColor = new BABYLON.Color4(0.0, 0.0, 0.0, 1.0);
  76606. this._volumetricLightScatteringRTT.onBeforeRenderObservable.add(function () {
  76607. savedSceneClearColor = scene.clearColor;
  76608. scene.clearColor = sceneClearColor;
  76609. });
  76610. this._volumetricLightScatteringRTT.onAfterRenderObservable.add(function () {
  76611. scene.clearColor = savedSceneClearColor;
  76612. });
  76613. this._volumetricLightScatteringRTT.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes, depthOnlySubMeshes) {
  76614. var engine = scene.getEngine();
  76615. var index;
  76616. if (depthOnlySubMeshes.length) {
  76617. engine.setColorWrite(false);
  76618. for (index = 0; index < depthOnlySubMeshes.length; index++) {
  76619. renderSubMesh(depthOnlySubMeshes.data[index]);
  76620. }
  76621. engine.setColorWrite(true);
  76622. }
  76623. for (index = 0; index < opaqueSubMeshes.length; index++) {
  76624. renderSubMesh(opaqueSubMeshes.data[index]);
  76625. }
  76626. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  76627. renderSubMesh(alphaTestSubMeshes.data[index]);
  76628. }
  76629. if (transparentSubMeshes.length) {
  76630. // Sort sub meshes
  76631. for (index = 0; index < transparentSubMeshes.length; index++) {
  76632. var submesh = transparentSubMeshes.data[index];
  76633. var boundingInfo = submesh.getBoundingInfo();
  76634. if (boundingInfo && scene.activeCamera) {
  76635. submesh._alphaIndex = submesh.getMesh().alphaIndex;
  76636. submesh._distanceToCamera = boundingInfo.boundingSphere.centerWorld.subtract(scene.activeCamera.position).length();
  76637. }
  76638. }
  76639. var sortedArray = transparentSubMeshes.data.slice(0, transparentSubMeshes.length);
  76640. sortedArray.sort(function (a, b) {
  76641. // Alpha index first
  76642. if (a._alphaIndex > b._alphaIndex) {
  76643. return 1;
  76644. }
  76645. if (a._alphaIndex < b._alphaIndex) {
  76646. return -1;
  76647. }
  76648. // Then distance to camera
  76649. if (a._distanceToCamera < b._distanceToCamera) {
  76650. return 1;
  76651. }
  76652. if (a._distanceToCamera > b._distanceToCamera) {
  76653. return -1;
  76654. }
  76655. return 0;
  76656. });
  76657. // Render sub meshes
  76658. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  76659. for (index = 0; index < sortedArray.length; index++) {
  76660. renderSubMesh(sortedArray[index]);
  76661. }
  76662. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  76663. }
  76664. };
  76665. };
  76666. VolumetricLightScatteringPostProcess.prototype._updateMeshScreenCoordinates = function (scene) {
  76667. var transform = scene.getTransformMatrix();
  76668. var meshPosition;
  76669. if (this.useCustomMeshPosition) {
  76670. meshPosition = this.customMeshPosition;
  76671. }
  76672. else if (this.attachedNode) {
  76673. meshPosition = this.attachedNode.position;
  76674. }
  76675. else {
  76676. meshPosition = this.mesh.parent ? this.mesh.getAbsolutePosition() : this.mesh.position;
  76677. }
  76678. var pos = BABYLON.Vector3.Project(meshPosition, BABYLON.Matrix.Identity(), transform, this._viewPort);
  76679. this._screenCoordinates.x = pos.x / this._viewPort.width;
  76680. this._screenCoordinates.y = pos.y / this._viewPort.height;
  76681. if (this.invert)
  76682. this._screenCoordinates.y = 1.0 - this._screenCoordinates.y;
  76683. };
  76684. // Static methods
  76685. /**
  76686. * Creates a default mesh for the Volumeric Light Scattering post-process
  76687. * @param {string} The mesh name
  76688. * @param {BABYLON.Scene} The scene where to create the mesh
  76689. * @return {BABYLON.Mesh} the default mesh
  76690. */
  76691. VolumetricLightScatteringPostProcess.CreateDefaultMesh = function (name, scene) {
  76692. var mesh = BABYLON.Mesh.CreatePlane(name, 1, scene);
  76693. mesh.billboardMode = BABYLON.AbstractMesh.BILLBOARDMODE_ALL;
  76694. var material = new BABYLON.StandardMaterial(name + "Material", scene);
  76695. material.emissiveColor = new BABYLON.Color3(1, 1, 1);
  76696. mesh.material = material;
  76697. return mesh;
  76698. };
  76699. __decorate([
  76700. BABYLON.serializeAsVector3()
  76701. ], VolumetricLightScatteringPostProcess.prototype, "customMeshPosition", void 0);
  76702. __decorate([
  76703. BABYLON.serialize()
  76704. ], VolumetricLightScatteringPostProcess.prototype, "useCustomMeshPosition", void 0);
  76705. __decorate([
  76706. BABYLON.serialize()
  76707. ], VolumetricLightScatteringPostProcess.prototype, "invert", void 0);
  76708. __decorate([
  76709. BABYLON.serializeAsMeshReference()
  76710. ], VolumetricLightScatteringPostProcess.prototype, "mesh", void 0);
  76711. __decorate([
  76712. BABYLON.serialize()
  76713. ], VolumetricLightScatteringPostProcess.prototype, "excludedMeshes", void 0);
  76714. __decorate([
  76715. BABYLON.serialize()
  76716. ], VolumetricLightScatteringPostProcess.prototype, "exposure", void 0);
  76717. __decorate([
  76718. BABYLON.serialize()
  76719. ], VolumetricLightScatteringPostProcess.prototype, "decay", void 0);
  76720. __decorate([
  76721. BABYLON.serialize()
  76722. ], VolumetricLightScatteringPostProcess.prototype, "weight", void 0);
  76723. __decorate([
  76724. BABYLON.serialize()
  76725. ], VolumetricLightScatteringPostProcess.prototype, "density", void 0);
  76726. return VolumetricLightScatteringPostProcess;
  76727. }(BABYLON.PostProcess));
  76728. BABYLON.VolumetricLightScatteringPostProcess = VolumetricLightScatteringPostProcess;
  76729. })(BABYLON || (BABYLON = {}));
  76730. //# sourceMappingURL=babylon.volumetricLightScatteringPostProcess.js.map
  76731. //
  76732. // This post-process allows the modification of rendered colors by using
  76733. // a 'look-up table' (LUT). This effect is also called Color Grading.
  76734. //
  76735. // The object needs to be provided an url to a texture containing the color
  76736. // look-up table: the texture must be 256 pixels wide and 16 pixels high.
  76737. // Use an image editing software to tweak the LUT to match your needs.
  76738. //
  76739. // For an example of a color LUT, see here:
  76740. // http://udn.epicgames.com/Three/rsrc/Three/ColorGrading/RGBTable16x1.png
  76741. // For explanations on color grading, see here:
  76742. // http://udn.epicgames.com/Three/ColorGrading.html
  76743. //
  76744. var BABYLON;
  76745. (function (BABYLON) {
  76746. var ColorCorrectionPostProcess = /** @class */ (function (_super) {
  76747. __extends(ColorCorrectionPostProcess, _super);
  76748. function ColorCorrectionPostProcess(name, colorTableUrl, options, camera, samplingMode, engine, reusable) {
  76749. var _this = _super.call(this, name, 'colorCorrection', null, ['colorTable'], options, camera, samplingMode, engine, reusable) || this;
  76750. _this._colorTableTexture = new BABYLON.Texture(colorTableUrl, camera.getScene(), true, false, BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  76751. _this._colorTableTexture.anisotropicFilteringLevel = 1;
  76752. _this._colorTableTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  76753. _this._colorTableTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  76754. _this.onApply = function (effect) {
  76755. effect.setTexture("colorTable", _this._colorTableTexture);
  76756. };
  76757. return _this;
  76758. }
  76759. return ColorCorrectionPostProcess;
  76760. }(BABYLON.PostProcess));
  76761. BABYLON.ColorCorrectionPostProcess = ColorCorrectionPostProcess;
  76762. })(BABYLON || (BABYLON = {}));
  76763. //# sourceMappingURL=babylon.colorCorrectionPostProcess.js.map
  76764. var BABYLON;
  76765. (function (BABYLON) {
  76766. /** Defines operator used for tonemapping */
  76767. var TonemappingOperator;
  76768. (function (TonemappingOperator) {
  76769. /** Hable */
  76770. TonemappingOperator[TonemappingOperator["Hable"] = 0] = "Hable";
  76771. /** Reinhard */
  76772. TonemappingOperator[TonemappingOperator["Reinhard"] = 1] = "Reinhard";
  76773. /** HejiDawson */
  76774. TonemappingOperator[TonemappingOperator["HejiDawson"] = 2] = "HejiDawson";
  76775. /** Photographic */
  76776. TonemappingOperator[TonemappingOperator["Photographic"] = 3] = "Photographic";
  76777. })(TonemappingOperator = BABYLON.TonemappingOperator || (BABYLON.TonemappingOperator = {}));
  76778. ;
  76779. /**
  76780. * Defines a post process to apply tone mapping
  76781. */
  76782. var TonemapPostProcess = /** @class */ (function (_super) {
  76783. __extends(TonemapPostProcess, _super);
  76784. /**
  76785. * Creates a new TonemapPostProcess
  76786. * @param name defines the name of the postprocess
  76787. * @param _operator defines the operator to use
  76788. * @param exposureAdjustment defines the required exposure adjustement
  76789. * @param camera defines the camera to use (can be null)
  76790. * @param samplingMode defines the required sampling mode (BABYLON.Texture.BILINEAR_SAMPLINGMODE by default)
  76791. * @param engine defines the hosting engine (can be ignore if camera is set)
  76792. * @param textureFormat defines the texture format to use (BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT by default)
  76793. */
  76794. function TonemapPostProcess(name, _operator,
  76795. /** Defines the required exposure adjustement */
  76796. exposureAdjustment, camera, samplingMode, engine, textureFormat) {
  76797. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  76798. if (textureFormat === void 0) { textureFormat = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  76799. var _this = _super.call(this, name, "tonemap", ["_ExposureAdjustment"], null, 1.0, camera, samplingMode, engine, true, null, textureFormat) || this;
  76800. _this._operator = _operator;
  76801. _this.exposureAdjustment = exposureAdjustment;
  76802. var defines = "#define ";
  76803. if (_this._operator === TonemappingOperator.Hable)
  76804. defines += "HABLE_TONEMAPPING";
  76805. else if (_this._operator === TonemappingOperator.Reinhard)
  76806. defines += "REINHARD_TONEMAPPING";
  76807. else if (_this._operator === TonemappingOperator.HejiDawson)
  76808. defines += "OPTIMIZED_HEJIDAWSON_TONEMAPPING";
  76809. else if (_this._operator === TonemappingOperator.Photographic)
  76810. defines += "PHOTOGRAPHIC_TONEMAPPING";
  76811. //sadly a second call to create the effect.
  76812. _this.updateEffect(defines);
  76813. _this.onApply = function (effect) {
  76814. effect.setFloat("_ExposureAdjustment", _this.exposureAdjustment);
  76815. };
  76816. return _this;
  76817. }
  76818. return TonemapPostProcess;
  76819. }(BABYLON.PostProcess));
  76820. BABYLON.TonemapPostProcess = TonemapPostProcess;
  76821. })(BABYLON || (BABYLON = {}));
  76822. //# sourceMappingURL=babylon.tonemapPostProcess.js.map
  76823. var BABYLON;
  76824. (function (BABYLON) {
  76825. var DisplayPassPostProcess = /** @class */ (function (_super) {
  76826. __extends(DisplayPassPostProcess, _super);
  76827. function DisplayPassPostProcess(name, options, camera, samplingMode, engine, reusable) {
  76828. return _super.call(this, name, "displayPass", ["passSampler"], ["passSampler"], options, camera, samplingMode, engine, reusable) || this;
  76829. }
  76830. return DisplayPassPostProcess;
  76831. }(BABYLON.PostProcess));
  76832. BABYLON.DisplayPassPostProcess = DisplayPassPostProcess;
  76833. })(BABYLON || (BABYLON = {}));
  76834. //# sourceMappingURL=babylon.displayPassPostProcess.js.map
  76835. var BABYLON;
  76836. (function (BABYLON) {
  76837. var HighlightsPostProcess = /** @class */ (function (_super) {
  76838. __extends(HighlightsPostProcess, _super);
  76839. function HighlightsPostProcess(name, options, camera, samplingMode, engine, reusable, textureType) {
  76840. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  76841. return _super.call(this, name, "highlights", null, null, options, camera, samplingMode, engine, reusable, null, textureType) || this;
  76842. }
  76843. return HighlightsPostProcess;
  76844. }(BABYLON.PostProcess));
  76845. BABYLON.HighlightsPostProcess = HighlightsPostProcess;
  76846. })(BABYLON || (BABYLON = {}));
  76847. //# sourceMappingURL=babylon.highlightsPostProcess.js.map
  76848. var BABYLON;
  76849. (function (BABYLON) {
  76850. var ImageProcessingPostProcess = /** @class */ (function (_super) {
  76851. __extends(ImageProcessingPostProcess, _super);
  76852. function ImageProcessingPostProcess(name, options, camera, samplingMode, engine, reusable, textureType, imageProcessingConfiguration) {
  76853. if (camera === void 0) { camera = null; }
  76854. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  76855. var _this = _super.call(this, name, "imageProcessing", [], [], options, camera, samplingMode, engine, reusable, null, textureType, "postprocess", null, true) || this;
  76856. _this._fromLinearSpace = true;
  76857. /**
  76858. * Defines cache preventing GC.
  76859. */
  76860. _this._defines = {
  76861. IMAGEPROCESSING: false,
  76862. VIGNETTE: false,
  76863. VIGNETTEBLENDMODEMULTIPLY: false,
  76864. VIGNETTEBLENDMODEOPAQUE: false,
  76865. TONEMAPPING: false,
  76866. CONTRAST: false,
  76867. COLORCURVES: false,
  76868. COLORGRADING: false,
  76869. COLORGRADING3D: false,
  76870. FROMLINEARSPACE: false,
  76871. SAMPLER3DGREENDEPTH: false,
  76872. SAMPLER3DBGRMAP: false,
  76873. IMAGEPROCESSINGPOSTPROCESS: false,
  76874. EXPOSURE: false,
  76875. };
  76876. // Setup the configuration as forced by the constructor. This would then not force the
  76877. // scene materials output in linear space and let untouched the default forward pass.
  76878. if (imageProcessingConfiguration) {
  76879. imageProcessingConfiguration.applyByPostProcess = true;
  76880. _this._attachImageProcessingConfiguration(imageProcessingConfiguration, true);
  76881. // This will cause the shader to be compiled
  76882. _this.fromLinearSpace = false;
  76883. }
  76884. // Setup the default processing configuration to the scene.
  76885. else {
  76886. _this._attachImageProcessingConfiguration(null, true);
  76887. _this.imageProcessingConfiguration.applyByPostProcess = true;
  76888. }
  76889. _this.onApply = function (effect) {
  76890. _this.imageProcessingConfiguration.bind(effect, _this.aspectRatio);
  76891. };
  76892. return _this;
  76893. }
  76894. Object.defineProperty(ImageProcessingPostProcess.prototype, "imageProcessingConfiguration", {
  76895. /**
  76896. * Gets the image processing configuration used either in this material.
  76897. */
  76898. get: function () {
  76899. return this._imageProcessingConfiguration;
  76900. },
  76901. /**
  76902. * Sets the Default image processing configuration used either in the this material.
  76903. *
  76904. * If sets to null, the scene one is in use.
  76905. */
  76906. set: function (value) {
  76907. this._attachImageProcessingConfiguration(value);
  76908. },
  76909. enumerable: true,
  76910. configurable: true
  76911. });
  76912. /**
  76913. * Attaches a new image processing configuration to the PBR Material.
  76914. * @param configuration
  76915. */
  76916. ImageProcessingPostProcess.prototype._attachImageProcessingConfiguration = function (configuration, doNotBuild) {
  76917. var _this = this;
  76918. if (doNotBuild === void 0) { doNotBuild = false; }
  76919. if (configuration === this._imageProcessingConfiguration) {
  76920. return;
  76921. }
  76922. // Detaches observer.
  76923. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  76924. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  76925. }
  76926. // Pick the scene configuration if needed.
  76927. if (!configuration) {
  76928. var scene = null;
  76929. var engine = this.getEngine();
  76930. var camera = this.getCamera();
  76931. if (camera) {
  76932. scene = camera.getScene();
  76933. }
  76934. else if (engine && engine.scenes) {
  76935. var scenes = engine.scenes;
  76936. scene = scenes[scenes.length - 1];
  76937. }
  76938. else {
  76939. scene = BABYLON.Engine.LastCreatedScene;
  76940. }
  76941. this._imageProcessingConfiguration = scene.imageProcessingConfiguration;
  76942. }
  76943. else {
  76944. this._imageProcessingConfiguration = configuration;
  76945. }
  76946. // Attaches observer.
  76947. this._imageProcessingObserver = this._imageProcessingConfiguration.onUpdateParameters.add(function (conf) {
  76948. _this._updateParameters();
  76949. });
  76950. // Ensure the effect will be rebuilt.
  76951. if (!doNotBuild) {
  76952. this._updateParameters();
  76953. }
  76954. };
  76955. Object.defineProperty(ImageProcessingPostProcess.prototype, "colorCurves", {
  76956. /**
  76957. * Gets Color curves setup used in the effect if colorCurvesEnabled is set to true .
  76958. */
  76959. get: function () {
  76960. return this.imageProcessingConfiguration.colorCurves;
  76961. },
  76962. /**
  76963. * Sets Color curves setup used in the effect if colorCurvesEnabled is set to true .
  76964. */
  76965. set: function (value) {
  76966. this.imageProcessingConfiguration.colorCurves = value;
  76967. },
  76968. enumerable: true,
  76969. configurable: true
  76970. });
  76971. Object.defineProperty(ImageProcessingPostProcess.prototype, "colorCurvesEnabled", {
  76972. /**
  76973. * Gets wether the color curves effect is enabled.
  76974. */
  76975. get: function () {
  76976. return this.imageProcessingConfiguration.colorCurvesEnabled;
  76977. },
  76978. /**
  76979. * Sets wether the color curves effect is enabled.
  76980. */
  76981. set: function (value) {
  76982. this.imageProcessingConfiguration.colorCurvesEnabled = value;
  76983. },
  76984. enumerable: true,
  76985. configurable: true
  76986. });
  76987. Object.defineProperty(ImageProcessingPostProcess.prototype, "colorGradingTexture", {
  76988. /**
  76989. * Gets Color grading LUT texture used in the effect if colorGradingEnabled is set to true.
  76990. */
  76991. get: function () {
  76992. return this.imageProcessingConfiguration.colorGradingTexture;
  76993. },
  76994. /**
  76995. * Sets Color grading LUT texture used in the effect if colorGradingEnabled is set to true.
  76996. */
  76997. set: function (value) {
  76998. this.imageProcessingConfiguration.colorGradingTexture = value;
  76999. },
  77000. enumerable: true,
  77001. configurable: true
  77002. });
  77003. Object.defineProperty(ImageProcessingPostProcess.prototype, "colorGradingEnabled", {
  77004. /**
  77005. * Gets wether the color grading effect is enabled.
  77006. */
  77007. get: function () {
  77008. return this.imageProcessingConfiguration.colorGradingEnabled;
  77009. },
  77010. /**
  77011. * Gets wether the color grading effect is enabled.
  77012. */
  77013. set: function (value) {
  77014. this.imageProcessingConfiguration.colorGradingEnabled = value;
  77015. },
  77016. enumerable: true,
  77017. configurable: true
  77018. });
  77019. Object.defineProperty(ImageProcessingPostProcess.prototype, "exposure", {
  77020. /**
  77021. * Gets exposure used in the effect.
  77022. */
  77023. get: function () {
  77024. return this.imageProcessingConfiguration.exposure;
  77025. },
  77026. /**
  77027. * Sets exposure used in the effect.
  77028. */
  77029. set: function (value) {
  77030. this.imageProcessingConfiguration.exposure = value;
  77031. },
  77032. enumerable: true,
  77033. configurable: true
  77034. });
  77035. Object.defineProperty(ImageProcessingPostProcess.prototype, "toneMappingEnabled", {
  77036. /**
  77037. * Gets wether tonemapping is enabled or not.
  77038. */
  77039. get: function () {
  77040. return this._imageProcessingConfiguration.toneMappingEnabled;
  77041. },
  77042. /**
  77043. * Sets wether tonemapping is enabled or not
  77044. */
  77045. set: function (value) {
  77046. this._imageProcessingConfiguration.toneMappingEnabled = value;
  77047. },
  77048. enumerable: true,
  77049. configurable: true
  77050. });
  77051. ;
  77052. ;
  77053. Object.defineProperty(ImageProcessingPostProcess.prototype, "contrast", {
  77054. /**
  77055. * Gets contrast used in the effect.
  77056. */
  77057. get: function () {
  77058. return this.imageProcessingConfiguration.contrast;
  77059. },
  77060. /**
  77061. * Sets contrast used in the effect.
  77062. */
  77063. set: function (value) {
  77064. this.imageProcessingConfiguration.contrast = value;
  77065. },
  77066. enumerable: true,
  77067. configurable: true
  77068. });
  77069. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteStretch", {
  77070. /**
  77071. * Gets Vignette stretch size.
  77072. */
  77073. get: function () {
  77074. return this.imageProcessingConfiguration.vignetteStretch;
  77075. },
  77076. /**
  77077. * Sets Vignette stretch size.
  77078. */
  77079. set: function (value) {
  77080. this.imageProcessingConfiguration.vignetteStretch = value;
  77081. },
  77082. enumerable: true,
  77083. configurable: true
  77084. });
  77085. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteCentreX", {
  77086. /**
  77087. * Gets Vignette centre X Offset.
  77088. */
  77089. get: function () {
  77090. return this.imageProcessingConfiguration.vignetteCentreX;
  77091. },
  77092. /**
  77093. * Sets Vignette centre X Offset.
  77094. */
  77095. set: function (value) {
  77096. this.imageProcessingConfiguration.vignetteCentreX = value;
  77097. },
  77098. enumerable: true,
  77099. configurable: true
  77100. });
  77101. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteCentreY", {
  77102. /**
  77103. * Gets Vignette centre Y Offset.
  77104. */
  77105. get: function () {
  77106. return this.imageProcessingConfiguration.vignetteCentreY;
  77107. },
  77108. /**
  77109. * Sets Vignette centre Y Offset.
  77110. */
  77111. set: function (value) {
  77112. this.imageProcessingConfiguration.vignetteCentreY = value;
  77113. },
  77114. enumerable: true,
  77115. configurable: true
  77116. });
  77117. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteWeight", {
  77118. /**
  77119. * Gets Vignette weight or intensity of the vignette effect.
  77120. */
  77121. get: function () {
  77122. return this.imageProcessingConfiguration.vignetteWeight;
  77123. },
  77124. /**
  77125. * Sets Vignette weight or intensity of the vignette effect.
  77126. */
  77127. set: function (value) {
  77128. this.imageProcessingConfiguration.vignetteWeight = value;
  77129. },
  77130. enumerable: true,
  77131. configurable: true
  77132. });
  77133. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteColor", {
  77134. /**
  77135. * Gets Color of the vignette applied on the screen through the chosen blend mode (vignetteBlendMode)
  77136. * if vignetteEnabled is set to true.
  77137. */
  77138. get: function () {
  77139. return this.imageProcessingConfiguration.vignetteColor;
  77140. },
  77141. /**
  77142. * Sets Color of the vignette applied on the screen through the chosen blend mode (vignetteBlendMode)
  77143. * if vignetteEnabled is set to true.
  77144. */
  77145. set: function (value) {
  77146. this.imageProcessingConfiguration.vignetteColor = value;
  77147. },
  77148. enumerable: true,
  77149. configurable: true
  77150. });
  77151. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteCameraFov", {
  77152. /**
  77153. * Gets Camera field of view used by the Vignette effect.
  77154. */
  77155. get: function () {
  77156. return this.imageProcessingConfiguration.vignetteCameraFov;
  77157. },
  77158. /**
  77159. * Sets Camera field of view used by the Vignette effect.
  77160. */
  77161. set: function (value) {
  77162. this.imageProcessingConfiguration.vignetteCameraFov = value;
  77163. },
  77164. enumerable: true,
  77165. configurable: true
  77166. });
  77167. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteBlendMode", {
  77168. /**
  77169. * Gets the vignette blend mode allowing different kind of effect.
  77170. */
  77171. get: function () {
  77172. return this.imageProcessingConfiguration.vignetteBlendMode;
  77173. },
  77174. /**
  77175. * Sets the vignette blend mode allowing different kind of effect.
  77176. */
  77177. set: function (value) {
  77178. this.imageProcessingConfiguration.vignetteBlendMode = value;
  77179. },
  77180. enumerable: true,
  77181. configurable: true
  77182. });
  77183. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteEnabled", {
  77184. /**
  77185. * Gets wether the vignette effect is enabled.
  77186. */
  77187. get: function () {
  77188. return this.imageProcessingConfiguration.vignetteEnabled;
  77189. },
  77190. /**
  77191. * Sets wether the vignette effect is enabled.
  77192. */
  77193. set: function (value) {
  77194. this.imageProcessingConfiguration.vignetteEnabled = value;
  77195. },
  77196. enumerable: true,
  77197. configurable: true
  77198. });
  77199. Object.defineProperty(ImageProcessingPostProcess.prototype, "fromLinearSpace", {
  77200. /**
  77201. * Gets wether the input of the processing is in Gamma or Linear Space.
  77202. */
  77203. get: function () {
  77204. return this._fromLinearSpace;
  77205. },
  77206. /**
  77207. * Sets wether the input of the processing is in Gamma or Linear Space.
  77208. */
  77209. set: function (value) {
  77210. if (this._fromLinearSpace === value) {
  77211. return;
  77212. }
  77213. this._fromLinearSpace = value;
  77214. this._updateParameters();
  77215. },
  77216. enumerable: true,
  77217. configurable: true
  77218. });
  77219. ImageProcessingPostProcess.prototype.getClassName = function () {
  77220. return "ImageProcessingPostProcess";
  77221. };
  77222. ImageProcessingPostProcess.prototype._updateParameters = function () {
  77223. this._defines.FROMLINEARSPACE = this._fromLinearSpace;
  77224. this.imageProcessingConfiguration.prepareDefines(this._defines, true);
  77225. var defines = "";
  77226. for (var define in this._defines) {
  77227. if (this._defines[define]) {
  77228. defines += "#define " + define + ";\r\n";
  77229. }
  77230. }
  77231. var samplers = ["textureSampler"];
  77232. BABYLON.ImageProcessingConfiguration.PrepareSamplers(samplers, this._defines);
  77233. var uniforms = ["scale"];
  77234. BABYLON.ImageProcessingConfiguration.PrepareUniforms(uniforms, this._defines);
  77235. this.updateEffect(defines, uniforms, samplers);
  77236. };
  77237. ImageProcessingPostProcess.prototype.dispose = function (camera) {
  77238. _super.prototype.dispose.call(this, camera);
  77239. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  77240. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  77241. }
  77242. this.imageProcessingConfiguration.applyByPostProcess = false;
  77243. };
  77244. __decorate([
  77245. BABYLON.serialize()
  77246. ], ImageProcessingPostProcess.prototype, "_fromLinearSpace", void 0);
  77247. return ImageProcessingPostProcess;
  77248. }(BABYLON.PostProcess));
  77249. BABYLON.ImageProcessingPostProcess = ImageProcessingPostProcess;
  77250. })(BABYLON || (BABYLON = {}));
  77251. //# sourceMappingURL=babylon.imageProcessingPostProcess.js.map
  77252. var BABYLON;
  77253. (function (BABYLON) {
  77254. /**
  77255. * Class used to store bone information
  77256. * @see http://doc.babylonjs.com/how_to/how_to_use_bones_and_skeletons
  77257. */
  77258. var Bone = /** @class */ (function (_super) {
  77259. __extends(Bone, _super);
  77260. /**
  77261. * Create a new bone
  77262. * @param name defines the bone name
  77263. * @param skeleton defines the parent skeleton
  77264. * @param parentBone defines the parent (can be null if the bone is the root)
  77265. * @param localMatrix defines the local matrix
  77266. * @param restPose defines the rest pose matrix
  77267. * @param baseMatrix defines the base matrix
  77268. * @param index defines index of the bone in the hiearchy
  77269. */
  77270. function Bone(
  77271. /**
  77272. * defines the bone name
  77273. */
  77274. name, skeleton, parentBone, localMatrix, restPose, baseMatrix, index) {
  77275. if (parentBone === void 0) { parentBone = null; }
  77276. if (localMatrix === void 0) { localMatrix = null; }
  77277. if (restPose === void 0) { restPose = null; }
  77278. if (baseMatrix === void 0) { baseMatrix = null; }
  77279. if (index === void 0) { index = null; }
  77280. var _this = _super.call(this, name, skeleton.getScene()) || this;
  77281. _this.name = name;
  77282. /**
  77283. * Gets the list of child bones
  77284. */
  77285. _this.children = new Array();
  77286. /** Gets the animations associated with this bone */
  77287. _this.animations = new Array();
  77288. /**
  77289. * @hidden Internal only
  77290. * Set this value to map this bone to a different index in the transform matrices
  77291. * Set this value to -1 to exclude the bone from the transform matrices
  77292. */
  77293. _this._index = null;
  77294. _this._absoluteTransform = new BABYLON.Matrix();
  77295. _this._invertedAbsoluteTransform = new BABYLON.Matrix();
  77296. _this._scalingDeterminant = 1;
  77297. _this._worldTransform = new BABYLON.Matrix();
  77298. _this._needToDecompose = true;
  77299. _this._needToCompose = false;
  77300. _this._skeleton = skeleton;
  77301. _this._localMatrix = localMatrix ? localMatrix.clone() : BABYLON.Matrix.Identity();
  77302. _this._restPose = restPose ? restPose : _this._localMatrix.clone();
  77303. _this._baseMatrix = baseMatrix ? baseMatrix : _this._localMatrix.clone();
  77304. _this._index = index;
  77305. skeleton.bones.push(_this);
  77306. _this.setParent(parentBone, false);
  77307. if (baseMatrix || localMatrix) {
  77308. _this._updateDifferenceMatrix();
  77309. }
  77310. return _this;
  77311. }
  77312. Object.defineProperty(Bone.prototype, "_matrix", {
  77313. /** @hidden */
  77314. get: function () {
  77315. this._compose();
  77316. return this._localMatrix;
  77317. },
  77318. /** @hidden */
  77319. set: function (value) {
  77320. this._localMatrix.copyFrom(value);
  77321. this._needToDecompose = true;
  77322. },
  77323. enumerable: true,
  77324. configurable: true
  77325. });
  77326. // Members
  77327. /**
  77328. * Gets the parent skeleton
  77329. * @returns a skeleton
  77330. */
  77331. Bone.prototype.getSkeleton = function () {
  77332. return this._skeleton;
  77333. };
  77334. /**
  77335. * Gets parent bone
  77336. * @returns a bone or null if the bone is the root of the bone hierarchy
  77337. */
  77338. Bone.prototype.getParent = function () {
  77339. return this._parent;
  77340. };
  77341. /**
  77342. * Sets the parent bone
  77343. * @param parent defines the parent (can be null if the bone is the root)
  77344. * @param updateDifferenceMatrix defines if the difference matrix must be updated
  77345. */
  77346. Bone.prototype.setParent = function (parent, updateDifferenceMatrix) {
  77347. if (updateDifferenceMatrix === void 0) { updateDifferenceMatrix = true; }
  77348. if (this._parent === parent) {
  77349. return;
  77350. }
  77351. if (this._parent) {
  77352. var index = this._parent.children.indexOf(this);
  77353. if (index !== -1) {
  77354. this._parent.children.splice(index, 1);
  77355. }
  77356. }
  77357. this._parent = parent;
  77358. if (this._parent) {
  77359. this._parent.children.push(this);
  77360. }
  77361. if (updateDifferenceMatrix) {
  77362. this._updateDifferenceMatrix();
  77363. }
  77364. this.markAsDirty();
  77365. };
  77366. /**
  77367. * Gets the local matrix
  77368. * @returns a matrix
  77369. */
  77370. Bone.prototype.getLocalMatrix = function () {
  77371. this._compose();
  77372. return this._localMatrix;
  77373. };
  77374. /**
  77375. * Gets the base matrix (initial matrix which remains unchanged)
  77376. * @returns a matrix
  77377. */
  77378. Bone.prototype.getBaseMatrix = function () {
  77379. return this._baseMatrix;
  77380. };
  77381. /**
  77382. * Gets the rest pose matrix
  77383. * @returns a matrix
  77384. */
  77385. Bone.prototype.getRestPose = function () {
  77386. return this._restPose;
  77387. };
  77388. /**
  77389. * Gets a matrix used to store world matrix (ie. the matrix sent to shaders)
  77390. */
  77391. Bone.prototype.getWorldMatrix = function () {
  77392. return this._worldTransform;
  77393. };
  77394. /**
  77395. * Sets the local matrix to rest pose matrix
  77396. */
  77397. Bone.prototype.returnToRest = function () {
  77398. this.updateMatrix(this._restPose.clone());
  77399. };
  77400. /**
  77401. * Gets the inverse of the absolute transform matrix.
  77402. * This matrix will be multiplied by local matrix to get the difference matrix (ie. the difference between original state and current state)
  77403. * @returns a matrix
  77404. */
  77405. Bone.prototype.getInvertedAbsoluteTransform = function () {
  77406. return this._invertedAbsoluteTransform;
  77407. };
  77408. /**
  77409. * Gets the absolute transform matrix (ie base matrix * parent world matrix)
  77410. * @returns a matrix
  77411. */
  77412. Bone.prototype.getAbsoluteTransform = function () {
  77413. return this._absoluteTransform;
  77414. };
  77415. Object.defineProperty(Bone.prototype, "position", {
  77416. // Properties (matches AbstractMesh properties)
  77417. /** Gets or sets current position (in local space) */
  77418. get: function () {
  77419. this._decompose();
  77420. return this._localPosition;
  77421. },
  77422. set: function (newPosition) {
  77423. this._decompose();
  77424. this._localPosition.copyFrom(newPosition);
  77425. this._markAsDirtyAndCompose();
  77426. },
  77427. enumerable: true,
  77428. configurable: true
  77429. });
  77430. Object.defineProperty(Bone.prototype, "rotation", {
  77431. /** Gets or sets current rotation (in local space) */
  77432. get: function () {
  77433. return this.getRotation();
  77434. },
  77435. set: function (newRotation) {
  77436. this.setRotation(newRotation);
  77437. },
  77438. enumerable: true,
  77439. configurable: true
  77440. });
  77441. Object.defineProperty(Bone.prototype, "rotationQuaternion", {
  77442. /** Gets or sets current rotation quaternion (in local space) */
  77443. get: function () {
  77444. this._decompose();
  77445. return this._localRotation;
  77446. },
  77447. set: function (newRotation) {
  77448. this.setRotationQuaternion(newRotation);
  77449. },
  77450. enumerable: true,
  77451. configurable: true
  77452. });
  77453. Object.defineProperty(Bone.prototype, "scaling", {
  77454. /** Gets or sets current scaling (in local space) */
  77455. get: function () {
  77456. return this.getScale();
  77457. },
  77458. set: function (newScaling) {
  77459. this.setScale(newScaling);
  77460. },
  77461. enumerable: true,
  77462. configurable: true
  77463. });
  77464. Object.defineProperty(Bone.prototype, "animationPropertiesOverride", {
  77465. /**
  77466. * Gets the animation properties override
  77467. */
  77468. get: function () {
  77469. return this._skeleton.animationPropertiesOverride;
  77470. },
  77471. enumerable: true,
  77472. configurable: true
  77473. });
  77474. // Methods
  77475. Bone.prototype._decompose = function () {
  77476. if (!this._needToDecompose) {
  77477. return;
  77478. }
  77479. this._needToDecompose = false;
  77480. if (!this._localScaling) {
  77481. this._localScaling = BABYLON.Vector3.Zero();
  77482. this._localRotation = BABYLON.Quaternion.Zero();
  77483. this._localPosition = BABYLON.Vector3.Zero();
  77484. }
  77485. this._localMatrix.decompose(this._localScaling, this._localRotation, this._localPosition);
  77486. };
  77487. Bone.prototype._compose = function () {
  77488. if (!this._needToCompose) {
  77489. return;
  77490. }
  77491. this._needToCompose = false;
  77492. BABYLON.Matrix.ComposeToRef(this._localScaling, this._localRotation, this._localPosition, this._localMatrix);
  77493. };
  77494. /**
  77495. * Update the base and local matrices
  77496. * @param matrix defines the new base or local matrix
  77497. * @param updateDifferenceMatrix defines if the difference matrix must be updated
  77498. * @param updateLocalMatrix defines if the local matrix should be updated
  77499. */
  77500. Bone.prototype.updateMatrix = function (matrix, updateDifferenceMatrix, updateLocalMatrix) {
  77501. if (updateDifferenceMatrix === void 0) { updateDifferenceMatrix = true; }
  77502. if (updateLocalMatrix === void 0) { updateLocalMatrix = true; }
  77503. this._baseMatrix.copyFrom(matrix);
  77504. if (updateDifferenceMatrix) {
  77505. this._updateDifferenceMatrix();
  77506. }
  77507. if (updateLocalMatrix) {
  77508. this._localMatrix.copyFrom(matrix);
  77509. this._markAsDirtyAndDecompose();
  77510. }
  77511. else {
  77512. this.markAsDirty();
  77513. }
  77514. };
  77515. /** @hidden */
  77516. Bone.prototype._updateDifferenceMatrix = function (rootMatrix, updateChildren) {
  77517. if (updateChildren === void 0) { updateChildren = true; }
  77518. if (!rootMatrix) {
  77519. rootMatrix = this._baseMatrix;
  77520. }
  77521. if (this._parent) {
  77522. rootMatrix.multiplyToRef(this._parent._absoluteTransform, this._absoluteTransform);
  77523. }
  77524. else {
  77525. this._absoluteTransform.copyFrom(rootMatrix);
  77526. }
  77527. this._absoluteTransform.invertToRef(this._invertedAbsoluteTransform);
  77528. if (updateChildren) {
  77529. for (var index = 0; index < this.children.length; index++) {
  77530. this.children[index]._updateDifferenceMatrix();
  77531. }
  77532. }
  77533. this._scalingDeterminant = (this._absoluteTransform.determinant() < 0 ? -1 : 1);
  77534. };
  77535. /**
  77536. * Flag the bone as dirty (Forcing it to update everything)
  77537. */
  77538. Bone.prototype.markAsDirty = function () {
  77539. this._currentRenderId++;
  77540. this._childRenderId++;
  77541. this._skeleton._markAsDirty();
  77542. };
  77543. Bone.prototype._markAsDirtyAndCompose = function () {
  77544. this.markAsDirty();
  77545. this._needToCompose = true;
  77546. };
  77547. Bone.prototype._markAsDirtyAndDecompose = function () {
  77548. this.markAsDirty();
  77549. this._needToDecompose = true;
  77550. };
  77551. /**
  77552. * Copy an animation range from another bone
  77553. * @param source defines the source bone
  77554. * @param rangeName defines the range name to copy
  77555. * @param frameOffset defines the frame offset
  77556. * @param rescaleAsRequired defines if rescaling must be applied if required
  77557. * @param skelDimensionsRatio defines the scaling ratio
  77558. * @returns true if operation was successful
  77559. */
  77560. Bone.prototype.copyAnimationRange = function (source, rangeName, frameOffset, rescaleAsRequired, skelDimensionsRatio) {
  77561. if (rescaleAsRequired === void 0) { rescaleAsRequired = false; }
  77562. if (skelDimensionsRatio === void 0) { skelDimensionsRatio = null; }
  77563. // all animation may be coming from a library skeleton, so may need to create animation
  77564. if (this.animations.length === 0) {
  77565. this.animations.push(new BABYLON.Animation(this.name, "_matrix", source.animations[0].framePerSecond, BABYLON.Animation.ANIMATIONTYPE_MATRIX, 0));
  77566. this.animations[0].setKeys([]);
  77567. }
  77568. // get animation info / verify there is such a range from the source bone
  77569. var sourceRange = source.animations[0].getRange(rangeName);
  77570. if (!sourceRange) {
  77571. return false;
  77572. }
  77573. var from = sourceRange.from;
  77574. var to = sourceRange.to;
  77575. var sourceKeys = source.animations[0].getKeys();
  77576. // rescaling prep
  77577. var sourceBoneLength = source.length;
  77578. var sourceParent = source.getParent();
  77579. var parent = this.getParent();
  77580. var parentScalingReqd = rescaleAsRequired && sourceParent && sourceBoneLength && this.length && sourceBoneLength !== this.length;
  77581. var parentRatio = parentScalingReqd && parent && sourceParent ? parent.length / sourceParent.length : 1;
  77582. var dimensionsScalingReqd = rescaleAsRequired && !parent && skelDimensionsRatio && (skelDimensionsRatio.x !== 1 || skelDimensionsRatio.y !== 1 || skelDimensionsRatio.z !== 1);
  77583. var destKeys = this.animations[0].getKeys();
  77584. // loop vars declaration
  77585. var orig;
  77586. var origTranslation;
  77587. var mat;
  77588. for (var key = 0, nKeys = sourceKeys.length; key < nKeys; key++) {
  77589. orig = sourceKeys[key];
  77590. if (orig.frame >= from && orig.frame <= to) {
  77591. if (rescaleAsRequired) {
  77592. mat = orig.value.clone();
  77593. // scale based on parent ratio, when bone has parent
  77594. if (parentScalingReqd) {
  77595. origTranslation = mat.getTranslation();
  77596. mat.setTranslation(origTranslation.scaleInPlace(parentRatio));
  77597. // scale based on skeleton dimension ratio when root bone, and value is passed
  77598. }
  77599. else if (dimensionsScalingReqd && skelDimensionsRatio) {
  77600. origTranslation = mat.getTranslation();
  77601. mat.setTranslation(origTranslation.multiplyInPlace(skelDimensionsRatio));
  77602. // use original when root bone, and no data for skelDimensionsRatio
  77603. }
  77604. else {
  77605. mat = orig.value;
  77606. }
  77607. }
  77608. else {
  77609. mat = orig.value;
  77610. }
  77611. destKeys.push({ frame: orig.frame + frameOffset, value: mat });
  77612. }
  77613. }
  77614. this.animations[0].createRange(rangeName, from + frameOffset, to + frameOffset);
  77615. return true;
  77616. };
  77617. /**
  77618. * Translate the bone in local or world space
  77619. * @param vec The amount to translate the bone
  77620. * @param space The space that the translation is in
  77621. * @param mesh The mesh that this bone is attached to. This is only used in world space
  77622. */
  77623. Bone.prototype.translate = function (vec, space, mesh) {
  77624. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  77625. var lm = this.getLocalMatrix();
  77626. if (space == BABYLON.Space.LOCAL) {
  77627. lm.m[12] += vec.x;
  77628. lm.m[13] += vec.y;
  77629. lm.m[14] += vec.z;
  77630. }
  77631. else {
  77632. var wm = null;
  77633. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  77634. if (mesh) {
  77635. wm = mesh.getWorldMatrix();
  77636. }
  77637. this._skeleton.computeAbsoluteTransforms();
  77638. var tmat = Bone._tmpMats[0];
  77639. var tvec = Bone._tmpVecs[0];
  77640. if (this._parent) {
  77641. if (mesh && wm) {
  77642. tmat.copyFrom(this._parent.getAbsoluteTransform());
  77643. tmat.multiplyToRef(wm, tmat);
  77644. }
  77645. else {
  77646. tmat.copyFrom(this._parent.getAbsoluteTransform());
  77647. }
  77648. }
  77649. tmat.m[12] = 0;
  77650. tmat.m[13] = 0;
  77651. tmat.m[14] = 0;
  77652. tmat.invert();
  77653. BABYLON.Vector3.TransformCoordinatesToRef(vec, tmat, tvec);
  77654. lm.m[12] += tvec.x;
  77655. lm.m[13] += tvec.y;
  77656. lm.m[14] += tvec.z;
  77657. }
  77658. this._markAsDirtyAndDecompose();
  77659. };
  77660. /**
  77661. * Set the postion of the bone in local or world space
  77662. * @param position The position to set the bone
  77663. * @param space The space that the position is in
  77664. * @param mesh The mesh that this bone is attached to. This is only used in world space
  77665. */
  77666. Bone.prototype.setPosition = function (position, space, mesh) {
  77667. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  77668. var lm = this.getLocalMatrix();
  77669. if (space == BABYLON.Space.LOCAL) {
  77670. lm.m[12] = position.x;
  77671. lm.m[13] = position.y;
  77672. lm.m[14] = position.z;
  77673. }
  77674. else {
  77675. var wm = null;
  77676. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  77677. if (mesh) {
  77678. wm = mesh.getWorldMatrix();
  77679. }
  77680. this._skeleton.computeAbsoluteTransforms();
  77681. var tmat = Bone._tmpMats[0];
  77682. var vec = Bone._tmpVecs[0];
  77683. if (this._parent) {
  77684. if (mesh && wm) {
  77685. tmat.copyFrom(this._parent.getAbsoluteTransform());
  77686. tmat.multiplyToRef(wm, tmat);
  77687. }
  77688. else {
  77689. tmat.copyFrom(this._parent.getAbsoluteTransform());
  77690. }
  77691. }
  77692. tmat.invert();
  77693. BABYLON.Vector3.TransformCoordinatesToRef(position, tmat, vec);
  77694. lm.m[12] = vec.x;
  77695. lm.m[13] = vec.y;
  77696. lm.m[14] = vec.z;
  77697. }
  77698. this._markAsDirtyAndDecompose();
  77699. };
  77700. /**
  77701. * Set the absolute position of the bone (world space)
  77702. * @param position The position to set the bone
  77703. * @param mesh The mesh that this bone is attached to
  77704. */
  77705. Bone.prototype.setAbsolutePosition = function (position, mesh) {
  77706. this.setPosition(position, BABYLON.Space.WORLD, mesh);
  77707. };
  77708. /**
  77709. * Scale the bone on the x, y and z axes (in local space)
  77710. * @param x The amount to scale the bone on the x axis
  77711. * @param y The amount to scale the bone on the y axis
  77712. * @param z The amount to scale the bone on the z axis
  77713. * @param scaleChildren sets this to true if children of the bone should be scaled as well (false by default)
  77714. */
  77715. Bone.prototype.scale = function (x, y, z, scaleChildren) {
  77716. if (scaleChildren === void 0) { scaleChildren = false; }
  77717. var locMat = this.getLocalMatrix();
  77718. // Apply new scaling on top of current local matrix
  77719. var scaleMat = Bone._tmpMats[0];
  77720. BABYLON.Matrix.ScalingToRef(x, y, z, scaleMat);
  77721. scaleMat.multiplyToRef(locMat, locMat);
  77722. // Invert scaling matrix and apply the inverse to all children
  77723. scaleMat.invert();
  77724. for (var _i = 0, _a = this.children; _i < _a.length; _i++) {
  77725. var child = _a[_i];
  77726. var cm = child.getLocalMatrix();
  77727. cm.multiplyToRef(scaleMat, cm);
  77728. cm.m[12] *= x;
  77729. cm.m[13] *= y;
  77730. cm.m[14] *= z;
  77731. child._markAsDirtyAndDecompose();
  77732. }
  77733. this._markAsDirtyAndDecompose();
  77734. if (scaleChildren) {
  77735. for (var _b = 0, _c = this.children; _b < _c.length; _b++) {
  77736. var child = _c[_b];
  77737. child.scale(x, y, z, scaleChildren);
  77738. }
  77739. }
  77740. };
  77741. /**
  77742. * Set the bone scaling in local space
  77743. * @param scale defines the scaling vector
  77744. */
  77745. Bone.prototype.setScale = function (scale) {
  77746. this._decompose();
  77747. this._localScaling.copyFrom(scale);
  77748. this._markAsDirtyAndCompose();
  77749. };
  77750. /**
  77751. * Gets the current scaling in local space
  77752. * @returns the current scaling vector
  77753. */
  77754. Bone.prototype.getScale = function () {
  77755. this._decompose();
  77756. return this._localScaling;
  77757. };
  77758. /**
  77759. * Gets the current scaling in local space and stores it in a target vector
  77760. * @param result defines the target vector
  77761. */
  77762. Bone.prototype.getScaleToRef = function (result) {
  77763. this._decompose();
  77764. result.copyFrom(this._localScaling);
  77765. };
  77766. /**
  77767. * Set the yaw, pitch, and roll of the bone in local or world space
  77768. * @param yaw The rotation of the bone on the y axis
  77769. * @param pitch The rotation of the bone on the x axis
  77770. * @param roll The rotation of the bone on the z axis
  77771. * @param space The space that the axes of rotation are in
  77772. * @param mesh The mesh that this bone is attached to. This is only used in world space
  77773. */
  77774. Bone.prototype.setYawPitchRoll = function (yaw, pitch, roll, space, mesh) {
  77775. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  77776. if (space === BABYLON.Space.LOCAL) {
  77777. var quat = Bone._tmpQuat;
  77778. BABYLON.Quaternion.RotationYawPitchRollToRef(yaw, pitch, roll, quat);
  77779. this.setRotationQuaternion(quat, space, mesh);
  77780. return;
  77781. }
  77782. var rotMatInv = Bone._tmpMats[0];
  77783. if (!this._getNegativeRotationToRef(rotMatInv, mesh)) {
  77784. return;
  77785. }
  77786. var rotMat = Bone._tmpMats[1];
  77787. BABYLON.Matrix.RotationYawPitchRollToRef(yaw, pitch, roll, rotMat);
  77788. rotMatInv.multiplyToRef(rotMat, rotMat);
  77789. this._rotateWithMatrix(rotMat, space, mesh);
  77790. };
  77791. /**
  77792. * Add a rotation to the bone on an axis in local or world space
  77793. * @param axis The axis to rotate the bone on
  77794. * @param amount The amount to rotate the bone
  77795. * @param space The space that the axis is in
  77796. * @param mesh The mesh that this bone is attached to. This is only used in world space
  77797. */
  77798. Bone.prototype.rotate = function (axis, amount, space, mesh) {
  77799. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  77800. var rmat = Bone._tmpMats[0];
  77801. rmat.m[12] = 0;
  77802. rmat.m[13] = 0;
  77803. rmat.m[14] = 0;
  77804. BABYLON.Matrix.RotationAxisToRef(axis, amount, rmat);
  77805. this._rotateWithMatrix(rmat, space, mesh);
  77806. };
  77807. /**
  77808. * Set the rotation of the bone to a particular axis angle in local or world space
  77809. * @param axis The axis to rotate the bone on
  77810. * @param angle The angle that the bone should be rotated to
  77811. * @param space The space that the axis is in
  77812. * @param mesh The mesh that this bone is attached to. This is only used in world space
  77813. */
  77814. Bone.prototype.setAxisAngle = function (axis, angle, space, mesh) {
  77815. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  77816. if (space === BABYLON.Space.LOCAL) {
  77817. var quat = Bone._tmpQuat;
  77818. BABYLON.Quaternion.RotationAxisToRef(axis, angle, quat);
  77819. this.setRotationQuaternion(quat, space, mesh);
  77820. return;
  77821. }
  77822. var rotMatInv = Bone._tmpMats[0];
  77823. if (!this._getNegativeRotationToRef(rotMatInv, mesh)) {
  77824. return;
  77825. }
  77826. var rotMat = Bone._tmpMats[1];
  77827. BABYLON.Matrix.RotationAxisToRef(axis, angle, rotMat);
  77828. rotMatInv.multiplyToRef(rotMat, rotMat);
  77829. this._rotateWithMatrix(rotMat, space, mesh);
  77830. };
  77831. /**
  77832. * Set the euler rotation of the bone in local of world space
  77833. * @param rotation The euler rotation that the bone should be set to
  77834. * @param space The space that the rotation is in
  77835. * @param mesh The mesh that this bone is attached to. This is only used in world space
  77836. */
  77837. Bone.prototype.setRotation = function (rotation, space, mesh) {
  77838. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  77839. this.setYawPitchRoll(rotation.y, rotation.x, rotation.z, space, mesh);
  77840. };
  77841. /**
  77842. * Set the quaternion rotation of the bone in local of world space
  77843. * @param quat The quaternion rotation that the bone should be set to
  77844. * @param space The space that the rotation is in
  77845. * @param mesh The mesh that this bone is attached to. This is only used in world space
  77846. */
  77847. Bone.prototype.setRotationQuaternion = function (quat, space, mesh) {
  77848. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  77849. if (space === BABYLON.Space.LOCAL) {
  77850. this._decompose();
  77851. this._localRotation.copyFrom(quat);
  77852. this._markAsDirtyAndCompose();
  77853. return;
  77854. }
  77855. var rotMatInv = Bone._tmpMats[0];
  77856. if (!this._getNegativeRotationToRef(rotMatInv, mesh)) {
  77857. return;
  77858. }
  77859. var rotMat = Bone._tmpMats[1];
  77860. BABYLON.Matrix.FromQuaternionToRef(quat, rotMat);
  77861. rotMatInv.multiplyToRef(rotMat, rotMat);
  77862. this._rotateWithMatrix(rotMat, space, mesh);
  77863. };
  77864. /**
  77865. * Set the rotation matrix of the bone in local of world space
  77866. * @param rotMat The rotation matrix that the bone should be set to
  77867. * @param space The space that the rotation is in
  77868. * @param mesh The mesh that this bone is attached to. This is only used in world space
  77869. */
  77870. Bone.prototype.setRotationMatrix = function (rotMat, space, mesh) {
  77871. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  77872. if (space === BABYLON.Space.LOCAL) {
  77873. var quat = Bone._tmpQuat;
  77874. BABYLON.Quaternion.FromRotationMatrixToRef(rotMat, quat);
  77875. this.setRotationQuaternion(quat, space, mesh);
  77876. return;
  77877. }
  77878. var rotMatInv = Bone._tmpMats[0];
  77879. if (!this._getNegativeRotationToRef(rotMatInv, mesh)) {
  77880. return;
  77881. }
  77882. var rotMat2 = Bone._tmpMats[1];
  77883. rotMat2.copyFrom(rotMat);
  77884. rotMatInv.multiplyToRef(rotMat, rotMat2);
  77885. this._rotateWithMatrix(rotMat2, space, mesh);
  77886. };
  77887. Bone.prototype._rotateWithMatrix = function (rmat, space, mesh) {
  77888. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  77889. var lmat = this.getLocalMatrix();
  77890. var lx = lmat.m[12];
  77891. var ly = lmat.m[13];
  77892. var lz = lmat.m[14];
  77893. var parent = this.getParent();
  77894. var parentScale = Bone._tmpMats[3];
  77895. var parentScaleInv = Bone._tmpMats[4];
  77896. if (parent && space == BABYLON.Space.WORLD) {
  77897. if (mesh) {
  77898. parentScale.copyFrom(mesh.getWorldMatrix());
  77899. parent.getAbsoluteTransform().multiplyToRef(parentScale, parentScale);
  77900. }
  77901. else {
  77902. parentScale.copyFrom(parent.getAbsoluteTransform());
  77903. }
  77904. parentScaleInv.copyFrom(parentScale);
  77905. parentScaleInv.invert();
  77906. lmat.multiplyToRef(parentScale, lmat);
  77907. lmat.multiplyToRef(rmat, lmat);
  77908. lmat.multiplyToRef(parentScaleInv, lmat);
  77909. }
  77910. else {
  77911. if (space == BABYLON.Space.WORLD && mesh) {
  77912. parentScale.copyFrom(mesh.getWorldMatrix());
  77913. parentScaleInv.copyFrom(parentScale);
  77914. parentScaleInv.invert();
  77915. lmat.multiplyToRef(parentScale, lmat);
  77916. lmat.multiplyToRef(rmat, lmat);
  77917. lmat.multiplyToRef(parentScaleInv, lmat);
  77918. }
  77919. else {
  77920. lmat.multiplyToRef(rmat, lmat);
  77921. }
  77922. }
  77923. lmat.m[12] = lx;
  77924. lmat.m[13] = ly;
  77925. lmat.m[14] = lz;
  77926. this.computeAbsoluteTransforms();
  77927. this._markAsDirtyAndDecompose();
  77928. };
  77929. Bone.prototype._getNegativeRotationToRef = function (rotMatInv, mesh) {
  77930. var scaleMatrix = Bone._tmpMats[2];
  77931. rotMatInv.copyFrom(this.getAbsoluteTransform());
  77932. if (mesh) {
  77933. rotMatInv.multiplyToRef(mesh.getWorldMatrix(), rotMatInv);
  77934. BABYLON.Matrix.ScalingToRef(mesh.scaling.x, mesh.scaling.y, mesh.scaling.z, scaleMatrix);
  77935. }
  77936. rotMatInv.invert();
  77937. if (isNaN(rotMatInv.m[0])) {
  77938. // Matrix failed to invert.
  77939. // This can happen if scale is zero for example.
  77940. return false;
  77941. }
  77942. scaleMatrix.m[0] *= this._scalingDeterminant;
  77943. rotMatInv.multiplyToRef(scaleMatrix, rotMatInv);
  77944. return true;
  77945. };
  77946. /**
  77947. * Get the position of the bone in local or world space
  77948. * @param space The space that the returned position is in
  77949. * @param mesh The mesh that this bone is attached to. This is only used in world space
  77950. * @returns The position of the bone
  77951. */
  77952. Bone.prototype.getPosition = function (space, mesh) {
  77953. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  77954. if (mesh === void 0) { mesh = null; }
  77955. var pos = BABYLON.Vector3.Zero();
  77956. this.getPositionToRef(space, mesh, pos);
  77957. return pos;
  77958. };
  77959. /**
  77960. * Copy the position of the bone to a vector3 in local or world space
  77961. * @param space The space that the returned position is in
  77962. * @param mesh The mesh that this bone is attached to. This is only used in world space
  77963. * @param result The vector3 to copy the position to
  77964. */
  77965. Bone.prototype.getPositionToRef = function (space, mesh, result) {
  77966. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  77967. if (space == BABYLON.Space.LOCAL) {
  77968. var lm = this.getLocalMatrix();
  77969. result.x = lm.m[12];
  77970. result.y = lm.m[13];
  77971. result.z = lm.m[14];
  77972. }
  77973. else {
  77974. var wm = null;
  77975. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  77976. if (mesh) {
  77977. wm = mesh.getWorldMatrix();
  77978. }
  77979. this._skeleton.computeAbsoluteTransforms();
  77980. var tmat = Bone._tmpMats[0];
  77981. if (mesh && wm) {
  77982. tmat.copyFrom(this.getAbsoluteTransform());
  77983. tmat.multiplyToRef(wm, tmat);
  77984. }
  77985. else {
  77986. tmat = this.getAbsoluteTransform();
  77987. }
  77988. result.x = tmat.m[12];
  77989. result.y = tmat.m[13];
  77990. result.z = tmat.m[14];
  77991. }
  77992. };
  77993. /**
  77994. * Get the absolute position of the bone (world space)
  77995. * @param mesh The mesh that this bone is attached to
  77996. * @returns The absolute position of the bone
  77997. */
  77998. Bone.prototype.getAbsolutePosition = function (mesh) {
  77999. if (mesh === void 0) { mesh = null; }
  78000. var pos = BABYLON.Vector3.Zero();
  78001. this.getPositionToRef(BABYLON.Space.WORLD, mesh, pos);
  78002. return pos;
  78003. };
  78004. /**
  78005. * Copy the absolute position of the bone (world space) to the result param
  78006. * @param mesh The mesh that this bone is attached to
  78007. * @param result The vector3 to copy the absolute position to
  78008. */
  78009. Bone.prototype.getAbsolutePositionToRef = function (mesh, result) {
  78010. this.getPositionToRef(BABYLON.Space.WORLD, mesh, result);
  78011. };
  78012. /**
  78013. * Compute the absolute transforms of this bone and its children
  78014. */
  78015. Bone.prototype.computeAbsoluteTransforms = function () {
  78016. this._compose();
  78017. if (this._parent) {
  78018. this._localMatrix.multiplyToRef(this._parent._absoluteTransform, this._absoluteTransform);
  78019. }
  78020. else {
  78021. this._absoluteTransform.copyFrom(this._localMatrix);
  78022. var poseMatrix = this._skeleton.getPoseMatrix();
  78023. if (poseMatrix) {
  78024. this._absoluteTransform.multiplyToRef(poseMatrix, this._absoluteTransform);
  78025. }
  78026. }
  78027. var children = this.children;
  78028. var len = children.length;
  78029. for (var i = 0; i < len; i++) {
  78030. children[i].computeAbsoluteTransforms();
  78031. }
  78032. };
  78033. /**
  78034. * Get the world direction from an axis that is in the local space of the bone
  78035. * @param localAxis The local direction that is used to compute the world direction
  78036. * @param mesh The mesh that this bone is attached to
  78037. * @returns The world direction
  78038. */
  78039. Bone.prototype.getDirection = function (localAxis, mesh) {
  78040. if (mesh === void 0) { mesh = null; }
  78041. var result = BABYLON.Vector3.Zero();
  78042. this.getDirectionToRef(localAxis, mesh, result);
  78043. return result;
  78044. };
  78045. /**
  78046. * Copy the world direction to a vector3 from an axis that is in the local space of the bone
  78047. * @param localAxis The local direction that is used to compute the world direction
  78048. * @param mesh The mesh that this bone is attached to
  78049. * @param result The vector3 that the world direction will be copied to
  78050. */
  78051. Bone.prototype.getDirectionToRef = function (localAxis, mesh, result) {
  78052. if (mesh === void 0) { mesh = null; }
  78053. var wm = null;
  78054. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  78055. if (mesh) {
  78056. wm = mesh.getWorldMatrix();
  78057. }
  78058. this._skeleton.computeAbsoluteTransforms();
  78059. var mat = Bone._tmpMats[0];
  78060. mat.copyFrom(this.getAbsoluteTransform());
  78061. if (mesh && wm) {
  78062. mat.multiplyToRef(wm, mat);
  78063. }
  78064. BABYLON.Vector3.TransformNormalToRef(localAxis, mat, result);
  78065. result.normalize();
  78066. };
  78067. /**
  78068. * Get the euler rotation of the bone in local or world space
  78069. * @param space The space that the rotation should be in
  78070. * @param mesh The mesh that this bone is attached to. This is only used in world space
  78071. * @returns The euler rotation
  78072. */
  78073. Bone.prototype.getRotation = function (space, mesh) {
  78074. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  78075. if (mesh === void 0) { mesh = null; }
  78076. var result = BABYLON.Vector3.Zero();
  78077. this.getRotationToRef(space, mesh, result);
  78078. return result;
  78079. };
  78080. /**
  78081. * Copy the euler rotation of the bone to a vector3. The rotation can be in either local or world space
  78082. * @param space The space that the rotation should be in
  78083. * @param mesh The mesh that this bone is attached to. This is only used in world space
  78084. * @param result The vector3 that the rotation should be copied to
  78085. */
  78086. Bone.prototype.getRotationToRef = function (space, mesh, result) {
  78087. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  78088. if (mesh === void 0) { mesh = null; }
  78089. var quat = Bone._tmpQuat;
  78090. this.getRotationQuaternionToRef(space, mesh, quat);
  78091. quat.toEulerAnglesToRef(result);
  78092. };
  78093. /**
  78094. * Get the quaternion rotation of the bone in either local or world space
  78095. * @param space The space that the rotation should be in
  78096. * @param mesh The mesh that this bone is attached to. This is only used in world space
  78097. * @returns The quaternion rotation
  78098. */
  78099. Bone.prototype.getRotationQuaternion = function (space, mesh) {
  78100. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  78101. if (mesh === void 0) { mesh = null; }
  78102. var result = BABYLON.Quaternion.Identity();
  78103. this.getRotationQuaternionToRef(space, mesh, result);
  78104. return result;
  78105. };
  78106. /**
  78107. * Copy the quaternion rotation of the bone to a quaternion. The rotation can be in either local or world space
  78108. * @param space The space that the rotation should be in
  78109. * @param mesh The mesh that this bone is attached to. This is only used in world space
  78110. * @param result The quaternion that the rotation should be copied to
  78111. */
  78112. Bone.prototype.getRotationQuaternionToRef = function (space, mesh, result) {
  78113. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  78114. if (mesh === void 0) { mesh = null; }
  78115. if (space == BABYLON.Space.LOCAL) {
  78116. this._decompose();
  78117. result.copyFrom(this._localRotation);
  78118. }
  78119. else {
  78120. var mat = Bone._tmpMats[0];
  78121. var amat = this.getAbsoluteTransform();
  78122. if (mesh) {
  78123. amat.multiplyToRef(mesh.getWorldMatrix(), mat);
  78124. }
  78125. else {
  78126. mat.copyFrom(amat);
  78127. }
  78128. mat.m[0] *= this._scalingDeterminant;
  78129. mat.m[1] *= this._scalingDeterminant;
  78130. mat.m[2] *= this._scalingDeterminant;
  78131. mat.decompose(undefined, result, undefined);
  78132. }
  78133. };
  78134. /**
  78135. * Get the rotation matrix of the bone in local or world space
  78136. * @param space The space that the rotation should be in
  78137. * @param mesh The mesh that this bone is attached to. This is only used in world space
  78138. * @returns The rotation matrix
  78139. */
  78140. Bone.prototype.getRotationMatrix = function (space, mesh) {
  78141. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  78142. var result = BABYLON.Matrix.Identity();
  78143. this.getRotationMatrixToRef(space, mesh, result);
  78144. return result;
  78145. };
  78146. /**
  78147. * Copy the rotation matrix of the bone to a matrix. The rotation can be in either local or world space
  78148. * @param space The space that the rotation should be in
  78149. * @param mesh The mesh that this bone is attached to. This is only used in world space
  78150. * @param result The quaternion that the rotation should be copied to
  78151. */
  78152. Bone.prototype.getRotationMatrixToRef = function (space, mesh, result) {
  78153. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  78154. if (space == BABYLON.Space.LOCAL) {
  78155. this.getLocalMatrix().getRotationMatrixToRef(result);
  78156. }
  78157. else {
  78158. var mat = Bone._tmpMats[0];
  78159. var amat = this.getAbsoluteTransform();
  78160. if (mesh) {
  78161. amat.multiplyToRef(mesh.getWorldMatrix(), mat);
  78162. }
  78163. else {
  78164. mat.copyFrom(amat);
  78165. }
  78166. mat.m[0] *= this._scalingDeterminant;
  78167. mat.m[1] *= this._scalingDeterminant;
  78168. mat.m[2] *= this._scalingDeterminant;
  78169. mat.getRotationMatrixToRef(result);
  78170. }
  78171. };
  78172. /**
  78173. * Get the world position of a point that is in the local space of the bone
  78174. * @param position The local position
  78175. * @param mesh The mesh that this bone is attached to
  78176. * @returns The world position
  78177. */
  78178. Bone.prototype.getAbsolutePositionFromLocal = function (position, mesh) {
  78179. if (mesh === void 0) { mesh = null; }
  78180. var result = BABYLON.Vector3.Zero();
  78181. this.getAbsolutePositionFromLocalToRef(position, mesh, result);
  78182. return result;
  78183. };
  78184. /**
  78185. * Get the world position of a point that is in the local space of the bone and copy it to the result param
  78186. * @param position The local position
  78187. * @param mesh The mesh that this bone is attached to
  78188. * @param result The vector3 that the world position should be copied to
  78189. */
  78190. Bone.prototype.getAbsolutePositionFromLocalToRef = function (position, mesh, result) {
  78191. if (mesh === void 0) { mesh = null; }
  78192. var wm = null;
  78193. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  78194. if (mesh) {
  78195. wm = mesh.getWorldMatrix();
  78196. }
  78197. this._skeleton.computeAbsoluteTransforms();
  78198. var tmat = Bone._tmpMats[0];
  78199. if (mesh && wm) {
  78200. tmat.copyFrom(this.getAbsoluteTransform());
  78201. tmat.multiplyToRef(wm, tmat);
  78202. }
  78203. else {
  78204. tmat = this.getAbsoluteTransform();
  78205. }
  78206. BABYLON.Vector3.TransformCoordinatesToRef(position, tmat, result);
  78207. };
  78208. /**
  78209. * Get the local position of a point that is in world space
  78210. * @param position The world position
  78211. * @param mesh The mesh that this bone is attached to
  78212. * @returns The local position
  78213. */
  78214. Bone.prototype.getLocalPositionFromAbsolute = function (position, mesh) {
  78215. if (mesh === void 0) { mesh = null; }
  78216. var result = BABYLON.Vector3.Zero();
  78217. this.getLocalPositionFromAbsoluteToRef(position, mesh, result);
  78218. return result;
  78219. };
  78220. /**
  78221. * Get the local position of a point that is in world space and copy it to the result param
  78222. * @param position The world position
  78223. * @param mesh The mesh that this bone is attached to
  78224. * @param result The vector3 that the local position should be copied to
  78225. */
  78226. Bone.prototype.getLocalPositionFromAbsoluteToRef = function (position, mesh, result) {
  78227. if (mesh === void 0) { mesh = null; }
  78228. var wm = null;
  78229. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  78230. if (mesh) {
  78231. wm = mesh.getWorldMatrix();
  78232. }
  78233. this._skeleton.computeAbsoluteTransforms();
  78234. var tmat = Bone._tmpMats[0];
  78235. tmat.copyFrom(this.getAbsoluteTransform());
  78236. if (mesh && wm) {
  78237. tmat.multiplyToRef(wm, tmat);
  78238. }
  78239. tmat.invert();
  78240. BABYLON.Vector3.TransformCoordinatesToRef(position, tmat, result);
  78241. };
  78242. Bone._tmpVecs = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  78243. Bone._tmpQuat = BABYLON.Quaternion.Identity();
  78244. Bone._tmpMats = [BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity()];
  78245. return Bone;
  78246. }(BABYLON.Node));
  78247. BABYLON.Bone = Bone;
  78248. })(BABYLON || (BABYLON = {}));
  78249. //# sourceMappingURL=babylon.bone.js.map
  78250. var BABYLON;
  78251. (function (BABYLON) {
  78252. /**
  78253. * Class used to apply inverse kinematics to bones
  78254. * @see http://doc.babylonjs.com/how_to/how_to_use_bones_and_skeletons#boneikcontroller
  78255. */
  78256. var BoneIKController = /** @class */ (function () {
  78257. /**
  78258. * Creates a new BoneIKController
  78259. * @param mesh defines the mesh to control
  78260. * @param bone defines the bone to control
  78261. * @param options defines options to set up the controller
  78262. */
  78263. function BoneIKController(mesh, bone, options) {
  78264. /**
  78265. * Gets or sets the target position
  78266. */
  78267. this.targetPosition = BABYLON.Vector3.Zero();
  78268. /**
  78269. * Gets or sets the pole target position
  78270. */
  78271. this.poleTargetPosition = BABYLON.Vector3.Zero();
  78272. /**
  78273. * Gets or sets the pole target local offset
  78274. */
  78275. this.poleTargetLocalOffset = BABYLON.Vector3.Zero();
  78276. /**
  78277. * Gets or sets the pole angle
  78278. */
  78279. this.poleAngle = 0;
  78280. /**
  78281. * 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)
  78282. */
  78283. this.slerpAmount = 1;
  78284. this._bone1Quat = BABYLON.Quaternion.Identity();
  78285. this._bone1Mat = BABYLON.Matrix.Identity();
  78286. this._bone2Ang = Math.PI;
  78287. this._maxAngle = Math.PI;
  78288. this._rightHandedSystem = false;
  78289. this._bendAxis = BABYLON.Vector3.Right();
  78290. this._slerping = false;
  78291. this._adjustRoll = 0;
  78292. this._bone2 = bone;
  78293. this._bone1 = bone.getParent();
  78294. if (!this._bone1) {
  78295. return;
  78296. }
  78297. this.mesh = mesh;
  78298. var bonePos = bone.getPosition();
  78299. if (bone.getAbsoluteTransform().determinant() > 0) {
  78300. this._rightHandedSystem = true;
  78301. this._bendAxis.x = 0;
  78302. this._bendAxis.y = 0;
  78303. this._bendAxis.z = -1;
  78304. if (bonePos.x > bonePos.y && bonePos.x > bonePos.z) {
  78305. this._adjustRoll = Math.PI * .5;
  78306. this._bendAxis.z = 1;
  78307. }
  78308. }
  78309. if (this._bone1.length) {
  78310. var boneScale1 = this._bone1.getScale();
  78311. var boneScale2 = this._bone2.getScale();
  78312. this._bone1Length = this._bone1.length * boneScale1.y * this.mesh.scaling.y;
  78313. this._bone2Length = this._bone2.length * boneScale2.y * this.mesh.scaling.y;
  78314. }
  78315. else if (this._bone1.children[0]) {
  78316. mesh.computeWorldMatrix(true);
  78317. var pos1 = this._bone2.children[0].getAbsolutePosition(mesh);
  78318. var pos2 = this._bone2.getAbsolutePosition(mesh);
  78319. var pos3 = this._bone1.getAbsolutePosition(mesh);
  78320. this._bone1Length = BABYLON.Vector3.Distance(pos1, pos2);
  78321. this._bone2Length = BABYLON.Vector3.Distance(pos2, pos3);
  78322. }
  78323. this._bone1.getRotationMatrixToRef(BABYLON.Space.WORLD, mesh, this._bone1Mat);
  78324. this.maxAngle = Math.PI;
  78325. if (options) {
  78326. if (options.targetMesh) {
  78327. this.targetMesh = options.targetMesh;
  78328. this.targetMesh.computeWorldMatrix(true);
  78329. }
  78330. if (options.poleTargetMesh) {
  78331. this.poleTargetMesh = options.poleTargetMesh;
  78332. this.poleTargetMesh.computeWorldMatrix(true);
  78333. }
  78334. else if (options.poleTargetBone) {
  78335. this.poleTargetBone = options.poleTargetBone;
  78336. }
  78337. else if (this._bone1.getParent()) {
  78338. this.poleTargetBone = this._bone1.getParent();
  78339. }
  78340. if (options.poleTargetLocalOffset) {
  78341. this.poleTargetLocalOffset.copyFrom(options.poleTargetLocalOffset);
  78342. }
  78343. if (options.poleAngle) {
  78344. this.poleAngle = options.poleAngle;
  78345. }
  78346. if (options.bendAxis) {
  78347. this._bendAxis.copyFrom(options.bendAxis);
  78348. }
  78349. if (options.maxAngle) {
  78350. this.maxAngle = options.maxAngle;
  78351. }
  78352. if (options.slerpAmount) {
  78353. this.slerpAmount = options.slerpAmount;
  78354. }
  78355. }
  78356. }
  78357. Object.defineProperty(BoneIKController.prototype, "maxAngle", {
  78358. /**
  78359. * Gets or sets maximum allowed angle
  78360. */
  78361. get: function () {
  78362. return this._maxAngle;
  78363. },
  78364. set: function (value) {
  78365. this._setMaxAngle(value);
  78366. },
  78367. enumerable: true,
  78368. configurable: true
  78369. });
  78370. BoneIKController.prototype._setMaxAngle = function (ang) {
  78371. if (ang < 0) {
  78372. ang = 0;
  78373. }
  78374. if (ang > Math.PI || ang == undefined) {
  78375. ang = Math.PI;
  78376. }
  78377. this._maxAngle = ang;
  78378. var a = this._bone1Length;
  78379. var b = this._bone2Length;
  78380. this._maxReach = Math.sqrt(a * a + b * b - 2 * a * b * Math.cos(ang));
  78381. };
  78382. /**
  78383. * Force the controller to update the bones
  78384. */
  78385. BoneIKController.prototype.update = function () {
  78386. var bone1 = this._bone1;
  78387. if (!bone1) {
  78388. return;
  78389. }
  78390. var target = this.targetPosition;
  78391. var poleTarget = this.poleTargetPosition;
  78392. var mat1 = BoneIKController._tmpMats[0];
  78393. var mat2 = BoneIKController._tmpMats[1];
  78394. if (this.targetMesh) {
  78395. target.copyFrom(this.targetMesh.getAbsolutePosition());
  78396. }
  78397. if (this.poleTargetBone) {
  78398. this.poleTargetBone.getAbsolutePositionFromLocalToRef(this.poleTargetLocalOffset, this.mesh, poleTarget);
  78399. }
  78400. else if (this.poleTargetMesh) {
  78401. BABYLON.Vector3.TransformCoordinatesToRef(this.poleTargetLocalOffset, this.poleTargetMesh.getWorldMatrix(), poleTarget);
  78402. }
  78403. var bonePos = BoneIKController._tmpVecs[0];
  78404. var zaxis = BoneIKController._tmpVecs[1];
  78405. var xaxis = BoneIKController._tmpVecs[2];
  78406. var yaxis = BoneIKController._tmpVecs[3];
  78407. var upAxis = BoneIKController._tmpVecs[4];
  78408. var _tmpQuat = BoneIKController._tmpQuat;
  78409. bone1.getAbsolutePositionToRef(this.mesh, bonePos);
  78410. poleTarget.subtractToRef(bonePos, upAxis);
  78411. if (upAxis.x == 0 && upAxis.y == 0 && upAxis.z == 0) {
  78412. upAxis.y = 1;
  78413. }
  78414. else {
  78415. upAxis.normalize();
  78416. }
  78417. target.subtractToRef(bonePos, yaxis);
  78418. yaxis.normalize();
  78419. BABYLON.Vector3.CrossToRef(yaxis, upAxis, zaxis);
  78420. zaxis.normalize();
  78421. BABYLON.Vector3.CrossToRef(yaxis, zaxis, xaxis);
  78422. xaxis.normalize();
  78423. BABYLON.Matrix.FromXYZAxesToRef(xaxis, yaxis, zaxis, mat1);
  78424. var a = this._bone1Length;
  78425. var b = this._bone2Length;
  78426. var c = BABYLON.Vector3.Distance(bonePos, target);
  78427. if (this._maxReach > 0) {
  78428. c = Math.min(this._maxReach, c);
  78429. }
  78430. var acosa = (b * b + c * c - a * a) / (2 * b * c);
  78431. var acosb = (c * c + a * a - b * b) / (2 * c * a);
  78432. if (acosa > 1) {
  78433. acosa = 1;
  78434. }
  78435. if (acosb > 1) {
  78436. acosb = 1;
  78437. }
  78438. if (acosa < -1) {
  78439. acosa = -1;
  78440. }
  78441. if (acosb < -1) {
  78442. acosb = -1;
  78443. }
  78444. var angA = Math.acos(acosa);
  78445. var angB = Math.acos(acosb);
  78446. var angC = -angA - angB;
  78447. if (this._rightHandedSystem) {
  78448. BABYLON.Matrix.RotationYawPitchRollToRef(0, 0, this._adjustRoll, mat2);
  78449. mat2.multiplyToRef(mat1, mat1);
  78450. BABYLON.Matrix.RotationAxisToRef(this._bendAxis, angB, mat2);
  78451. mat2.multiplyToRef(mat1, mat1);
  78452. }
  78453. else {
  78454. var _tmpVec = BoneIKController._tmpVecs[5];
  78455. _tmpVec.copyFrom(this._bendAxis);
  78456. _tmpVec.x *= -1;
  78457. BABYLON.Matrix.RotationAxisToRef(_tmpVec, -angB, mat2);
  78458. mat2.multiplyToRef(mat1, mat1);
  78459. }
  78460. if (this.poleAngle) {
  78461. BABYLON.Matrix.RotationAxisToRef(yaxis, this.poleAngle, mat2);
  78462. mat1.multiplyToRef(mat2, mat1);
  78463. }
  78464. if (this._bone1) {
  78465. if (this.slerpAmount < 1) {
  78466. if (!this._slerping) {
  78467. BABYLON.Quaternion.FromRotationMatrixToRef(this._bone1Mat, this._bone1Quat);
  78468. }
  78469. BABYLON.Quaternion.FromRotationMatrixToRef(mat1, _tmpQuat);
  78470. BABYLON.Quaternion.SlerpToRef(this._bone1Quat, _tmpQuat, this.slerpAmount, this._bone1Quat);
  78471. angC = this._bone2Ang * (1.0 - this.slerpAmount) + angC * this.slerpAmount;
  78472. this._bone1.setRotationQuaternion(this._bone1Quat, BABYLON.Space.WORLD, this.mesh);
  78473. this._slerping = true;
  78474. }
  78475. else {
  78476. this._bone1.setRotationMatrix(mat1, BABYLON.Space.WORLD, this.mesh);
  78477. this._bone1Mat.copyFrom(mat1);
  78478. this._slerping = false;
  78479. }
  78480. }
  78481. this._bone2.setAxisAngle(this._bendAxis, angC, BABYLON.Space.LOCAL);
  78482. this._bone2Ang = angC;
  78483. };
  78484. BoneIKController._tmpVecs = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  78485. BoneIKController._tmpQuat = BABYLON.Quaternion.Identity();
  78486. BoneIKController._tmpMats = [BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity()];
  78487. return BoneIKController;
  78488. }());
  78489. BABYLON.BoneIKController = BoneIKController;
  78490. })(BABYLON || (BABYLON = {}));
  78491. //# sourceMappingURL=babylon.boneIKController.js.map
  78492. var BABYLON;
  78493. (function (BABYLON) {
  78494. /**
  78495. * Class used to make a bone look toward a point in space
  78496. * @see http://doc.babylonjs.com/how_to/how_to_use_bones_and_skeletons#bonelookcontroller
  78497. */
  78498. var BoneLookController = /** @class */ (function () {
  78499. /**
  78500. * Create a BoneLookController
  78501. * @param mesh the mesh that the bone belongs to
  78502. * @param bone the bone that will be looking to the target
  78503. * @param target the target Vector3 to look at
  78504. * @param settings optional settings:
  78505. * * maxYaw: the maximum angle the bone will yaw to
  78506. * * minYaw: the minimum angle the bone will yaw to
  78507. * * maxPitch: the maximum angle the bone will pitch to
  78508. * * minPitch: the minimum angle the bone will yaw to
  78509. * * slerpAmount: set the between 0 and 1 to make the bone slerp to the target.
  78510. * * upAxis: the up axis of the coordinate system
  78511. * * upAxisSpace: the space that the up axis is in - BABYLON.Space.BONE, BABYLON.Space.LOCAL (default), or BABYLON.Space.WORLD.
  78512. * * yawAxis: set yawAxis if the bone does not yaw on the y axis
  78513. * * pitchAxis: set pitchAxis if the bone does not pitch on the x axis
  78514. * * adjustYaw: used to make an adjustment to the yaw of the bone
  78515. * * adjustPitch: used to make an adjustment to the pitch of the bone
  78516. * * adjustRoll: used to make an adjustment to the roll of the bone
  78517. **/
  78518. function BoneLookController(mesh, bone, target, options) {
  78519. /**
  78520. * The up axis of the coordinate system that is used when the bone is rotated
  78521. */
  78522. this.upAxis = BABYLON.Vector3.Up();
  78523. /**
  78524. * The space that the up axis is in - BABYLON.Space.BONE, BABYLON.Space.LOCAL (default), or BABYLON.Space.WORLD
  78525. */
  78526. this.upAxisSpace = BABYLON.Space.LOCAL;
  78527. /**
  78528. * Used to make an adjustment to the yaw of the bone
  78529. */
  78530. this.adjustYaw = 0;
  78531. /**
  78532. * Used to make an adjustment to the pitch of the bone
  78533. */
  78534. this.adjustPitch = 0;
  78535. /**
  78536. * Used to make an adjustment to the roll of the bone
  78537. */
  78538. this.adjustRoll = 0;
  78539. /**
  78540. * 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)
  78541. */
  78542. this.slerpAmount = 1;
  78543. this._boneQuat = BABYLON.Quaternion.Identity();
  78544. this._slerping = false;
  78545. this._firstFrameSkipped = false;
  78546. this._fowardAxis = BABYLON.Vector3.Forward();
  78547. this.mesh = mesh;
  78548. this.bone = bone;
  78549. this.target = target;
  78550. if (options) {
  78551. if (options.adjustYaw) {
  78552. this.adjustYaw = options.adjustYaw;
  78553. }
  78554. if (options.adjustPitch) {
  78555. this.adjustPitch = options.adjustPitch;
  78556. }
  78557. if (options.adjustRoll) {
  78558. this.adjustRoll = options.adjustRoll;
  78559. }
  78560. if (options.maxYaw != null) {
  78561. this.maxYaw = options.maxYaw;
  78562. }
  78563. else {
  78564. this.maxYaw = Math.PI;
  78565. }
  78566. if (options.minYaw != null) {
  78567. this.minYaw = options.minYaw;
  78568. }
  78569. else {
  78570. this.minYaw = -Math.PI;
  78571. }
  78572. if (options.maxPitch != null) {
  78573. this.maxPitch = options.maxPitch;
  78574. }
  78575. else {
  78576. this.maxPitch = Math.PI;
  78577. }
  78578. if (options.minPitch != null) {
  78579. this.minPitch = options.minPitch;
  78580. }
  78581. else {
  78582. this.minPitch = -Math.PI;
  78583. }
  78584. if (options.slerpAmount != null) {
  78585. this.slerpAmount = options.slerpAmount;
  78586. }
  78587. if (options.upAxis != null) {
  78588. this.upAxis = options.upAxis;
  78589. }
  78590. if (options.upAxisSpace != null) {
  78591. this.upAxisSpace = options.upAxisSpace;
  78592. }
  78593. if (options.yawAxis != null || options.pitchAxis != null) {
  78594. var newYawAxis = BABYLON.Axis.Y;
  78595. var newPitchAxis = BABYLON.Axis.X;
  78596. if (options.yawAxis != null) {
  78597. newYawAxis = options.yawAxis.clone();
  78598. newYawAxis.normalize();
  78599. }
  78600. if (options.pitchAxis != null) {
  78601. newPitchAxis = options.pitchAxis.clone();
  78602. newPitchAxis.normalize();
  78603. }
  78604. var newRollAxis = BABYLON.Vector3.Cross(newPitchAxis, newYawAxis);
  78605. this._transformYawPitch = BABYLON.Matrix.Identity();
  78606. BABYLON.Matrix.FromXYZAxesToRef(newPitchAxis, newYawAxis, newRollAxis, this._transformYawPitch);
  78607. this._transformYawPitchInv = this._transformYawPitch.clone();
  78608. this._transformYawPitch.invert();
  78609. }
  78610. }
  78611. if (!bone.getParent() && this.upAxisSpace == BABYLON.Space.BONE) {
  78612. this.upAxisSpace = BABYLON.Space.LOCAL;
  78613. }
  78614. }
  78615. Object.defineProperty(BoneLookController.prototype, "minYaw", {
  78616. /**
  78617. * Gets or sets the minimum yaw angle that the bone can look to
  78618. */
  78619. get: function () {
  78620. return this._minYaw;
  78621. },
  78622. set: function (value) {
  78623. this._minYaw = value;
  78624. this._minYawSin = Math.sin(value);
  78625. this._minYawCos = Math.cos(value);
  78626. if (this._maxYaw != null) {
  78627. this._midYawConstraint = this._getAngleDiff(this._minYaw, this._maxYaw) * .5 + this._minYaw;
  78628. this._yawRange = this._maxYaw - this._minYaw;
  78629. }
  78630. },
  78631. enumerable: true,
  78632. configurable: true
  78633. });
  78634. Object.defineProperty(BoneLookController.prototype, "maxYaw", {
  78635. /**
  78636. * Gets or sets the maximum yaw angle that the bone can look to
  78637. */
  78638. get: function () {
  78639. return this._maxYaw;
  78640. },
  78641. set: function (value) {
  78642. this._maxYaw = value;
  78643. this._maxYawSin = Math.sin(value);
  78644. this._maxYawCos = Math.cos(value);
  78645. if (this._minYaw != null) {
  78646. this._midYawConstraint = this._getAngleDiff(this._minYaw, this._maxYaw) * .5 + this._minYaw;
  78647. this._yawRange = this._maxYaw - this._minYaw;
  78648. }
  78649. },
  78650. enumerable: true,
  78651. configurable: true
  78652. });
  78653. Object.defineProperty(BoneLookController.prototype, "minPitch", {
  78654. /**
  78655. * Gets or sets the minimum pitch angle that the bone can look to
  78656. */
  78657. get: function () {
  78658. return this._minPitch;
  78659. },
  78660. set: function (value) {
  78661. this._minPitch = value;
  78662. this._minPitchTan = Math.tan(value);
  78663. },
  78664. enumerable: true,
  78665. configurable: true
  78666. });
  78667. Object.defineProperty(BoneLookController.prototype, "maxPitch", {
  78668. /**
  78669. * Gets or sets the maximum pitch angle that the bone can look to
  78670. */
  78671. get: function () {
  78672. return this._maxPitch;
  78673. },
  78674. set: function (value) {
  78675. this._maxPitch = value;
  78676. this._maxPitchTan = Math.tan(value);
  78677. },
  78678. enumerable: true,
  78679. configurable: true
  78680. });
  78681. /**
  78682. * Update the bone to look at the target. This should be called before the scene is rendered (use scene.registerBeforeRender())
  78683. */
  78684. BoneLookController.prototype.update = function () {
  78685. //skip the first frame when slerping so that the mesh rotation is correct
  78686. if (this.slerpAmount < 1 && !this._firstFrameSkipped) {
  78687. this._firstFrameSkipped = true;
  78688. return;
  78689. }
  78690. var bone = this.bone;
  78691. var bonePos = BoneLookController._tmpVecs[0];
  78692. bone.getAbsolutePositionToRef(this.mesh, bonePos);
  78693. var target = this.target;
  78694. var _tmpMat1 = BoneLookController._tmpMats[0];
  78695. var _tmpMat2 = BoneLookController._tmpMats[1];
  78696. var mesh = this.mesh;
  78697. var parentBone = bone.getParent();
  78698. var upAxis = BoneLookController._tmpVecs[1];
  78699. upAxis.copyFrom(this.upAxis);
  78700. if (this.upAxisSpace == BABYLON.Space.BONE && parentBone) {
  78701. if (this._transformYawPitch) {
  78702. BABYLON.Vector3.TransformCoordinatesToRef(upAxis, this._transformYawPitchInv, upAxis);
  78703. }
  78704. parentBone.getDirectionToRef(upAxis, this.mesh, upAxis);
  78705. }
  78706. else if (this.upAxisSpace == BABYLON.Space.LOCAL) {
  78707. mesh.getDirectionToRef(upAxis, upAxis);
  78708. if (mesh.scaling.x != 1 || mesh.scaling.y != 1 || mesh.scaling.z != 1) {
  78709. upAxis.normalize();
  78710. }
  78711. }
  78712. var checkYaw = false;
  78713. var checkPitch = false;
  78714. if (this._maxYaw != Math.PI || this._minYaw != -Math.PI) {
  78715. checkYaw = true;
  78716. }
  78717. if (this._maxPitch != Math.PI || this._minPitch != -Math.PI) {
  78718. checkPitch = true;
  78719. }
  78720. if (checkYaw || checkPitch) {
  78721. var spaceMat = BoneLookController._tmpMats[2];
  78722. var spaceMatInv = BoneLookController._tmpMats[3];
  78723. if (this.upAxisSpace == BABYLON.Space.BONE && upAxis.y == 1 && parentBone) {
  78724. parentBone.getRotationMatrixToRef(BABYLON.Space.WORLD, this.mesh, spaceMat);
  78725. }
  78726. else if (this.upAxisSpace == BABYLON.Space.LOCAL && upAxis.y == 1 && !parentBone) {
  78727. spaceMat.copyFrom(mesh.getWorldMatrix());
  78728. }
  78729. else {
  78730. var forwardAxis = BoneLookController._tmpVecs[2];
  78731. forwardAxis.copyFrom(this._fowardAxis);
  78732. if (this._transformYawPitch) {
  78733. BABYLON.Vector3.TransformCoordinatesToRef(forwardAxis, this._transformYawPitchInv, forwardAxis);
  78734. }
  78735. if (parentBone) {
  78736. parentBone.getDirectionToRef(forwardAxis, this.mesh, forwardAxis);
  78737. }
  78738. else {
  78739. mesh.getDirectionToRef(forwardAxis, forwardAxis);
  78740. }
  78741. var rightAxis = BABYLON.Vector3.Cross(upAxis, forwardAxis);
  78742. rightAxis.normalize();
  78743. var forwardAxis = BABYLON.Vector3.Cross(rightAxis, upAxis);
  78744. BABYLON.Matrix.FromXYZAxesToRef(rightAxis, upAxis, forwardAxis, spaceMat);
  78745. }
  78746. spaceMat.invertToRef(spaceMatInv);
  78747. var xzlen = null;
  78748. if (checkPitch) {
  78749. var localTarget = BoneLookController._tmpVecs[3];
  78750. target.subtractToRef(bonePos, localTarget);
  78751. BABYLON.Vector3.TransformCoordinatesToRef(localTarget, spaceMatInv, localTarget);
  78752. xzlen = Math.sqrt(localTarget.x * localTarget.x + localTarget.z * localTarget.z);
  78753. var pitch = Math.atan2(localTarget.y, xzlen);
  78754. var newPitch = pitch;
  78755. if (pitch > this._maxPitch) {
  78756. localTarget.y = this._maxPitchTan * xzlen;
  78757. newPitch = this._maxPitch;
  78758. }
  78759. else if (pitch < this._minPitch) {
  78760. localTarget.y = this._minPitchTan * xzlen;
  78761. newPitch = this._minPitch;
  78762. }
  78763. if (pitch != newPitch) {
  78764. BABYLON.Vector3.TransformCoordinatesToRef(localTarget, spaceMat, localTarget);
  78765. localTarget.addInPlace(bonePos);
  78766. target = localTarget;
  78767. }
  78768. }
  78769. if (checkYaw) {
  78770. var localTarget = BoneLookController._tmpVecs[4];
  78771. target.subtractToRef(bonePos, localTarget);
  78772. BABYLON.Vector3.TransformCoordinatesToRef(localTarget, spaceMatInv, localTarget);
  78773. var yaw = Math.atan2(localTarget.x, localTarget.z);
  78774. var newYaw = yaw;
  78775. if (yaw > this._maxYaw || yaw < this._minYaw) {
  78776. if (xzlen == null) {
  78777. xzlen = Math.sqrt(localTarget.x * localTarget.x + localTarget.z * localTarget.z);
  78778. }
  78779. if (this._yawRange > Math.PI) {
  78780. if (this._isAngleBetween(yaw, this._maxYaw, this._midYawConstraint)) {
  78781. localTarget.z = this._maxYawCos * xzlen;
  78782. localTarget.x = this._maxYawSin * xzlen;
  78783. newYaw = this._maxYaw;
  78784. }
  78785. else if (this._isAngleBetween(yaw, this._midYawConstraint, this._minYaw)) {
  78786. localTarget.z = this._minYawCos * xzlen;
  78787. localTarget.x = this._minYawSin * xzlen;
  78788. newYaw = this._minYaw;
  78789. }
  78790. }
  78791. else {
  78792. if (yaw > this._maxYaw) {
  78793. localTarget.z = this._maxYawCos * xzlen;
  78794. localTarget.x = this._maxYawSin * xzlen;
  78795. newYaw = this._maxYaw;
  78796. }
  78797. else if (yaw < this._minYaw) {
  78798. localTarget.z = this._minYawCos * xzlen;
  78799. localTarget.x = this._minYawSin * xzlen;
  78800. newYaw = this._minYaw;
  78801. }
  78802. }
  78803. }
  78804. if (this._slerping && this._yawRange > Math.PI) {
  78805. //are we going to be crossing into the min/max region?
  78806. var boneFwd = BoneLookController._tmpVecs[8];
  78807. boneFwd.copyFrom(BABYLON.Axis.Z);
  78808. if (this._transformYawPitch) {
  78809. BABYLON.Vector3.TransformCoordinatesToRef(boneFwd, this._transformYawPitchInv, boneFwd);
  78810. }
  78811. var boneRotMat = BoneLookController._tmpMats[4];
  78812. this._boneQuat.toRotationMatrix(boneRotMat);
  78813. this.mesh.getWorldMatrix().multiplyToRef(boneRotMat, boneRotMat);
  78814. BABYLON.Vector3.TransformCoordinatesToRef(boneFwd, boneRotMat, boneFwd);
  78815. BABYLON.Vector3.TransformCoordinatesToRef(boneFwd, spaceMatInv, boneFwd);
  78816. var boneYaw = Math.atan2(boneFwd.x, boneFwd.z);
  78817. var angBtwTar = this._getAngleBetween(boneYaw, yaw);
  78818. var angBtwMidYaw = this._getAngleBetween(boneYaw, this._midYawConstraint);
  78819. if (angBtwTar > angBtwMidYaw) {
  78820. if (xzlen == null) {
  78821. xzlen = Math.sqrt(localTarget.x * localTarget.x + localTarget.z * localTarget.z);
  78822. }
  78823. var angBtwMax = this._getAngleBetween(boneYaw, this._maxYaw);
  78824. var angBtwMin = this._getAngleBetween(boneYaw, this._minYaw);
  78825. if (angBtwMin < angBtwMax) {
  78826. newYaw = boneYaw + Math.PI * .75;
  78827. localTarget.z = Math.cos(newYaw) * xzlen;
  78828. localTarget.x = Math.sin(newYaw) * xzlen;
  78829. }
  78830. else {
  78831. newYaw = boneYaw - Math.PI * .75;
  78832. localTarget.z = Math.cos(newYaw) * xzlen;
  78833. localTarget.x = Math.sin(newYaw) * xzlen;
  78834. }
  78835. }
  78836. }
  78837. if (yaw != newYaw) {
  78838. BABYLON.Vector3.TransformCoordinatesToRef(localTarget, spaceMat, localTarget);
  78839. localTarget.addInPlace(bonePos);
  78840. target = localTarget;
  78841. }
  78842. }
  78843. }
  78844. var zaxis = BoneLookController._tmpVecs[5];
  78845. var xaxis = BoneLookController._tmpVecs[6];
  78846. var yaxis = BoneLookController._tmpVecs[7];
  78847. var _tmpQuat = BoneLookController._tmpQuat;
  78848. target.subtractToRef(bonePos, zaxis);
  78849. zaxis.normalize();
  78850. BABYLON.Vector3.CrossToRef(upAxis, zaxis, xaxis);
  78851. xaxis.normalize();
  78852. BABYLON.Vector3.CrossToRef(zaxis, xaxis, yaxis);
  78853. yaxis.normalize();
  78854. BABYLON.Matrix.FromXYZAxesToRef(xaxis, yaxis, zaxis, _tmpMat1);
  78855. if (xaxis.x === 0 && xaxis.y === 0 && xaxis.z === 0) {
  78856. return;
  78857. }
  78858. if (yaxis.x === 0 && yaxis.y === 0 && yaxis.z === 0) {
  78859. return;
  78860. }
  78861. if (zaxis.x === 0 && zaxis.y === 0 && zaxis.z === 0) {
  78862. return;
  78863. }
  78864. if (this.adjustYaw || this.adjustPitch || this.adjustRoll) {
  78865. BABYLON.Matrix.RotationYawPitchRollToRef(this.adjustYaw, this.adjustPitch, this.adjustRoll, _tmpMat2);
  78866. _tmpMat2.multiplyToRef(_tmpMat1, _tmpMat1);
  78867. }
  78868. if (this.slerpAmount < 1) {
  78869. if (!this._slerping) {
  78870. this.bone.getRotationQuaternionToRef(BABYLON.Space.WORLD, this.mesh, this._boneQuat);
  78871. }
  78872. if (this._transformYawPitch) {
  78873. this._transformYawPitch.multiplyToRef(_tmpMat1, _tmpMat1);
  78874. }
  78875. BABYLON.Quaternion.FromRotationMatrixToRef(_tmpMat1, _tmpQuat);
  78876. BABYLON.Quaternion.SlerpToRef(this._boneQuat, _tmpQuat, this.slerpAmount, this._boneQuat);
  78877. this.bone.setRotationQuaternion(this._boneQuat, BABYLON.Space.WORLD, this.mesh);
  78878. this._slerping = true;
  78879. }
  78880. else {
  78881. if (this._transformYawPitch) {
  78882. this._transformYawPitch.multiplyToRef(_tmpMat1, _tmpMat1);
  78883. }
  78884. this.bone.setRotationMatrix(_tmpMat1, BABYLON.Space.WORLD, this.mesh);
  78885. this._slerping = false;
  78886. }
  78887. };
  78888. BoneLookController.prototype._getAngleDiff = function (ang1, ang2) {
  78889. var angDiff = ang2 - ang1;
  78890. angDiff %= Math.PI * 2;
  78891. if (angDiff > Math.PI) {
  78892. angDiff -= Math.PI * 2;
  78893. }
  78894. else if (angDiff < -Math.PI) {
  78895. angDiff += Math.PI * 2;
  78896. }
  78897. return angDiff;
  78898. };
  78899. BoneLookController.prototype._getAngleBetween = function (ang1, ang2) {
  78900. ang1 %= (2 * Math.PI);
  78901. ang1 = (ang1 < 0) ? ang1 + (2 * Math.PI) : ang1;
  78902. ang2 %= (2 * Math.PI);
  78903. ang2 = (ang2 < 0) ? ang2 + (2 * Math.PI) : ang2;
  78904. var ab = 0;
  78905. if (ang1 < ang2) {
  78906. ab = ang2 - ang1;
  78907. }
  78908. else {
  78909. ab = ang1 - ang2;
  78910. }
  78911. if (ab > Math.PI) {
  78912. ab = Math.PI * 2 - ab;
  78913. }
  78914. return ab;
  78915. };
  78916. BoneLookController.prototype._isAngleBetween = function (ang, ang1, ang2) {
  78917. ang %= (2 * Math.PI);
  78918. ang = (ang < 0) ? ang + (2 * Math.PI) : ang;
  78919. ang1 %= (2 * Math.PI);
  78920. ang1 = (ang1 < 0) ? ang1 + (2 * Math.PI) : ang1;
  78921. ang2 %= (2 * Math.PI);
  78922. ang2 = (ang2 < 0) ? ang2 + (2 * Math.PI) : ang2;
  78923. if (ang1 < ang2) {
  78924. if (ang > ang1 && ang < ang2) {
  78925. return true;
  78926. }
  78927. }
  78928. else {
  78929. if (ang > ang2 && ang < ang1) {
  78930. return true;
  78931. }
  78932. }
  78933. return false;
  78934. };
  78935. 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()];
  78936. BoneLookController._tmpQuat = BABYLON.Quaternion.Identity();
  78937. BoneLookController._tmpMats = [BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity()];
  78938. return BoneLookController;
  78939. }());
  78940. BABYLON.BoneLookController = BoneLookController;
  78941. })(BABYLON || (BABYLON = {}));
  78942. //# sourceMappingURL=babylon.boneLookController.js.map
  78943. var BABYLON;
  78944. (function (BABYLON) {
  78945. /**
  78946. * Class used to handle skinning animations
  78947. * @see http://doc.babylonjs.com/how_to/how_to_use_bones_and_skeletons
  78948. */
  78949. var Skeleton = /** @class */ (function () {
  78950. /**
  78951. * Creates a new skeleton
  78952. * @param name defines the skeleton name
  78953. * @param id defines the skeleton Id
  78954. * @param scene defines the hosting scene
  78955. */
  78956. function Skeleton(
  78957. /** defines the skeleton name */
  78958. name,
  78959. /** defines the skeleton Id */
  78960. id, scene) {
  78961. this.name = name;
  78962. this.id = id;
  78963. /**
  78964. * Gets the list of child bones
  78965. */
  78966. this.bones = new Array();
  78967. /**
  78968. * Gets a boolean indicating if the root matrix is provided by meshes or by the current skeleton (this is the default value)
  78969. */
  78970. this.needInitialSkinMatrix = false;
  78971. this._isDirty = true;
  78972. this._meshesWithPoseMatrix = new Array();
  78973. this._identity = BABYLON.Matrix.Identity();
  78974. this._ranges = {};
  78975. this._lastAbsoluteTransformsUpdateId = -1;
  78976. /**
  78977. * Specifies if the skeleton should be serialized
  78978. */
  78979. this.doNotSerialize = false;
  78980. this._animationPropertiesOverride = null;
  78981. // Events
  78982. /**
  78983. * An observable triggered before computing the skeleton's matrices
  78984. */
  78985. this.onBeforeComputeObservable = new BABYLON.Observable();
  78986. this.bones = [];
  78987. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  78988. scene.skeletons.push(this);
  78989. //make sure it will recalculate the matrix next time prepare is called.
  78990. this._isDirty = true;
  78991. }
  78992. Object.defineProperty(Skeleton.prototype, "animationPropertiesOverride", {
  78993. /**
  78994. * Gets or sets the animation properties override
  78995. */
  78996. get: function () {
  78997. if (!this._animationPropertiesOverride) {
  78998. return this._scene.animationPropertiesOverride;
  78999. }
  79000. return this._animationPropertiesOverride;
  79001. },
  79002. set: function (value) {
  79003. this._animationPropertiesOverride = value;
  79004. },
  79005. enumerable: true,
  79006. configurable: true
  79007. });
  79008. // Members
  79009. /**
  79010. * Gets the list of transform matrices to send to shaders (one matrix per bone)
  79011. * @param mesh defines the mesh to use to get the root matrix (if needInitialSkinMatrix === true)
  79012. * @returns a Float32Array containing matrices data
  79013. */
  79014. Skeleton.prototype.getTransformMatrices = function (mesh) {
  79015. if (this.needInitialSkinMatrix && mesh._bonesTransformMatrices) {
  79016. return mesh._bonesTransformMatrices;
  79017. }
  79018. if (!this._transformMatrices) {
  79019. this.prepare();
  79020. }
  79021. return this._transformMatrices;
  79022. };
  79023. /**
  79024. * Gets the current hosting scene
  79025. * @returns a scene object
  79026. */
  79027. Skeleton.prototype.getScene = function () {
  79028. return this._scene;
  79029. };
  79030. // Methods
  79031. /**
  79032. * Gets a string representing the current skeleton data
  79033. * @param fullDetails defines a boolean indicating if we want a verbose version
  79034. * @returns a string representing the current skeleton data
  79035. */
  79036. Skeleton.prototype.toString = function (fullDetails) {
  79037. var ret = "Name: " + this.name + ", nBones: " + this.bones.length;
  79038. ret += ", nAnimationRanges: " + (this._ranges ? Object.keys(this._ranges).length : "none");
  79039. if (fullDetails) {
  79040. ret += ", Ranges: {";
  79041. var first = true;
  79042. for (var name_1 in this._ranges) {
  79043. if (first) {
  79044. ret += ", ";
  79045. first = false;
  79046. }
  79047. ret += name_1;
  79048. }
  79049. ret += "}";
  79050. }
  79051. return ret;
  79052. };
  79053. /**
  79054. * Get bone's index searching by name
  79055. * @param name defines bone's name to search for
  79056. * @return the indice of the bone. Returns -1 if not found
  79057. */
  79058. Skeleton.prototype.getBoneIndexByName = function (name) {
  79059. for (var boneIndex = 0, cache = this.bones.length; boneIndex < cache; boneIndex++) {
  79060. if (this.bones[boneIndex].name === name) {
  79061. return boneIndex;
  79062. }
  79063. }
  79064. return -1;
  79065. };
  79066. /**
  79067. * Creater a new animation range
  79068. * @param name defines the name of the range
  79069. * @param from defines the start key
  79070. * @param to defines the end key
  79071. */
  79072. Skeleton.prototype.createAnimationRange = function (name, from, to) {
  79073. // check name not already in use
  79074. if (!this._ranges[name]) {
  79075. this._ranges[name] = new BABYLON.AnimationRange(name, from, to);
  79076. for (var i = 0, nBones = this.bones.length; i < nBones; i++) {
  79077. if (this.bones[i].animations[0]) {
  79078. this.bones[i].animations[0].createRange(name, from, to);
  79079. }
  79080. }
  79081. }
  79082. };
  79083. /**
  79084. * Delete a specific animation range
  79085. * @param name defines the name of the range
  79086. * @param deleteFrames defines if frames must be removed as well
  79087. */
  79088. Skeleton.prototype.deleteAnimationRange = function (name, deleteFrames) {
  79089. if (deleteFrames === void 0) { deleteFrames = true; }
  79090. for (var i = 0, nBones = this.bones.length; i < nBones; i++) {
  79091. if (this.bones[i].animations[0]) {
  79092. this.bones[i].animations[0].deleteRange(name, deleteFrames);
  79093. }
  79094. }
  79095. this._ranges[name] = null; // said much faster than 'delete this._range[name]'
  79096. };
  79097. /**
  79098. * Gets a specific animation range
  79099. * @param name defines the name of the range to look for
  79100. * @returns the requested animation range or null if not found
  79101. */
  79102. Skeleton.prototype.getAnimationRange = function (name) {
  79103. return this._ranges[name];
  79104. };
  79105. /**
  79106. * Gets the list of all animation ranges defined on this skeleton
  79107. * @returns an array
  79108. */
  79109. Skeleton.prototype.getAnimationRanges = function () {
  79110. var animationRanges = [];
  79111. var name;
  79112. var i = 0;
  79113. for (name in this._ranges) {
  79114. animationRanges[i] = this._ranges[name];
  79115. i++;
  79116. }
  79117. return animationRanges;
  79118. };
  79119. /**
  79120. * Copy animation range from a source skeleton.
  79121. * This is not for a complete retargeting, only between very similar skeleton's with only possible bone length differences
  79122. * @param source defines the source skeleton
  79123. * @param name defines the name of the range to copy
  79124. * @param rescaleAsRequired defines if rescaling must be applied if required
  79125. * @returns true if operation was successful
  79126. */
  79127. Skeleton.prototype.copyAnimationRange = function (source, name, rescaleAsRequired) {
  79128. if (rescaleAsRequired === void 0) { rescaleAsRequired = false; }
  79129. if (this._ranges[name] || !source.getAnimationRange(name)) {
  79130. return false;
  79131. }
  79132. var ret = true;
  79133. var frameOffset = this._getHighestAnimationFrame() + 1;
  79134. // make a dictionary of source skeleton's bones, so exact same order or doublely nested loop is not required
  79135. var boneDict = {};
  79136. var sourceBones = source.bones;
  79137. var nBones;
  79138. var i;
  79139. for (i = 0, nBones = sourceBones.length; i < nBones; i++) {
  79140. boneDict[sourceBones[i].name] = sourceBones[i];
  79141. }
  79142. if (this.bones.length !== sourceBones.length) {
  79143. BABYLON.Tools.Warn("copyAnimationRange: this rig has " + this.bones.length + " bones, while source as " + sourceBones.length);
  79144. ret = false;
  79145. }
  79146. var skelDimensionsRatio = (rescaleAsRequired && this.dimensionsAtRest && source.dimensionsAtRest) ? this.dimensionsAtRest.divide(source.dimensionsAtRest) : null;
  79147. for (i = 0, nBones = this.bones.length; i < nBones; i++) {
  79148. var boneName = this.bones[i].name;
  79149. var sourceBone = boneDict[boneName];
  79150. if (sourceBone) {
  79151. ret = ret && this.bones[i].copyAnimationRange(sourceBone, name, frameOffset, rescaleAsRequired, skelDimensionsRatio);
  79152. }
  79153. else {
  79154. BABYLON.Tools.Warn("copyAnimationRange: not same rig, missing source bone " + boneName);
  79155. ret = false;
  79156. }
  79157. }
  79158. // do not call createAnimationRange(), since it also is done to bones, which was already done
  79159. var range = source.getAnimationRange(name);
  79160. if (range) {
  79161. this._ranges[name] = new BABYLON.AnimationRange(name, range.from + frameOffset, range.to + frameOffset);
  79162. }
  79163. return ret;
  79164. };
  79165. /**
  79166. * Forces the skeleton to go to rest pose
  79167. */
  79168. Skeleton.prototype.returnToRest = function () {
  79169. for (var index = 0; index < this.bones.length; index++) {
  79170. this.bones[index].returnToRest();
  79171. }
  79172. };
  79173. Skeleton.prototype._getHighestAnimationFrame = function () {
  79174. var ret = 0;
  79175. for (var i = 0, nBones = this.bones.length; i < nBones; i++) {
  79176. if (this.bones[i].animations[0]) {
  79177. var highest = this.bones[i].animations[0].getHighestFrame();
  79178. if (ret < highest) {
  79179. ret = highest;
  79180. }
  79181. }
  79182. }
  79183. return ret;
  79184. };
  79185. /**
  79186. * Begin a specific animation range
  79187. * @param name defines the name of the range to start
  79188. * @param loop defines if looping must be turned on (false by default)
  79189. * @param speedRatio defines the speed ratio to apply (1 by default)
  79190. * @param onAnimationEnd defines a callback which will be called when animation will end
  79191. * @returns a new animatable
  79192. */
  79193. Skeleton.prototype.beginAnimation = function (name, loop, speedRatio, onAnimationEnd) {
  79194. var range = this.getAnimationRange(name);
  79195. if (!range) {
  79196. return null;
  79197. }
  79198. return this._scene.beginAnimation(this, range.from, range.to, loop, speedRatio, onAnimationEnd);
  79199. };
  79200. /** @hidden */
  79201. Skeleton.prototype._markAsDirty = function () {
  79202. this._isDirty = true;
  79203. };
  79204. /** @hidden */
  79205. Skeleton.prototype._registerMeshWithPoseMatrix = function (mesh) {
  79206. this._meshesWithPoseMatrix.push(mesh);
  79207. };
  79208. /** @hidden */
  79209. Skeleton.prototype._unregisterMeshWithPoseMatrix = function (mesh) {
  79210. var index = this._meshesWithPoseMatrix.indexOf(mesh);
  79211. if (index > -1) {
  79212. this._meshesWithPoseMatrix.splice(index, 1);
  79213. }
  79214. };
  79215. /** @hidden */
  79216. Skeleton.prototype._computeTransformMatrices = function (targetMatrix, initialSkinMatrix) {
  79217. this.onBeforeComputeObservable.notifyObservers(this);
  79218. for (var index = 0; index < this.bones.length; index++) {
  79219. var bone = this.bones[index];
  79220. var parentBone = bone.getParent();
  79221. if (parentBone) {
  79222. bone.getLocalMatrix().multiplyToRef(parentBone.getWorldMatrix(), bone.getWorldMatrix());
  79223. }
  79224. else {
  79225. if (initialSkinMatrix) {
  79226. bone.getLocalMatrix().multiplyToRef(initialSkinMatrix, bone.getWorldMatrix());
  79227. }
  79228. else {
  79229. bone.getWorldMatrix().copyFrom(bone.getLocalMatrix());
  79230. }
  79231. }
  79232. if (bone._index !== -1) {
  79233. var mappedIndex = bone._index === null ? index : bone._index;
  79234. bone.getInvertedAbsoluteTransform().multiplyToArray(bone.getWorldMatrix(), targetMatrix, mappedIndex * 16);
  79235. }
  79236. }
  79237. this._identity.copyToArray(targetMatrix, this.bones.length * 16);
  79238. };
  79239. /**
  79240. * Build all resources required to render a skeleton
  79241. */
  79242. Skeleton.prototype.prepare = function () {
  79243. if (!this._isDirty) {
  79244. return;
  79245. }
  79246. if (this.needInitialSkinMatrix) {
  79247. for (var index = 0; index < this._meshesWithPoseMatrix.length; index++) {
  79248. var mesh = this._meshesWithPoseMatrix[index];
  79249. var poseMatrix = mesh.getPoseMatrix();
  79250. if (!mesh._bonesTransformMatrices || mesh._bonesTransformMatrices.length !== 16 * (this.bones.length + 1)) {
  79251. mesh._bonesTransformMatrices = new Float32Array(16 * (this.bones.length + 1));
  79252. }
  79253. if (this._synchronizedWithMesh !== mesh) {
  79254. this._synchronizedWithMesh = mesh;
  79255. // Prepare bones
  79256. for (var boneIndex = 0; boneIndex < this.bones.length; boneIndex++) {
  79257. var bone = this.bones[boneIndex];
  79258. if (!bone.getParent()) {
  79259. var matrix = bone.getBaseMatrix();
  79260. matrix.multiplyToRef(poseMatrix, BABYLON.Tmp.Matrix[1]);
  79261. bone._updateDifferenceMatrix(BABYLON.Tmp.Matrix[1]);
  79262. }
  79263. }
  79264. }
  79265. this._computeTransformMatrices(mesh._bonesTransformMatrices, poseMatrix);
  79266. }
  79267. }
  79268. else {
  79269. if (!this._transformMatrices || this._transformMatrices.length !== 16 * (this.bones.length + 1)) {
  79270. this._transformMatrices = new Float32Array(16 * (this.bones.length + 1));
  79271. }
  79272. this._computeTransformMatrices(this._transformMatrices, null);
  79273. }
  79274. this._isDirty = false;
  79275. this._scene._activeBones.addCount(this.bones.length, false);
  79276. };
  79277. /**
  79278. * Gets the list of animatables currently running for this skeleton
  79279. * @returns an array of animatables
  79280. */
  79281. Skeleton.prototype.getAnimatables = function () {
  79282. if (!this._animatables || this._animatables.length !== this.bones.length) {
  79283. this._animatables = [];
  79284. for (var index = 0; index < this.bones.length; index++) {
  79285. this._animatables.push(this.bones[index]);
  79286. }
  79287. }
  79288. return this._animatables;
  79289. };
  79290. /**
  79291. * Clone the current skeleton
  79292. * @param name defines the name of the new skeleton
  79293. * @param id defines the id of the enw skeleton
  79294. * @returns the new skeleton
  79295. */
  79296. Skeleton.prototype.clone = function (name, id) {
  79297. var result = new Skeleton(name, id || name, this._scene);
  79298. result.needInitialSkinMatrix = this.needInitialSkinMatrix;
  79299. for (var index = 0; index < this.bones.length; index++) {
  79300. var source = this.bones[index];
  79301. var parentBone = null;
  79302. var parent_1 = source.getParent();
  79303. if (parent_1) {
  79304. var parentIndex = this.bones.indexOf(parent_1);
  79305. parentBone = result.bones[parentIndex];
  79306. }
  79307. var bone = new BABYLON.Bone(source.name, result, parentBone, source.getBaseMatrix().clone(), source.getRestPose().clone());
  79308. BABYLON.Tools.DeepCopy(source.animations, bone.animations);
  79309. }
  79310. if (this._ranges) {
  79311. result._ranges = {};
  79312. for (var rangeName in this._ranges) {
  79313. var range = this._ranges[rangeName];
  79314. if (range) {
  79315. result._ranges[rangeName] = range.clone();
  79316. }
  79317. }
  79318. }
  79319. this._isDirty = true;
  79320. return result;
  79321. };
  79322. /**
  79323. * Enable animation blending for this skeleton
  79324. * @param blendingSpeed defines the blending speed to apply
  79325. * @see http://doc.babylonjs.com/babylon101/animations#animation-blending
  79326. */
  79327. Skeleton.prototype.enableBlending = function (blendingSpeed) {
  79328. if (blendingSpeed === void 0) { blendingSpeed = 0.01; }
  79329. this.bones.forEach(function (bone) {
  79330. bone.animations.forEach(function (animation) {
  79331. animation.enableBlending = true;
  79332. animation.blendingSpeed = blendingSpeed;
  79333. });
  79334. });
  79335. };
  79336. /**
  79337. * Releases all resources associated with the current skeleton
  79338. */
  79339. Skeleton.prototype.dispose = function () {
  79340. this._meshesWithPoseMatrix = [];
  79341. // Animations
  79342. this.getScene().stopAnimation(this);
  79343. // Remove from scene
  79344. this.getScene().removeSkeleton(this);
  79345. };
  79346. /**
  79347. * Serialize the skeleton in a JSON object
  79348. * @returns a JSON object
  79349. */
  79350. Skeleton.prototype.serialize = function () {
  79351. var serializationObject = {};
  79352. serializationObject.name = this.name;
  79353. serializationObject.id = this.id;
  79354. if (this.dimensionsAtRest) {
  79355. serializationObject.dimensionsAtRest = this.dimensionsAtRest.asArray();
  79356. }
  79357. serializationObject.bones = [];
  79358. serializationObject.needInitialSkinMatrix = this.needInitialSkinMatrix;
  79359. for (var index = 0; index < this.bones.length; index++) {
  79360. var bone = this.bones[index];
  79361. var parent_2 = bone.getParent();
  79362. var serializedBone = {
  79363. parentBoneIndex: parent_2 ? this.bones.indexOf(parent_2) : -1,
  79364. name: bone.name,
  79365. matrix: bone.getBaseMatrix().toArray(),
  79366. rest: bone.getRestPose().toArray()
  79367. };
  79368. serializationObject.bones.push(serializedBone);
  79369. if (bone.length) {
  79370. serializedBone.length = bone.length;
  79371. }
  79372. if (bone.animations && bone.animations.length > 0) {
  79373. serializedBone.animation = bone.animations[0].serialize();
  79374. }
  79375. serializationObject.ranges = [];
  79376. for (var name in this._ranges) {
  79377. var source = this._ranges[name];
  79378. if (!source) {
  79379. continue;
  79380. }
  79381. var range = {};
  79382. range.name = name;
  79383. range.from = source.from;
  79384. range.to = source.to;
  79385. serializationObject.ranges.push(range);
  79386. }
  79387. }
  79388. return serializationObject;
  79389. };
  79390. /**
  79391. * Creates a new skeleton from serialized data
  79392. * @param parsedSkeleton defines the serialized data
  79393. * @param scene defines the hosting scene
  79394. * @returns a new skeleton
  79395. */
  79396. Skeleton.Parse = function (parsedSkeleton, scene) {
  79397. var skeleton = new Skeleton(parsedSkeleton.name, parsedSkeleton.id, scene);
  79398. if (parsedSkeleton.dimensionsAtRest) {
  79399. skeleton.dimensionsAtRest = BABYLON.Vector3.FromArray(parsedSkeleton.dimensionsAtRest);
  79400. }
  79401. skeleton.needInitialSkinMatrix = parsedSkeleton.needInitialSkinMatrix;
  79402. var index;
  79403. for (index = 0; index < parsedSkeleton.bones.length; index++) {
  79404. var parsedBone = parsedSkeleton.bones[index];
  79405. var parentBone = null;
  79406. if (parsedBone.parentBoneIndex > -1) {
  79407. parentBone = skeleton.bones[parsedBone.parentBoneIndex];
  79408. }
  79409. var rest = parsedBone.rest ? BABYLON.Matrix.FromArray(parsedBone.rest) : null;
  79410. var bone = new BABYLON.Bone(parsedBone.name, skeleton, parentBone, BABYLON.Matrix.FromArray(parsedBone.matrix), rest);
  79411. if (parsedBone.length) {
  79412. bone.length = parsedBone.length;
  79413. }
  79414. if (parsedBone.animation) {
  79415. bone.animations.push(BABYLON.Animation.Parse(parsedBone.animation));
  79416. }
  79417. }
  79418. // placed after bones, so createAnimationRange can cascade down
  79419. if (parsedSkeleton.ranges) {
  79420. for (index = 0; index < parsedSkeleton.ranges.length; index++) {
  79421. var data = parsedSkeleton.ranges[index];
  79422. skeleton.createAnimationRange(data.name, data.from, data.to);
  79423. }
  79424. }
  79425. return skeleton;
  79426. };
  79427. /**
  79428. * Compute all node absolute transforms
  79429. * @param forceUpdate defines if computation must be done even if cache is up to date
  79430. */
  79431. Skeleton.prototype.computeAbsoluteTransforms = function (forceUpdate) {
  79432. if (forceUpdate === void 0) { forceUpdate = false; }
  79433. var renderId = this._scene.getRenderId();
  79434. if (this._lastAbsoluteTransformsUpdateId != renderId || forceUpdate) {
  79435. this.bones[0].computeAbsoluteTransforms();
  79436. this._lastAbsoluteTransformsUpdateId = renderId;
  79437. }
  79438. };
  79439. /**
  79440. * Gets the root pose matrix
  79441. * @returns a matrix
  79442. */
  79443. Skeleton.prototype.getPoseMatrix = function () {
  79444. var poseMatrix = null;
  79445. if (this._meshesWithPoseMatrix.length > 0) {
  79446. poseMatrix = this._meshesWithPoseMatrix[0].getPoseMatrix();
  79447. }
  79448. return poseMatrix;
  79449. };
  79450. /**
  79451. * Sorts bones per internal index
  79452. */
  79453. Skeleton.prototype.sortBones = function () {
  79454. var bones = new Array();
  79455. var visited = new Array(this.bones.length);
  79456. for (var index = 0; index < this.bones.length; index++) {
  79457. this._sortBones(index, bones, visited);
  79458. }
  79459. this.bones = bones;
  79460. };
  79461. Skeleton.prototype._sortBones = function (index, bones, visited) {
  79462. if (visited[index]) {
  79463. return;
  79464. }
  79465. visited[index] = true;
  79466. var bone = this.bones[index];
  79467. if (bone._index === undefined) {
  79468. bone._index = index;
  79469. }
  79470. var parentBone = bone.getParent();
  79471. if (parentBone) {
  79472. this._sortBones(this.bones.indexOf(parentBone), bones, visited);
  79473. }
  79474. bones.push(bone);
  79475. };
  79476. return Skeleton;
  79477. }());
  79478. BABYLON.Skeleton = Skeleton;
  79479. })(BABYLON || (BABYLON = {}));
  79480. //# sourceMappingURL=babylon.skeleton.js.map
  79481. var BABYLON;
  79482. (function (BABYLON) {
  79483. var SphericalPolynomial = /** @class */ (function () {
  79484. function SphericalPolynomial() {
  79485. this.x = BABYLON.Vector3.Zero();
  79486. this.y = BABYLON.Vector3.Zero();
  79487. this.z = BABYLON.Vector3.Zero();
  79488. this.xx = BABYLON.Vector3.Zero();
  79489. this.yy = BABYLON.Vector3.Zero();
  79490. this.zz = BABYLON.Vector3.Zero();
  79491. this.xy = BABYLON.Vector3.Zero();
  79492. this.yz = BABYLON.Vector3.Zero();
  79493. this.zx = BABYLON.Vector3.Zero();
  79494. }
  79495. SphericalPolynomial.prototype.addAmbient = function (color) {
  79496. var colorVector = new BABYLON.Vector3(color.r, color.g, color.b);
  79497. this.xx = this.xx.add(colorVector);
  79498. this.yy = this.yy.add(colorVector);
  79499. this.zz = this.zz.add(colorVector);
  79500. };
  79501. SphericalPolynomial.getSphericalPolynomialFromHarmonics = function (harmonics) {
  79502. var result = new SphericalPolynomial();
  79503. result.x = harmonics.L11.scale(1.02333);
  79504. result.y = harmonics.L1_1.scale(1.02333);
  79505. result.z = harmonics.L10.scale(1.02333);
  79506. result.xx = harmonics.L00.scale(0.886277).subtract(harmonics.L20.scale(0.247708)).add(harmonics.L22.scale(0.429043));
  79507. result.yy = harmonics.L00.scale(0.886277).subtract(harmonics.L20.scale(0.247708)).subtract(harmonics.L22.scale(0.429043));
  79508. result.zz = harmonics.L00.scale(0.886277).add(harmonics.L20.scale(0.495417));
  79509. result.yz = harmonics.L2_1.scale(0.858086);
  79510. result.zx = harmonics.L21.scale(0.858086);
  79511. result.xy = harmonics.L2_2.scale(0.858086);
  79512. result.scale(1.0 / Math.PI);
  79513. return result;
  79514. };
  79515. SphericalPolynomial.prototype.scale = function (scale) {
  79516. this.x = this.x.scale(scale);
  79517. this.y = this.y.scale(scale);
  79518. this.z = this.z.scale(scale);
  79519. this.xx = this.xx.scale(scale);
  79520. this.yy = this.yy.scale(scale);
  79521. this.zz = this.zz.scale(scale);
  79522. this.yz = this.yz.scale(scale);
  79523. this.zx = this.zx.scale(scale);
  79524. this.xy = this.xy.scale(scale);
  79525. };
  79526. return SphericalPolynomial;
  79527. }());
  79528. BABYLON.SphericalPolynomial = SphericalPolynomial;
  79529. var SphericalHarmonics = /** @class */ (function () {
  79530. function SphericalHarmonics() {
  79531. this.L00 = BABYLON.Vector3.Zero();
  79532. this.L1_1 = BABYLON.Vector3.Zero();
  79533. this.L10 = BABYLON.Vector3.Zero();
  79534. this.L11 = BABYLON.Vector3.Zero();
  79535. this.L2_2 = BABYLON.Vector3.Zero();
  79536. this.L2_1 = BABYLON.Vector3.Zero();
  79537. this.L20 = BABYLON.Vector3.Zero();
  79538. this.L21 = BABYLON.Vector3.Zero();
  79539. this.L22 = BABYLON.Vector3.Zero();
  79540. }
  79541. SphericalHarmonics.prototype.addLight = function (direction, color, deltaSolidAngle) {
  79542. var colorVector = new BABYLON.Vector3(color.r, color.g, color.b);
  79543. var c = colorVector.scale(deltaSolidAngle);
  79544. this.L00 = this.L00.add(c.scale(0.282095));
  79545. this.L1_1 = this.L1_1.add(c.scale(0.488603 * direction.y));
  79546. this.L10 = this.L10.add(c.scale(0.488603 * direction.z));
  79547. this.L11 = this.L11.add(c.scale(0.488603 * direction.x));
  79548. this.L2_2 = this.L2_2.add(c.scale(1.092548 * direction.x * direction.y));
  79549. this.L2_1 = this.L2_1.add(c.scale(1.092548 * direction.y * direction.z));
  79550. this.L21 = this.L21.add(c.scale(1.092548 * direction.x * direction.z));
  79551. this.L20 = this.L20.add(c.scale(0.315392 * (3.0 * direction.z * direction.z - 1.0)));
  79552. this.L22 = this.L22.add(c.scale(0.546274 * (direction.x * direction.x - direction.y * direction.y)));
  79553. };
  79554. SphericalHarmonics.prototype.scale = function (scale) {
  79555. this.L00 = this.L00.scale(scale);
  79556. this.L1_1 = this.L1_1.scale(scale);
  79557. this.L10 = this.L10.scale(scale);
  79558. this.L11 = this.L11.scale(scale);
  79559. this.L2_2 = this.L2_2.scale(scale);
  79560. this.L2_1 = this.L2_1.scale(scale);
  79561. this.L20 = this.L20.scale(scale);
  79562. this.L21 = this.L21.scale(scale);
  79563. this.L22 = this.L22.scale(scale);
  79564. };
  79565. SphericalHarmonics.prototype.convertIncidentRadianceToIrradiance = function () {
  79566. // Convert from incident radiance (Li) to irradiance (E) by applying convolution with the cosine-weighted hemisphere.
  79567. //
  79568. // E_lm = A_l * L_lm
  79569. //
  79570. // In spherical harmonics this convolution amounts to scaling factors for each frequency band.
  79571. // This corresponds to equation 5 in "An Efficient Representation for Irradiance Environment Maps", where
  79572. // the scaling factors are given in equation 9.
  79573. // Constant (Band 0)
  79574. this.L00 = this.L00.scale(3.141593);
  79575. // Linear (Band 1)
  79576. this.L1_1 = this.L1_1.scale(2.094395);
  79577. this.L10 = this.L10.scale(2.094395);
  79578. this.L11 = this.L11.scale(2.094395);
  79579. // Quadratic (Band 2)
  79580. this.L2_2 = this.L2_2.scale(0.785398);
  79581. this.L2_1 = this.L2_1.scale(0.785398);
  79582. this.L20 = this.L20.scale(0.785398);
  79583. this.L21 = this.L21.scale(0.785398);
  79584. this.L22 = this.L22.scale(0.785398);
  79585. };
  79586. SphericalHarmonics.prototype.convertIrradianceToLambertianRadiance = function () {
  79587. // Convert from irradiance to outgoing radiance for Lambertian BDRF, suitable for efficient shader evaluation.
  79588. // L = (1/pi) * E * rho
  79589. //
  79590. // This is done by an additional scale by 1/pi, so is a fairly trivial operation but important conceptually.
  79591. this.scale(1.0 / Math.PI);
  79592. // The resultant SH now represents outgoing radiance, so includes the Lambert 1/pi normalisation factor but without albedo (rho) applied
  79593. // (The pixel shader must apply albedo after texture fetches, etc).
  79594. };
  79595. SphericalHarmonics.getsphericalHarmonicsFromPolynomial = function (polynomial) {
  79596. var result = new SphericalHarmonics();
  79597. result.L00 = polynomial.xx.scale(0.376127).add(polynomial.yy.scale(0.376127)).add(polynomial.zz.scale(0.376126));
  79598. result.L1_1 = polynomial.y.scale(0.977204);
  79599. result.L10 = polynomial.z.scale(0.977204);
  79600. result.L11 = polynomial.x.scale(0.977204);
  79601. result.L2_2 = polynomial.xy.scale(1.16538);
  79602. result.L2_1 = polynomial.yz.scale(1.16538);
  79603. result.L20 = polynomial.zz.scale(1.34567).subtract(polynomial.xx.scale(0.672834)).subtract(polynomial.yy.scale(0.672834));
  79604. result.L21 = polynomial.zx.scale(1.16538);
  79605. result.L22 = polynomial.xx.scale(1.16538).subtract(polynomial.yy.scale(1.16538));
  79606. result.scale(Math.PI);
  79607. return result;
  79608. };
  79609. return SphericalHarmonics;
  79610. }());
  79611. BABYLON.SphericalHarmonics = SphericalHarmonics;
  79612. })(BABYLON || (BABYLON = {}));
  79613. //# sourceMappingURL=babylon.sphericalPolynomial.js.map
  79614. var BABYLON;
  79615. (function (BABYLON) {
  79616. var FileFaceOrientation = /** @class */ (function () {
  79617. function FileFaceOrientation(name, worldAxisForNormal, worldAxisForFileX, worldAxisForFileY) {
  79618. this.name = name;
  79619. this.worldAxisForNormal = worldAxisForNormal;
  79620. this.worldAxisForFileX = worldAxisForFileX;
  79621. this.worldAxisForFileY = worldAxisForFileY;
  79622. }
  79623. return FileFaceOrientation;
  79624. }());
  79625. ;
  79626. /**
  79627. * Helper class dealing with the extraction of spherical polynomial dataArray
  79628. * from a cube map.
  79629. */
  79630. var CubeMapToSphericalPolynomialTools = /** @class */ (function () {
  79631. function CubeMapToSphericalPolynomialTools() {
  79632. }
  79633. /**
  79634. * Converts a texture to the according Spherical Polynomial data.
  79635. * This extracts the first 3 orders only as they are the only one used in the lighting.
  79636. *
  79637. * @param texture The texture to extract the information from.
  79638. * @return The Spherical Polynomial data.
  79639. */
  79640. CubeMapToSphericalPolynomialTools.ConvertCubeMapTextureToSphericalPolynomial = function (texture) {
  79641. if (!texture.isCube) {
  79642. // Only supports cube Textures currently.
  79643. return null;
  79644. }
  79645. var size = texture.getSize().width;
  79646. var right = texture.readPixels(0);
  79647. var left = texture.readPixels(1);
  79648. var up;
  79649. var down;
  79650. if (texture.isRenderTarget) {
  79651. up = texture.readPixels(3);
  79652. down = texture.readPixels(2);
  79653. }
  79654. else {
  79655. up = texture.readPixels(2);
  79656. down = texture.readPixels(3);
  79657. }
  79658. var front = texture.readPixels(4);
  79659. var back = texture.readPixels(5);
  79660. var gammaSpace = texture.gammaSpace;
  79661. // Always read as RGBA.
  79662. var format = BABYLON.Engine.TEXTUREFORMAT_RGBA;
  79663. var type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  79664. if (texture.textureType && texture.textureType !== BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT) {
  79665. type = BABYLON.Engine.TEXTURETYPE_FLOAT;
  79666. }
  79667. var cubeInfo = {
  79668. size: size,
  79669. right: right,
  79670. left: left,
  79671. up: up,
  79672. down: down,
  79673. front: front,
  79674. back: back,
  79675. format: format,
  79676. type: type,
  79677. gammaSpace: gammaSpace,
  79678. };
  79679. return this.ConvertCubeMapToSphericalPolynomial(cubeInfo);
  79680. };
  79681. /**
  79682. * Converts a cubemap to the according Spherical Polynomial data.
  79683. * This extracts the first 3 orders only as they are the only one used in the lighting.
  79684. *
  79685. * @param cubeInfo The Cube map to extract the information from.
  79686. * @return The Spherical Polynomial data.
  79687. */
  79688. CubeMapToSphericalPolynomialTools.ConvertCubeMapToSphericalPolynomial = function (cubeInfo) {
  79689. var sphericalHarmonics = new BABYLON.SphericalHarmonics();
  79690. var totalSolidAngle = 0.0;
  79691. // The (u,v) range is [-1,+1], so the distance between each texel is 2/Size.
  79692. var du = 2.0 / cubeInfo.size;
  79693. var dv = du;
  79694. // The (u,v) of the first texel is half a texel from the corner (-1,-1).
  79695. var minUV = du * 0.5 - 1.0;
  79696. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  79697. var fileFace = this.FileFaces[faceIndex];
  79698. var dataArray = cubeInfo[fileFace.name];
  79699. var v = minUV;
  79700. // TODO: we could perform the summation directly into a SphericalPolynomial (SP), which is more efficient than SphericalHarmonic (SH).
  79701. // This is possible because during the summation we do not need the SH-specific properties, e.g. orthogonality.
  79702. // Because SP is still linear, so summation is fine in that basis.
  79703. var stride = cubeInfo.format === BABYLON.Engine.TEXTUREFORMAT_RGBA ? 4 : 3;
  79704. for (var y = 0; y < cubeInfo.size; y++) {
  79705. var u = minUV;
  79706. for (var x = 0; x < cubeInfo.size; x++) {
  79707. // World direction (not normalised)
  79708. var worldDirection = fileFace.worldAxisForFileX.scale(u).add(fileFace.worldAxisForFileY.scale(v)).add(fileFace.worldAxisForNormal);
  79709. worldDirection.normalize();
  79710. var deltaSolidAngle = Math.pow(1.0 + u * u + v * v, -3.0 / 2.0);
  79711. var r = dataArray[(y * cubeInfo.size * stride) + (x * stride) + 0];
  79712. var g = dataArray[(y * cubeInfo.size * stride) + (x * stride) + 1];
  79713. var b = dataArray[(y * cubeInfo.size * stride) + (x * stride) + 2];
  79714. // Handle Integer types.
  79715. if (cubeInfo.type === BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT) {
  79716. r /= 255;
  79717. g /= 255;
  79718. b /= 255;
  79719. }
  79720. // Handle Gamma space textures.
  79721. if (cubeInfo.gammaSpace) {
  79722. r = Math.pow(BABYLON.Scalar.Clamp(r), BABYLON.ToLinearSpace);
  79723. g = Math.pow(BABYLON.Scalar.Clamp(g), BABYLON.ToLinearSpace);
  79724. b = Math.pow(BABYLON.Scalar.Clamp(b), BABYLON.ToLinearSpace);
  79725. }
  79726. var color = new BABYLON.Color3(r, g, b);
  79727. sphericalHarmonics.addLight(worldDirection, color, deltaSolidAngle);
  79728. totalSolidAngle += deltaSolidAngle;
  79729. u += du;
  79730. }
  79731. v += dv;
  79732. }
  79733. }
  79734. // Solid angle for entire sphere is 4*pi
  79735. var sphereSolidAngle = 4.0 * Math.PI;
  79736. // Adjust the solid angle to allow for how many faces we processed.
  79737. var facesProcessed = 6.0;
  79738. var expectedSolidAngle = sphereSolidAngle * facesProcessed / 6.0;
  79739. // Adjust the harmonics so that the accumulated solid angle matches the expected solid angle.
  79740. // This is needed because the numerical integration over the cube uses a
  79741. // small angle approximation of solid angle for each texel (see deltaSolidAngle),
  79742. // and also to compensate for accumulative error due to float precision in the summation.
  79743. var correctionFactor = expectedSolidAngle / totalSolidAngle;
  79744. sphericalHarmonics.scale(correctionFactor);
  79745. sphericalHarmonics.convertIncidentRadianceToIrradiance();
  79746. sphericalHarmonics.convertIrradianceToLambertianRadiance();
  79747. return BABYLON.SphericalPolynomial.getSphericalPolynomialFromHarmonics(sphericalHarmonics);
  79748. };
  79749. CubeMapToSphericalPolynomialTools.FileFaces = [
  79750. new FileFaceOrientation("right", new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, 0, -1), new BABYLON.Vector3(0, -1, 0)),
  79751. new FileFaceOrientation("left", new BABYLON.Vector3(-1, 0, 0), new BABYLON.Vector3(0, 0, 1), new BABYLON.Vector3(0, -1, 0)),
  79752. new FileFaceOrientation("up", new BABYLON.Vector3(0, 1, 0), new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, 0, 1)),
  79753. new FileFaceOrientation("down", new BABYLON.Vector3(0, -1, 0), new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, 0, -1)),
  79754. new FileFaceOrientation("front", new BABYLON.Vector3(0, 0, 1), new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, -1, 0)),
  79755. new FileFaceOrientation("back", new BABYLON.Vector3(0, 0, -1), new BABYLON.Vector3(-1, 0, 0), new BABYLON.Vector3(0, -1, 0)) // -Z bottom
  79756. ];
  79757. return CubeMapToSphericalPolynomialTools;
  79758. }());
  79759. BABYLON.CubeMapToSphericalPolynomialTools = CubeMapToSphericalPolynomialTools;
  79760. })(BABYLON || (BABYLON = {}));
  79761. //# sourceMappingURL=babylon.cubemapToSphericalPolynomial.js.map
  79762. var BABYLON;
  79763. (function (BABYLON) {
  79764. /**
  79765. * Helper class usefull to convert panorama picture to their cubemap representation in 6 faces.
  79766. */
  79767. var PanoramaToCubeMapTools = /** @class */ (function () {
  79768. function PanoramaToCubeMapTools() {
  79769. }
  79770. /**
  79771. * Converts a panorma stored in RGB right to left up to down format into a cubemap (6 faces).
  79772. *
  79773. * @param float32Array The source data.
  79774. * @param inputWidth The width of the input panorama.
  79775. * @param inputhHeight The height of the input panorama.
  79776. * @param size The willing size of the generated cubemap (each faces will be size * size pixels)
  79777. * @return The cubemap data
  79778. */
  79779. PanoramaToCubeMapTools.ConvertPanoramaToCubemap = function (float32Array, inputWidth, inputHeight, size) {
  79780. if (!float32Array) {
  79781. throw "ConvertPanoramaToCubemap: input cannot be null";
  79782. }
  79783. if (float32Array.length != inputWidth * inputHeight * 3) {
  79784. throw "ConvertPanoramaToCubemap: input size is wrong";
  79785. }
  79786. var textureFront = this.CreateCubemapTexture(size, this.FACE_FRONT, float32Array, inputWidth, inputHeight);
  79787. var textureBack = this.CreateCubemapTexture(size, this.FACE_BACK, float32Array, inputWidth, inputHeight);
  79788. var textureLeft = this.CreateCubemapTexture(size, this.FACE_LEFT, float32Array, inputWidth, inputHeight);
  79789. var textureRight = this.CreateCubemapTexture(size, this.FACE_RIGHT, float32Array, inputWidth, inputHeight);
  79790. var textureUp = this.CreateCubemapTexture(size, this.FACE_UP, float32Array, inputWidth, inputHeight);
  79791. var textureDown = this.CreateCubemapTexture(size, this.FACE_DOWN, float32Array, inputWidth, inputHeight);
  79792. return {
  79793. front: textureFront,
  79794. back: textureBack,
  79795. left: textureLeft,
  79796. right: textureRight,
  79797. up: textureUp,
  79798. down: textureDown,
  79799. size: size,
  79800. type: BABYLON.Engine.TEXTURETYPE_FLOAT,
  79801. format: BABYLON.Engine.TEXTUREFORMAT_RGB,
  79802. gammaSpace: false,
  79803. };
  79804. };
  79805. PanoramaToCubeMapTools.CreateCubemapTexture = function (texSize, faceData, float32Array, inputWidth, inputHeight) {
  79806. var buffer = new ArrayBuffer(texSize * texSize * 4 * 3);
  79807. var textureArray = new Float32Array(buffer);
  79808. var rotDX1 = faceData[1].subtract(faceData[0]).scale(1 / texSize);
  79809. var rotDX2 = faceData[3].subtract(faceData[2]).scale(1 / texSize);
  79810. var dy = 1 / texSize;
  79811. var fy = 0;
  79812. for (var y = 0; y < texSize; y++) {
  79813. var xv1 = faceData[0];
  79814. var xv2 = faceData[2];
  79815. for (var x = 0; x < texSize; x++) {
  79816. var v = xv2.subtract(xv1).scale(fy).add(xv1);
  79817. v.normalize();
  79818. var color = this.CalcProjectionSpherical(v, float32Array, inputWidth, inputHeight);
  79819. // 3 channels per pixels
  79820. textureArray[y * texSize * 3 + (x * 3) + 0] = color.r;
  79821. textureArray[y * texSize * 3 + (x * 3) + 1] = color.g;
  79822. textureArray[y * texSize * 3 + (x * 3) + 2] = color.b;
  79823. xv1 = xv1.add(rotDX1);
  79824. xv2 = xv2.add(rotDX2);
  79825. }
  79826. fy += dy;
  79827. }
  79828. return textureArray;
  79829. };
  79830. PanoramaToCubeMapTools.CalcProjectionSpherical = function (vDir, float32Array, inputWidth, inputHeight) {
  79831. var theta = Math.atan2(vDir.z, vDir.x);
  79832. var phi = Math.acos(vDir.y);
  79833. while (theta < -Math.PI)
  79834. theta += 2 * Math.PI;
  79835. while (theta > Math.PI)
  79836. theta -= 2 * Math.PI;
  79837. var dx = theta / Math.PI;
  79838. var dy = phi / Math.PI;
  79839. // recenter.
  79840. dx = dx * 0.5 + 0.5;
  79841. var px = Math.round(dx * inputWidth);
  79842. if (px < 0)
  79843. px = 0;
  79844. else if (px >= inputWidth)
  79845. px = inputWidth - 1;
  79846. var py = Math.round(dy * inputHeight);
  79847. if (py < 0)
  79848. py = 0;
  79849. else if (py >= inputHeight)
  79850. py = inputHeight - 1;
  79851. var inputY = (inputHeight - py - 1);
  79852. var r = float32Array[inputY * inputWidth * 3 + (px * 3) + 0];
  79853. var g = float32Array[inputY * inputWidth * 3 + (px * 3) + 1];
  79854. var b = float32Array[inputY * inputWidth * 3 + (px * 3) + 2];
  79855. return {
  79856. r: r,
  79857. g: g,
  79858. b: b
  79859. };
  79860. };
  79861. PanoramaToCubeMapTools.FACE_FRONT = [
  79862. new BABYLON.Vector3(-1.0, -1.0, -1.0),
  79863. new BABYLON.Vector3(1.0, -1.0, -1.0),
  79864. new BABYLON.Vector3(-1.0, 1.0, -1.0),
  79865. new BABYLON.Vector3(1.0, 1.0, -1.0)
  79866. ];
  79867. PanoramaToCubeMapTools.FACE_BACK = [
  79868. new BABYLON.Vector3(1.0, -1.0, 1.0),
  79869. new BABYLON.Vector3(-1.0, -1.0, 1.0),
  79870. new BABYLON.Vector3(1.0, 1.0, 1.0),
  79871. new BABYLON.Vector3(-1.0, 1.0, 1.0)
  79872. ];
  79873. PanoramaToCubeMapTools.FACE_RIGHT = [
  79874. new BABYLON.Vector3(1.0, -1.0, -1.0),
  79875. new BABYLON.Vector3(1.0, -1.0, 1.0),
  79876. new BABYLON.Vector3(1.0, 1.0, -1.0),
  79877. new BABYLON.Vector3(1.0, 1.0, 1.0)
  79878. ];
  79879. PanoramaToCubeMapTools.FACE_LEFT = [
  79880. new BABYLON.Vector3(-1.0, -1.0, 1.0),
  79881. new BABYLON.Vector3(-1.0, -1.0, -1.0),
  79882. new BABYLON.Vector3(-1.0, 1.0, 1.0),
  79883. new BABYLON.Vector3(-1.0, 1.0, -1.0)
  79884. ];
  79885. PanoramaToCubeMapTools.FACE_DOWN = [
  79886. new BABYLON.Vector3(-1.0, 1.0, -1.0),
  79887. new BABYLON.Vector3(1.0, 1.0, -1.0),
  79888. new BABYLON.Vector3(-1.0, 1.0, 1.0),
  79889. new BABYLON.Vector3(1.0, 1.0, 1.0)
  79890. ];
  79891. PanoramaToCubeMapTools.FACE_UP = [
  79892. new BABYLON.Vector3(-1.0, -1.0, 1.0),
  79893. new BABYLON.Vector3(1.0, -1.0, 1.0),
  79894. new BABYLON.Vector3(-1.0, -1.0, -1.0),
  79895. new BABYLON.Vector3(1.0, -1.0, -1.0)
  79896. ];
  79897. return PanoramaToCubeMapTools;
  79898. }());
  79899. BABYLON.PanoramaToCubeMapTools = PanoramaToCubeMapTools;
  79900. })(BABYLON || (BABYLON = {}));
  79901. //# sourceMappingURL=babylon.panoramaToCubemap.js.map
  79902. var BABYLON;
  79903. (function (BABYLON) {
  79904. ;
  79905. /**
  79906. * This groups tools to convert HDR texture to native colors array.
  79907. */
  79908. var HDRTools = /** @class */ (function () {
  79909. function HDRTools() {
  79910. }
  79911. HDRTools.Ldexp = function (mantissa, exponent) {
  79912. if (exponent > 1023) {
  79913. return mantissa * Math.pow(2, 1023) * Math.pow(2, exponent - 1023);
  79914. }
  79915. if (exponent < -1074) {
  79916. return mantissa * Math.pow(2, -1074) * Math.pow(2, exponent + 1074);
  79917. }
  79918. return mantissa * Math.pow(2, exponent);
  79919. };
  79920. HDRTools.Rgbe2float = function (float32array, red, green, blue, exponent, index) {
  79921. if (exponent > 0) { /*nonzero pixel*/
  79922. exponent = this.Ldexp(1.0, exponent - (128 + 8));
  79923. float32array[index + 0] = red * exponent;
  79924. float32array[index + 1] = green * exponent;
  79925. float32array[index + 2] = blue * exponent;
  79926. }
  79927. else {
  79928. float32array[index + 0] = 0;
  79929. float32array[index + 1] = 0;
  79930. float32array[index + 2] = 0;
  79931. }
  79932. };
  79933. HDRTools.readStringLine = function (uint8array, startIndex) {
  79934. var line = "";
  79935. var character = "";
  79936. for (var i = startIndex; i < uint8array.length - startIndex; i++) {
  79937. character = String.fromCharCode(uint8array[i]);
  79938. if (character == "\n") {
  79939. break;
  79940. }
  79941. line += character;
  79942. }
  79943. return line;
  79944. };
  79945. /**
  79946. * Reads header information from an RGBE texture stored in a native array.
  79947. * More information on this format are available here:
  79948. * https://en.wikipedia.org/wiki/RGBE_image_format
  79949. *
  79950. * @param uint8array The binary file stored in native array.
  79951. * @return The header information.
  79952. */
  79953. HDRTools.RGBE_ReadHeader = function (uint8array) {
  79954. var height = 0;
  79955. var width = 0;
  79956. var line = this.readStringLine(uint8array, 0);
  79957. if (line[0] != '#' || line[1] != '?') {
  79958. throw "Bad HDR Format.";
  79959. }
  79960. var endOfHeader = false;
  79961. var findFormat = false;
  79962. var lineIndex = 0;
  79963. do {
  79964. lineIndex += (line.length + 1);
  79965. line = this.readStringLine(uint8array, lineIndex);
  79966. if (line == "FORMAT=32-bit_rle_rgbe") {
  79967. findFormat = true;
  79968. }
  79969. else if (line.length == 0) {
  79970. endOfHeader = true;
  79971. }
  79972. } while (!endOfHeader);
  79973. if (!findFormat) {
  79974. throw "HDR Bad header format, unsupported FORMAT";
  79975. }
  79976. lineIndex += (line.length + 1);
  79977. line = this.readStringLine(uint8array, lineIndex);
  79978. var sizeRegexp = /^\-Y (.*) \+X (.*)$/g;
  79979. var match = sizeRegexp.exec(line);
  79980. // TODO. Support +Y and -X if needed.
  79981. if (!match || match.length < 3) {
  79982. throw "HDR Bad header format, no size";
  79983. }
  79984. width = parseInt(match[2]);
  79985. height = parseInt(match[1]);
  79986. if (width < 8 || width > 0x7fff) {
  79987. throw "HDR Bad header format, unsupported size";
  79988. }
  79989. lineIndex += (line.length + 1);
  79990. return {
  79991. height: height,
  79992. width: width,
  79993. dataPosition: lineIndex
  79994. };
  79995. };
  79996. /**
  79997. * Returns the cubemap information (each faces texture data) extracted from an RGBE texture.
  79998. * This RGBE texture needs to store the information as a panorama.
  79999. *
  80000. * More information on this format are available here:
  80001. * https://en.wikipedia.org/wiki/RGBE_image_format
  80002. *
  80003. * @param buffer The binary file stored in an array buffer.
  80004. * @param size The expected size of the extracted cubemap.
  80005. * @return The Cube Map information.
  80006. */
  80007. HDRTools.GetCubeMapTextureData = function (buffer, size) {
  80008. var uint8array = new Uint8Array(buffer);
  80009. var hdrInfo = this.RGBE_ReadHeader(uint8array);
  80010. var data = this.RGBE_ReadPixels_RLE(uint8array, hdrInfo);
  80011. var cubeMapData = BABYLON.PanoramaToCubeMapTools.ConvertPanoramaToCubemap(data, hdrInfo.width, hdrInfo.height, size);
  80012. return cubeMapData;
  80013. };
  80014. /**
  80015. * Returns the pixels data extracted from an RGBE texture.
  80016. * This pixels will be stored left to right up to down in the R G B order in one array.
  80017. *
  80018. * More information on this format are available here:
  80019. * https://en.wikipedia.org/wiki/RGBE_image_format
  80020. *
  80021. * @param uint8array The binary file stored in an array buffer.
  80022. * @param hdrInfo The header information of the file.
  80023. * @return The pixels data in RGB right to left up to down order.
  80024. */
  80025. HDRTools.RGBE_ReadPixels = function (uint8array, hdrInfo) {
  80026. // Keep for multi format supports.
  80027. return this.RGBE_ReadPixels_RLE(uint8array, hdrInfo);
  80028. };
  80029. HDRTools.RGBE_ReadPixels_RLE = function (uint8array, hdrInfo) {
  80030. var num_scanlines = hdrInfo.height;
  80031. var scanline_width = hdrInfo.width;
  80032. var a, b, c, d, count;
  80033. var dataIndex = hdrInfo.dataPosition;
  80034. var index = 0, endIndex = 0, i = 0;
  80035. var scanLineArrayBuffer = new ArrayBuffer(scanline_width * 4); // four channel R G B E
  80036. var scanLineArray = new Uint8Array(scanLineArrayBuffer);
  80037. // 3 channels of 4 bytes per pixel in float.
  80038. var resultBuffer = new ArrayBuffer(hdrInfo.width * hdrInfo.height * 4 * 3);
  80039. var resultArray = new Float32Array(resultBuffer);
  80040. // read in each successive scanline
  80041. while (num_scanlines > 0) {
  80042. a = uint8array[dataIndex++];
  80043. b = uint8array[dataIndex++];
  80044. c = uint8array[dataIndex++];
  80045. d = uint8array[dataIndex++];
  80046. if (a != 2 || b != 2 || (c & 0x80)) {
  80047. // this file is not run length encoded
  80048. throw "HDR Bad header format, not RLE";
  80049. }
  80050. if (((c << 8) | d) != scanline_width) {
  80051. throw "HDR Bad header format, wrong scan line width";
  80052. }
  80053. index = 0;
  80054. // read each of the four channels for the scanline into the buffer
  80055. for (i = 0; i < 4; i++) {
  80056. endIndex = (i + 1) * scanline_width;
  80057. while (index < endIndex) {
  80058. a = uint8array[dataIndex++];
  80059. b = uint8array[dataIndex++];
  80060. if (a > 128) {
  80061. // a run of the same value
  80062. count = a - 128;
  80063. if ((count == 0) || (count > endIndex - index)) {
  80064. throw "HDR Bad Format, bad scanline data (run)";
  80065. }
  80066. while (count-- > 0) {
  80067. scanLineArray[index++] = b;
  80068. }
  80069. }
  80070. else {
  80071. // a non-run
  80072. count = a;
  80073. if ((count == 0) || (count > endIndex - index)) {
  80074. throw "HDR Bad Format, bad scanline data (non-run)";
  80075. }
  80076. scanLineArray[index++] = b;
  80077. if (--count > 0) {
  80078. for (var j = 0; j < count; j++) {
  80079. scanLineArray[index++] = uint8array[dataIndex++];
  80080. }
  80081. }
  80082. }
  80083. }
  80084. }
  80085. // now convert data from buffer into floats
  80086. for (i = 0; i < scanline_width; i++) {
  80087. a = scanLineArray[i];
  80088. b = scanLineArray[i + scanline_width];
  80089. c = scanLineArray[i + 2 * scanline_width];
  80090. d = scanLineArray[i + 3 * scanline_width];
  80091. this.Rgbe2float(resultArray, a, b, c, d, (hdrInfo.height - num_scanlines) * scanline_width * 3 + i * 3);
  80092. }
  80093. num_scanlines--;
  80094. }
  80095. return resultArray;
  80096. };
  80097. return HDRTools;
  80098. }());
  80099. BABYLON.HDRTools = HDRTools;
  80100. })(BABYLON || (BABYLON = {}));
  80101. //# sourceMappingURL=babylon.hdr.js.map
  80102. var BABYLON;
  80103. (function (BABYLON) {
  80104. /**
  80105. * This represents a texture coming from an HDR input.
  80106. *
  80107. * The only supported format is currently panorama picture stored in RGBE format.
  80108. * Example of such files can be found on HDRLib: http://hdrlib.com/
  80109. */
  80110. var HDRCubeTexture = /** @class */ (function (_super) {
  80111. __extends(HDRCubeTexture, _super);
  80112. /**
  80113. * Instantiates an HDRTexture from the following parameters.
  80114. *
  80115. * @param url The location of the HDR raw data (Panorama stored in RGBE format)
  80116. * @param scene The scene the texture will be used in
  80117. * @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.
  80118. * @param noMipmap Forces to not generate the mipmap if true
  80119. * @param generateHarmonics Specifies whether you want to extract the polynomial harmonics during the generation process
  80120. * @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)
  80121. * @param usePMREMGenerator Specifies whether or not to generate the CubeMap through CubeMapGen to avoid seams issue at run time.
  80122. */
  80123. function HDRCubeTexture(url, scene, size, noMipmap, generateHarmonics, useInGammaSpace, usePMREMGenerator, onLoad, onError) {
  80124. if (noMipmap === void 0) { noMipmap = false; }
  80125. if (generateHarmonics === void 0) { generateHarmonics = true; }
  80126. if (useInGammaSpace === void 0) { useInGammaSpace = false; }
  80127. if (usePMREMGenerator === void 0) { usePMREMGenerator = false; }
  80128. if (onLoad === void 0) { onLoad = null; }
  80129. if (onError === void 0) { onError = null; }
  80130. var _this = _super.call(this, scene) || this;
  80131. _this._useInGammaSpace = false;
  80132. _this._generateHarmonics = true;
  80133. _this._isBABYLONPreprocessed = false;
  80134. _this._onLoad = null;
  80135. _this._onError = null;
  80136. /**
  80137. * The texture coordinates mode. As this texture is stored in a cube format, please modify carefully.
  80138. */
  80139. _this.coordinatesMode = BABYLON.Texture.CUBIC_MODE;
  80140. /**
  80141. * Specifies wether the texture has been generated through the PMREMGenerator tool.
  80142. * This is usefull at run time to apply the good shader.
  80143. */
  80144. _this.isPMREM = false;
  80145. _this._isBlocking = true;
  80146. _this._rotationY = 0;
  80147. /**
  80148. * Gets or sets the center of the bounding box associated with the cube texture
  80149. * It must define where the camera used to render the texture was set
  80150. */
  80151. _this.boundingBoxPosition = BABYLON.Vector3.Zero();
  80152. if (!url) {
  80153. return _this;
  80154. }
  80155. _this.name = url;
  80156. _this.url = url;
  80157. _this.hasAlpha = false;
  80158. _this.isCube = true;
  80159. _this._textureMatrix = BABYLON.Matrix.Identity();
  80160. _this._onLoad = onLoad;
  80161. _this._onError = onError;
  80162. _this.gammaSpace = false;
  80163. var caps = scene.getEngine().getCaps();
  80164. if (size) {
  80165. _this._isBABYLONPreprocessed = false;
  80166. _this._noMipmap = noMipmap;
  80167. _this._size = size;
  80168. _this._useInGammaSpace = useInGammaSpace;
  80169. _this._usePMREMGenerator = usePMREMGenerator &&
  80170. caps.textureLOD &&
  80171. caps.textureFloat &&
  80172. !_this._useInGammaSpace;
  80173. }
  80174. else {
  80175. _this._isBABYLONPreprocessed = true;
  80176. _this._noMipmap = false;
  80177. _this._useInGammaSpace = false;
  80178. _this._usePMREMGenerator = caps.textureLOD && caps.textureFloat &&
  80179. !_this._useInGammaSpace;
  80180. }
  80181. _this.isPMREM = _this._usePMREMGenerator;
  80182. _this._texture = _this._getFromCache(url, _this._noMipmap);
  80183. if (!_this._texture) {
  80184. if (!scene.useDelayedTextureLoading) {
  80185. _this.loadTexture();
  80186. }
  80187. else {
  80188. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  80189. }
  80190. }
  80191. return _this;
  80192. }
  80193. Object.defineProperty(HDRCubeTexture.prototype, "isBlocking", {
  80194. /**
  80195. * Gets wether or not the texture is blocking during loading.
  80196. */
  80197. get: function () {
  80198. return this._isBlocking;
  80199. },
  80200. /**
  80201. * Sets wether or not the texture is blocking during loading.
  80202. */
  80203. set: function (value) {
  80204. this._isBlocking = value;
  80205. },
  80206. enumerable: true,
  80207. configurable: true
  80208. });
  80209. Object.defineProperty(HDRCubeTexture.prototype, "rotationY", {
  80210. /**
  80211. * Gets texture matrix rotation angle around Y axis radians.
  80212. */
  80213. get: function () {
  80214. return this._rotationY;
  80215. },
  80216. /**
  80217. * Sets texture matrix rotation angle around Y axis in radians.
  80218. */
  80219. set: function (value) {
  80220. this._rotationY = value;
  80221. this.setReflectionTextureMatrix(BABYLON.Matrix.RotationY(this._rotationY));
  80222. },
  80223. enumerable: true,
  80224. configurable: true
  80225. });
  80226. Object.defineProperty(HDRCubeTexture.prototype, "boundingBoxSize", {
  80227. get: function () {
  80228. return this._boundingBoxSize;
  80229. },
  80230. /**
  80231. * Gets or sets the size of the bounding box associated with the cube texture
  80232. * When defined, the cubemap will switch to local mode
  80233. * @see https://community.arm.com/graphics/b/blog/posts/reflections-based-on-local-cubemaps-in-unity
  80234. * @example https://www.babylonjs-playground.com/#RNASML
  80235. */
  80236. set: function (value) {
  80237. if (this._boundingBoxSize && this._boundingBoxSize.equals(value)) {
  80238. return;
  80239. }
  80240. this._boundingBoxSize = value;
  80241. var scene = this.getScene();
  80242. if (scene) {
  80243. scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  80244. }
  80245. },
  80246. enumerable: true,
  80247. configurable: true
  80248. });
  80249. /**
  80250. * Occurs when the file is a preprocessed .babylon.hdr file.
  80251. */
  80252. HDRCubeTexture.prototype.loadBabylonTexture = function () {
  80253. var _this = this;
  80254. var mipLevels = 0;
  80255. var floatArrayView = null;
  80256. var scene = this.getScene();
  80257. var mipmapGenerator = (!this._useInGammaSpace && scene && scene.getEngine().getCaps().textureFloat) ? function (data) {
  80258. var mips = new Array();
  80259. if (!floatArrayView) {
  80260. return mips;
  80261. }
  80262. var startIndex = 30;
  80263. for (var level = 0; level < mipLevels; level++) {
  80264. mips.push([]);
  80265. // Fill each pixel of the mip level.
  80266. var faceSize = Math.pow(_this._size >> level, 2) * 3;
  80267. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  80268. var faceData = floatArrayView.subarray(startIndex, startIndex + faceSize);
  80269. mips[level].push(faceData);
  80270. startIndex += faceSize;
  80271. }
  80272. }
  80273. return mips;
  80274. } : null;
  80275. var callback = function (buffer) {
  80276. var scene = _this.getScene();
  80277. if (!scene) {
  80278. return null;
  80279. }
  80280. // Create Native Array Views
  80281. var intArrayView = new Int32Array(buffer);
  80282. floatArrayView = new Float32Array(buffer);
  80283. // Fill header.
  80284. var version = intArrayView[0]; // Version 1. (MAy be use in case of format changes for backward compaibility)
  80285. _this._size = intArrayView[1]; // CubeMap max mip face size.
  80286. // Update Texture Information.
  80287. if (!_this._texture) {
  80288. return null;
  80289. }
  80290. _this._texture.updateSize(_this._size, _this._size);
  80291. // Fill polynomial information.
  80292. var sphericalPolynomial = new BABYLON.SphericalPolynomial();
  80293. sphericalPolynomial.x.copyFromFloats(floatArrayView[2], floatArrayView[3], floatArrayView[4]);
  80294. sphericalPolynomial.y.copyFromFloats(floatArrayView[5], floatArrayView[6], floatArrayView[7]);
  80295. sphericalPolynomial.z.copyFromFloats(floatArrayView[8], floatArrayView[9], floatArrayView[10]);
  80296. sphericalPolynomial.xx.copyFromFloats(floatArrayView[11], floatArrayView[12], floatArrayView[13]);
  80297. sphericalPolynomial.yy.copyFromFloats(floatArrayView[14], floatArrayView[15], floatArrayView[16]);
  80298. sphericalPolynomial.zz.copyFromFloats(floatArrayView[17], floatArrayView[18], floatArrayView[19]);
  80299. sphericalPolynomial.xy.copyFromFloats(floatArrayView[20], floatArrayView[21], floatArrayView[22]);
  80300. sphericalPolynomial.yz.copyFromFloats(floatArrayView[23], floatArrayView[24], floatArrayView[25]);
  80301. sphericalPolynomial.zx.copyFromFloats(floatArrayView[26], floatArrayView[27], floatArrayView[28]);
  80302. _this.sphericalPolynomial = sphericalPolynomial;
  80303. // Fill pixel data.
  80304. mipLevels = intArrayView[29]; // Number of mip levels.
  80305. var startIndex = 30;
  80306. var data = [];
  80307. var faceSize = Math.pow(_this._size, 2) * 3;
  80308. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  80309. data.push(floatArrayView.subarray(startIndex, startIndex + faceSize));
  80310. startIndex += faceSize;
  80311. }
  80312. var results = [];
  80313. var byteArray = null;
  80314. // Push each faces.
  80315. for (var k = 0; k < 6; k++) {
  80316. var dataFace = null;
  80317. // To be deprecated.
  80318. if (version === 1) {
  80319. var j = ([0, 2, 4, 1, 3, 5])[k]; // Transforms +X+Y+Z... to +X-X+Y-Y...
  80320. dataFace = data[j];
  80321. }
  80322. // If special cases.
  80323. if (!mipmapGenerator && dataFace) {
  80324. if (!scene.getEngine().getCaps().textureFloat) {
  80325. // 3 channels of 1 bytes per pixel in bytes.
  80326. var byteBuffer = new ArrayBuffer(faceSize);
  80327. byteArray = new Uint8Array(byteBuffer);
  80328. }
  80329. for (var i = 0; i < _this._size * _this._size; i++) {
  80330. // Put in gamma space if requested.
  80331. if (_this._useInGammaSpace) {
  80332. dataFace[(i * 3) + 0] = Math.pow(dataFace[(i * 3) + 0], BABYLON.ToGammaSpace);
  80333. dataFace[(i * 3) + 1] = Math.pow(dataFace[(i * 3) + 1], BABYLON.ToGammaSpace);
  80334. dataFace[(i * 3) + 2] = Math.pow(dataFace[(i * 3) + 2], BABYLON.ToGammaSpace);
  80335. }
  80336. // Convert to int texture for fallback.
  80337. if (byteArray) {
  80338. var r = Math.max(dataFace[(i * 3) + 0] * 255, 0);
  80339. var g = Math.max(dataFace[(i * 3) + 1] * 255, 0);
  80340. var b = Math.max(dataFace[(i * 3) + 2] * 255, 0);
  80341. // May use luminance instead if the result is not accurate.
  80342. var max = Math.max(Math.max(r, g), b);
  80343. if (max > 255) {
  80344. var scale = 255 / max;
  80345. r *= scale;
  80346. g *= scale;
  80347. b *= scale;
  80348. }
  80349. byteArray[(i * 3) + 0] = r;
  80350. byteArray[(i * 3) + 1] = g;
  80351. byteArray[(i * 3) + 2] = b;
  80352. }
  80353. }
  80354. }
  80355. // Fill the array accordingly.
  80356. if (byteArray) {
  80357. results.push(byteArray);
  80358. }
  80359. else {
  80360. results.push(dataFace);
  80361. }
  80362. }
  80363. return results;
  80364. };
  80365. if (scene) {
  80366. 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);
  80367. }
  80368. };
  80369. /**
  80370. * Occurs when the file is raw .hdr file.
  80371. */
  80372. HDRCubeTexture.prototype.loadHDRTexture = function () {
  80373. var _this = this;
  80374. var callback = function (buffer) {
  80375. var scene = _this.getScene();
  80376. if (!scene) {
  80377. return null;
  80378. }
  80379. // Extract the raw linear data.
  80380. var data = BABYLON.HDRTools.GetCubeMapTextureData(buffer, _this._size);
  80381. // Generate harmonics if needed.
  80382. if (_this._generateHarmonics) {
  80383. var sphericalPolynomial = BABYLON.CubeMapToSphericalPolynomialTools.ConvertCubeMapToSphericalPolynomial(data);
  80384. _this.sphericalPolynomial = sphericalPolynomial;
  80385. }
  80386. var results = [];
  80387. var byteArray = null;
  80388. // Push each faces.
  80389. for (var j = 0; j < 6; j++) {
  80390. // Create uintarray fallback.
  80391. if (!scene.getEngine().getCaps().textureFloat) {
  80392. // 3 channels of 1 bytes per pixel in bytes.
  80393. var byteBuffer = new ArrayBuffer(_this._size * _this._size * 3);
  80394. byteArray = new Uint8Array(byteBuffer);
  80395. }
  80396. var dataFace = (data[HDRCubeTexture._facesMapping[j]]);
  80397. // If special cases.
  80398. if (_this._useInGammaSpace || byteArray) {
  80399. for (var i = 0; i < _this._size * _this._size; i++) {
  80400. // Put in gamma space if requested.
  80401. if (_this._useInGammaSpace) {
  80402. dataFace[(i * 3) + 0] = Math.pow(dataFace[(i * 3) + 0], BABYLON.ToGammaSpace);
  80403. dataFace[(i * 3) + 1] = Math.pow(dataFace[(i * 3) + 1], BABYLON.ToGammaSpace);
  80404. dataFace[(i * 3) + 2] = Math.pow(dataFace[(i * 3) + 2], BABYLON.ToGammaSpace);
  80405. }
  80406. // Convert to int texture for fallback.
  80407. if (byteArray) {
  80408. var r = Math.max(dataFace[(i * 3) + 0] * 255, 0);
  80409. var g = Math.max(dataFace[(i * 3) + 1] * 255, 0);
  80410. var b = Math.max(dataFace[(i * 3) + 2] * 255, 0);
  80411. // May use luminance instead if the result is not accurate.
  80412. var max = Math.max(Math.max(r, g), b);
  80413. if (max > 255) {
  80414. var scale = 255 / max;
  80415. r *= scale;
  80416. g *= scale;
  80417. b *= scale;
  80418. }
  80419. byteArray[(i * 3) + 0] = r;
  80420. byteArray[(i * 3) + 1] = g;
  80421. byteArray[(i * 3) + 2] = b;
  80422. }
  80423. }
  80424. }
  80425. if (byteArray) {
  80426. results.push(byteArray);
  80427. }
  80428. else {
  80429. results.push(dataFace);
  80430. }
  80431. }
  80432. return results;
  80433. };
  80434. var mipmapGenerator = null;
  80435. // TODO. Implement In code PMREM Generator following the LYS toolset generation.
  80436. // if (!this._noMipmap &&
  80437. // this._usePMREMGenerator) {
  80438. // mipmapGenerator = (data: ArrayBufferView[]) => {
  80439. // // Custom setup of the generator matching with the PBR shader values.
  80440. // var generator = new BABYLON.PMREMGenerator(data,
  80441. // this._size,
  80442. // this._size,
  80443. // 0,
  80444. // 3,
  80445. // this.getScene().getEngine().getCaps().textureFloat,
  80446. // 2048,
  80447. // 0.25,
  80448. // false,
  80449. // true);
  80450. // return generator.filterCubeMap();
  80451. // };
  80452. // }
  80453. var scene = this.getScene();
  80454. if (scene) {
  80455. 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);
  80456. }
  80457. };
  80458. /**
  80459. * Starts the loading process of the texture.
  80460. */
  80461. HDRCubeTexture.prototype.loadTexture = function () {
  80462. if (this._isBABYLONPreprocessed) {
  80463. this.loadBabylonTexture();
  80464. }
  80465. else {
  80466. this.loadHDRTexture();
  80467. }
  80468. };
  80469. HDRCubeTexture.prototype.clone = function () {
  80470. var scene = this.getScene();
  80471. if (!scene) {
  80472. return this;
  80473. }
  80474. var size = (this._isBABYLONPreprocessed ? null : this._size);
  80475. var newTexture = new HDRCubeTexture(this.url, scene, size, this._noMipmap, this._generateHarmonics, this._useInGammaSpace, this._usePMREMGenerator);
  80476. // Base texture
  80477. newTexture.level = this.level;
  80478. newTexture.wrapU = this.wrapU;
  80479. newTexture.wrapV = this.wrapV;
  80480. newTexture.coordinatesIndex = this.coordinatesIndex;
  80481. newTexture.coordinatesMode = this.coordinatesMode;
  80482. return newTexture;
  80483. };
  80484. // Methods
  80485. HDRCubeTexture.prototype.delayLoad = function () {
  80486. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  80487. return;
  80488. }
  80489. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  80490. this._texture = this._getFromCache(this.url, this._noMipmap);
  80491. if (!this._texture) {
  80492. this.loadTexture();
  80493. }
  80494. };
  80495. HDRCubeTexture.prototype.getReflectionTextureMatrix = function () {
  80496. return this._textureMatrix;
  80497. };
  80498. HDRCubeTexture.prototype.setReflectionTextureMatrix = function (value) {
  80499. this._textureMatrix = value;
  80500. };
  80501. HDRCubeTexture.Parse = function (parsedTexture, scene, rootUrl) {
  80502. var texture = null;
  80503. if (parsedTexture.name && !parsedTexture.isRenderTarget) {
  80504. var size = parsedTexture.isBABYLONPreprocessed ? null : parsedTexture.size;
  80505. texture = new HDRCubeTexture(rootUrl + parsedTexture.name, scene, size, parsedTexture.noMipmap, parsedTexture.generateHarmonics, parsedTexture.useInGammaSpace, parsedTexture.usePMREMGenerator);
  80506. texture.name = parsedTexture.name;
  80507. texture.hasAlpha = parsedTexture.hasAlpha;
  80508. texture.level = parsedTexture.level;
  80509. texture.coordinatesMode = parsedTexture.coordinatesMode;
  80510. texture.isBlocking = parsedTexture.isBlocking;
  80511. }
  80512. if (texture) {
  80513. if (parsedTexture.boundingBoxPosition) {
  80514. texture.boundingBoxPosition = BABYLON.Vector3.FromArray(parsedTexture.boundingBoxPosition);
  80515. }
  80516. if (parsedTexture.boundingBoxSize) {
  80517. texture.boundingBoxSize = BABYLON.Vector3.FromArray(parsedTexture.boundingBoxSize);
  80518. }
  80519. if (parsedTexture.rotationY) {
  80520. texture.rotationY = parsedTexture.rotationY;
  80521. }
  80522. }
  80523. return texture;
  80524. };
  80525. HDRCubeTexture.prototype.serialize = function () {
  80526. if (!this.name) {
  80527. return null;
  80528. }
  80529. var serializationObject = {};
  80530. serializationObject.name = this.name;
  80531. serializationObject.hasAlpha = this.hasAlpha;
  80532. serializationObject.isCube = true;
  80533. serializationObject.level = this.level;
  80534. serializationObject.size = this._size;
  80535. serializationObject.coordinatesMode = this.coordinatesMode;
  80536. serializationObject.useInGammaSpace = this._useInGammaSpace;
  80537. serializationObject.generateHarmonics = this._generateHarmonics;
  80538. serializationObject.usePMREMGenerator = this._usePMREMGenerator;
  80539. serializationObject.isBABYLONPreprocessed = this._isBABYLONPreprocessed;
  80540. serializationObject.customType = "BABYLON.HDRCubeTexture";
  80541. serializationObject.noMipmap = this._noMipmap;
  80542. serializationObject.isBlocking = this._isBlocking;
  80543. serializationObject.rotationY = this._rotationY;
  80544. return serializationObject;
  80545. };
  80546. /**
  80547. * Saves as a file the data contained in the texture in a binary format.
  80548. * This can be used to prevent the long loading tie associated with creating the seamless texture as well
  80549. * as the spherical used in the lighting.
  80550. * @param url The HDR file url.
  80551. * @param size The size of the texture data to generate (one of the cubemap face desired width).
  80552. * @param onError Method called if any error happens during download.
  80553. * @return The packed binary data.
  80554. */
  80555. HDRCubeTexture.generateBabylonHDROnDisk = function (url, size, onError) {
  80556. if (onError === void 0) { onError = null; }
  80557. var callback = function (buffer) {
  80558. var data = new Blob([buffer], { type: 'application/octet-stream' });
  80559. // Returns a URL you can use as a href.
  80560. var objUrl = window.URL.createObjectURL(data);
  80561. // Simulates a link to it and click to dowload.
  80562. var a = document.createElement("a");
  80563. document.body.appendChild(a);
  80564. a.style.display = "none";
  80565. a.href = objUrl;
  80566. a.download = "envmap.babylon.hdr";
  80567. a.click();
  80568. };
  80569. HDRCubeTexture.generateBabylonHDR(url, size, callback, onError);
  80570. };
  80571. /**
  80572. * Serializes the data contained in the texture in a binary format.
  80573. * This can be used to prevent the long loading tie associated with creating the seamless texture as well
  80574. * as the spherical used in the lighting.
  80575. * @param url The HDR file url.
  80576. * @param size The size of the texture data to generate (one of the cubemap face desired width).
  80577. * @param onError Method called if any error happens during download.
  80578. * @return The packed binary data.
  80579. */
  80580. HDRCubeTexture.generateBabylonHDR = function (url, size, callback, onError) {
  80581. if (onError === void 0) { onError = null; }
  80582. // Needs the url tho create the texture.
  80583. if (!url) {
  80584. return;
  80585. }
  80586. // Check Power of two size.
  80587. if (!BABYLON.Tools.IsExponentOfTwo(size)) { // Need to check engine.needPOTTextures
  80588. return;
  80589. }
  80590. // Coming Back in 3.x.
  80591. BABYLON.Tools.Error("Generation of Babylon HDR is coming back in 3.2.");
  80592. };
  80593. HDRCubeTexture._facesMapping = [
  80594. "right",
  80595. "left",
  80596. "up",
  80597. "down",
  80598. "front",
  80599. "back"
  80600. ];
  80601. return HDRCubeTexture;
  80602. }(BABYLON.BaseTexture));
  80603. BABYLON.HDRCubeTexture = HDRCubeTexture;
  80604. })(BABYLON || (BABYLON = {}));
  80605. //# sourceMappingURL=babylon.hdrCubeTexture.js.map
  80606. var BABYLON;
  80607. (function (BABYLON) {
  80608. var IndexedVector2 = /** @class */ (function (_super) {
  80609. __extends(IndexedVector2, _super);
  80610. function IndexedVector2(original, index) {
  80611. var _this = _super.call(this, original.x, original.y) || this;
  80612. _this.index = index;
  80613. return _this;
  80614. }
  80615. return IndexedVector2;
  80616. }(BABYLON.Vector2));
  80617. var PolygonPoints = /** @class */ (function () {
  80618. function PolygonPoints() {
  80619. this.elements = new Array();
  80620. }
  80621. PolygonPoints.prototype.add = function (originalPoints) {
  80622. var _this = this;
  80623. var result = new Array();
  80624. originalPoints.forEach(function (point) {
  80625. if (result.length === 0 || !point.equalsWithEpsilon(result[0])) {
  80626. var newPoint = new IndexedVector2(point, _this.elements.length);
  80627. result.push(newPoint);
  80628. _this.elements.push(newPoint);
  80629. }
  80630. });
  80631. return result;
  80632. };
  80633. PolygonPoints.prototype.computeBounds = function () {
  80634. var lmin = new BABYLON.Vector2(this.elements[0].x, this.elements[0].y);
  80635. var lmax = new BABYLON.Vector2(this.elements[0].x, this.elements[0].y);
  80636. this.elements.forEach(function (point) {
  80637. // x
  80638. if (point.x < lmin.x) {
  80639. lmin.x = point.x;
  80640. }
  80641. else if (point.x > lmax.x) {
  80642. lmax.x = point.x;
  80643. }
  80644. // y
  80645. if (point.y < lmin.y) {
  80646. lmin.y = point.y;
  80647. }
  80648. else if (point.y > lmax.y) {
  80649. lmax.y = point.y;
  80650. }
  80651. });
  80652. return {
  80653. min: lmin,
  80654. max: lmax,
  80655. width: lmax.x - lmin.x,
  80656. height: lmax.y - lmin.y
  80657. };
  80658. };
  80659. return PolygonPoints;
  80660. }());
  80661. var Polygon = /** @class */ (function () {
  80662. function Polygon() {
  80663. }
  80664. Polygon.Rectangle = function (xmin, ymin, xmax, ymax) {
  80665. return [
  80666. new BABYLON.Vector2(xmin, ymin),
  80667. new BABYLON.Vector2(xmax, ymin),
  80668. new BABYLON.Vector2(xmax, ymax),
  80669. new BABYLON.Vector2(xmin, ymax)
  80670. ];
  80671. };
  80672. Polygon.Circle = function (radius, cx, cy, numberOfSides) {
  80673. if (cx === void 0) { cx = 0; }
  80674. if (cy === void 0) { cy = 0; }
  80675. if (numberOfSides === void 0) { numberOfSides = 32; }
  80676. var result = new Array();
  80677. var angle = 0;
  80678. var increment = (Math.PI * 2) / numberOfSides;
  80679. for (var i = 0; i < numberOfSides; i++) {
  80680. result.push(new BABYLON.Vector2(cx + Math.cos(angle) * radius, cy + Math.sin(angle) * radius));
  80681. angle -= increment;
  80682. }
  80683. return result;
  80684. };
  80685. Polygon.Parse = function (input) {
  80686. var floats = input.split(/[^-+eE\.\d]+/).map(parseFloat).filter(function (val) { return (!isNaN(val)); });
  80687. var i, result = [];
  80688. for (i = 0; i < (floats.length & 0x7FFFFFFE); i += 2) {
  80689. result.push(new BABYLON.Vector2(floats[i], floats[i + 1]));
  80690. }
  80691. return result;
  80692. };
  80693. Polygon.StartingAt = function (x, y) {
  80694. return BABYLON.Path2.StartingAt(x, y);
  80695. };
  80696. return Polygon;
  80697. }());
  80698. BABYLON.Polygon = Polygon;
  80699. var PolygonMeshBuilder = /** @class */ (function () {
  80700. function PolygonMeshBuilder(name, contours, scene) {
  80701. this._points = new PolygonPoints();
  80702. this._outlinepoints = new PolygonPoints();
  80703. this._holes = new Array();
  80704. this._epoints = new Array();
  80705. this._eholes = new Array();
  80706. this._name = name;
  80707. this._scene = scene;
  80708. var points;
  80709. if (contours instanceof BABYLON.Path2) {
  80710. points = contours.getPoints();
  80711. }
  80712. else {
  80713. points = contours;
  80714. }
  80715. this._addToepoint(points);
  80716. this._points.add(points);
  80717. this._outlinepoints.add(points);
  80718. if (typeof earcut === 'undefined') {
  80719. BABYLON.Tools.Warn("Earcut was not found, the polygon will not be built.");
  80720. }
  80721. }
  80722. PolygonMeshBuilder.prototype._addToepoint = function (points) {
  80723. for (var _i = 0, points_1 = points; _i < points_1.length; _i++) {
  80724. var p = points_1[_i];
  80725. this._epoints.push(p.x, p.y);
  80726. }
  80727. };
  80728. PolygonMeshBuilder.prototype.addHole = function (hole) {
  80729. this._points.add(hole);
  80730. var holepoints = new PolygonPoints();
  80731. holepoints.add(hole);
  80732. this._holes.push(holepoints);
  80733. this._eholes.push(this._epoints.length / 2);
  80734. this._addToepoint(hole);
  80735. return this;
  80736. };
  80737. PolygonMeshBuilder.prototype.build = function (updatable, depth) {
  80738. var _this = this;
  80739. if (updatable === void 0) { updatable = false; }
  80740. if (depth === void 0) { depth = 0; }
  80741. var result = new BABYLON.Mesh(this._name, this._scene);
  80742. var normals = new Array();
  80743. var positions = new Array();
  80744. var uvs = new Array();
  80745. var bounds = this._points.computeBounds();
  80746. this._points.elements.forEach(function (p) {
  80747. normals.push(0, 1.0, 0);
  80748. positions.push(p.x, 0, p.y);
  80749. uvs.push((p.x - bounds.min.x) / bounds.width, (p.y - bounds.min.y) / bounds.height);
  80750. });
  80751. var indices = new Array();
  80752. var res = earcut(this._epoints, this._eholes, 2);
  80753. for (var i = 0; i < res.length; i++) {
  80754. indices.push(res[i]);
  80755. }
  80756. if (depth > 0) {
  80757. var positionscount = (positions.length / 3); //get the current pointcount
  80758. this._points.elements.forEach(function (p) {
  80759. normals.push(0, -1.0, 0);
  80760. positions.push(p.x, -depth, p.y);
  80761. uvs.push(1 - (p.x - bounds.min.x) / bounds.width, 1 - (p.y - bounds.min.y) / bounds.height);
  80762. });
  80763. var totalCount = indices.length;
  80764. for (var i = 0; i < totalCount; i += 3) {
  80765. var i0 = indices[i + 0];
  80766. var i1 = indices[i + 1];
  80767. var i2 = indices[i + 2];
  80768. indices.push(i2 + positionscount);
  80769. indices.push(i1 + positionscount);
  80770. indices.push(i0 + positionscount);
  80771. }
  80772. //Add the sides
  80773. this.addSide(positions, normals, uvs, indices, bounds, this._outlinepoints, depth, false);
  80774. this._holes.forEach(function (hole) {
  80775. _this.addSide(positions, normals, uvs, indices, bounds, hole, depth, true);
  80776. });
  80777. }
  80778. result.setVerticesData(BABYLON.VertexBuffer.PositionKind, positions, updatable);
  80779. result.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals, updatable);
  80780. result.setVerticesData(BABYLON.VertexBuffer.UVKind, uvs, updatable);
  80781. result.setIndices(indices);
  80782. return result;
  80783. };
  80784. PolygonMeshBuilder.prototype.addSide = function (positions, normals, uvs, indices, bounds, points, depth, flip) {
  80785. var StartIndex = positions.length / 3;
  80786. var ulength = 0;
  80787. for (var i = 0; i < points.elements.length; i++) {
  80788. var p = points.elements[i];
  80789. var p1;
  80790. if ((i + 1) > points.elements.length - 1) {
  80791. p1 = points.elements[0];
  80792. }
  80793. else {
  80794. p1 = points.elements[i + 1];
  80795. }
  80796. positions.push(p.x, 0, p.y);
  80797. positions.push(p.x, -depth, p.y);
  80798. positions.push(p1.x, 0, p1.y);
  80799. positions.push(p1.x, -depth, p1.y);
  80800. var v1 = new BABYLON.Vector3(p.x, 0, p.y);
  80801. var v2 = new BABYLON.Vector3(p1.x, 0, p1.y);
  80802. var v3 = v2.subtract(v1);
  80803. var v4 = new BABYLON.Vector3(0, 1, 0);
  80804. var vn = BABYLON.Vector3.Cross(v3, v4);
  80805. vn = vn.normalize();
  80806. uvs.push(ulength / bounds.width, 0);
  80807. uvs.push(ulength / bounds.width, 1);
  80808. ulength += v3.length();
  80809. uvs.push((ulength / bounds.width), 0);
  80810. uvs.push((ulength / bounds.width), 1);
  80811. if (!flip) {
  80812. normals.push(-vn.x, -vn.y, -vn.z);
  80813. normals.push(-vn.x, -vn.y, -vn.z);
  80814. normals.push(-vn.x, -vn.y, -vn.z);
  80815. normals.push(-vn.x, -vn.y, -vn.z);
  80816. indices.push(StartIndex);
  80817. indices.push(StartIndex + 1);
  80818. indices.push(StartIndex + 2);
  80819. indices.push(StartIndex + 1);
  80820. indices.push(StartIndex + 3);
  80821. indices.push(StartIndex + 2);
  80822. }
  80823. else {
  80824. normals.push(vn.x, vn.y, vn.z);
  80825. normals.push(vn.x, vn.y, vn.z);
  80826. normals.push(vn.x, vn.y, vn.z);
  80827. normals.push(vn.x, vn.y, vn.z);
  80828. indices.push(StartIndex);
  80829. indices.push(StartIndex + 2);
  80830. indices.push(StartIndex + 1);
  80831. indices.push(StartIndex + 1);
  80832. indices.push(StartIndex + 2);
  80833. indices.push(StartIndex + 3);
  80834. }
  80835. StartIndex += 4;
  80836. }
  80837. ;
  80838. };
  80839. return PolygonMeshBuilder;
  80840. }());
  80841. BABYLON.PolygonMeshBuilder = PolygonMeshBuilder;
  80842. })(BABYLON || (BABYLON = {}));
  80843. //# sourceMappingURL=babylon.polygonMesh.js.map
  80844. var BABYLON;
  80845. (function (BABYLON) {
  80846. // Unique ID when we import meshes from Babylon to CSG
  80847. var currentCSGMeshId = 0;
  80848. // # class Vertex
  80849. // Represents a vertex of a polygon. Use your own vertex class instead of this
  80850. // one to provide additional features like texture coordinates and vertex
  80851. // colors. Custom vertex classes need to provide a `pos` property and `clone()`,
  80852. // `flip()`, and `interpolate()` methods that behave analogous to the ones
  80853. // defined by `BABYLON.CSG.Vertex`. This class provides `normal` so convenience
  80854. // functions like `BABYLON.CSG.sphere()` can return a smooth vertex normal, but `normal`
  80855. // is not used anywhere else.
  80856. // Same goes for uv, it allows to keep the original vertex uv coordinates of the 2 meshes
  80857. var Vertex = /** @class */ (function () {
  80858. function Vertex(pos, normal, uv) {
  80859. this.pos = pos;
  80860. this.normal = normal;
  80861. this.uv = uv;
  80862. }
  80863. Vertex.prototype.clone = function () {
  80864. return new Vertex(this.pos.clone(), this.normal.clone(), this.uv.clone());
  80865. };
  80866. // Invert all orientation-specific data (e.g. vertex normal). Called when the
  80867. // orientation of a polygon is flipped.
  80868. Vertex.prototype.flip = function () {
  80869. this.normal = this.normal.scale(-1);
  80870. };
  80871. // Create a new vertex between this vertex and `other` by linearly
  80872. // interpolating all properties using a parameter of `t`. Subclasses should
  80873. // override this to interpolate additional properties.
  80874. Vertex.prototype.interpolate = function (other, t) {
  80875. 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));
  80876. };
  80877. return Vertex;
  80878. }());
  80879. // # class Plane
  80880. // Represents a plane in 3D space.
  80881. var Plane = /** @class */ (function () {
  80882. function Plane(normal, w) {
  80883. this.normal = normal;
  80884. this.w = w;
  80885. }
  80886. Plane.FromPoints = function (a, b, c) {
  80887. var v0 = c.subtract(a);
  80888. var v1 = b.subtract(a);
  80889. if (v0.lengthSquared() === 0 || v1.lengthSquared() === 0) {
  80890. return null;
  80891. }
  80892. var n = BABYLON.Vector3.Normalize(BABYLON.Vector3.Cross(v0, v1));
  80893. return new Plane(n, BABYLON.Vector3.Dot(n, a));
  80894. };
  80895. Plane.prototype.clone = function () {
  80896. return new Plane(this.normal.clone(), this.w);
  80897. };
  80898. Plane.prototype.flip = function () {
  80899. this.normal.scaleInPlace(-1);
  80900. this.w = -this.w;
  80901. };
  80902. // Split `polygon` by this plane if needed, then put the polygon or polygon
  80903. // fragments in the appropriate lists. Coplanar polygons go into either
  80904. // `coplanarFront` or `coplanarBack` depending on their orientation with
  80905. // respect to this plane. Polygons in front or in back of this plane go into
  80906. // either `front` or `back`.
  80907. Plane.prototype.splitPolygon = function (polygon, coplanarFront, coplanarBack, front, back) {
  80908. var COPLANAR = 0;
  80909. var FRONT = 1;
  80910. var BACK = 2;
  80911. var SPANNING = 3;
  80912. // Classify each point as well as the entire polygon into one of the above
  80913. // four classes.
  80914. var polygonType = 0;
  80915. var types = [];
  80916. var i;
  80917. var t;
  80918. for (i = 0; i < polygon.vertices.length; i++) {
  80919. t = BABYLON.Vector3.Dot(this.normal, polygon.vertices[i].pos) - this.w;
  80920. var type = (t < -Plane.EPSILON) ? BACK : (t > Plane.EPSILON) ? FRONT : COPLANAR;
  80921. polygonType |= type;
  80922. types.push(type);
  80923. }
  80924. // Put the polygon in the correct list, splitting it when necessary.
  80925. switch (polygonType) {
  80926. case COPLANAR:
  80927. (BABYLON.Vector3.Dot(this.normal, polygon.plane.normal) > 0 ? coplanarFront : coplanarBack).push(polygon);
  80928. break;
  80929. case FRONT:
  80930. front.push(polygon);
  80931. break;
  80932. case BACK:
  80933. back.push(polygon);
  80934. break;
  80935. case SPANNING:
  80936. var f = [], b = [];
  80937. for (i = 0; i < polygon.vertices.length; i++) {
  80938. var j = (i + 1) % polygon.vertices.length;
  80939. var ti = types[i], tj = types[j];
  80940. var vi = polygon.vertices[i], vj = polygon.vertices[j];
  80941. if (ti !== BACK)
  80942. f.push(vi);
  80943. if (ti !== FRONT)
  80944. b.push(ti !== BACK ? vi.clone() : vi);
  80945. if ((ti | tj) === SPANNING) {
  80946. t = (this.w - BABYLON.Vector3.Dot(this.normal, vi.pos)) / BABYLON.Vector3.Dot(this.normal, vj.pos.subtract(vi.pos));
  80947. var v = vi.interpolate(vj, t);
  80948. f.push(v);
  80949. b.push(v.clone());
  80950. }
  80951. }
  80952. var poly;
  80953. if (f.length >= 3) {
  80954. poly = new Polygon(f, polygon.shared);
  80955. if (poly.plane)
  80956. front.push(poly);
  80957. }
  80958. if (b.length >= 3) {
  80959. poly = new Polygon(b, polygon.shared);
  80960. if (poly.plane)
  80961. back.push(poly);
  80962. }
  80963. break;
  80964. }
  80965. };
  80966. // `BABYLON.CSG.Plane.EPSILON` is the tolerance used by `splitPolygon()` to decide if a
  80967. // point is on the plane.
  80968. Plane.EPSILON = 1e-5;
  80969. return Plane;
  80970. }());
  80971. // # class Polygon
  80972. // Represents a convex polygon. The vertices used to initialize a polygon must
  80973. // be coplanar and form a convex loop.
  80974. //
  80975. // Each convex polygon has a `shared` property, which is shared between all
  80976. // polygons that are clones of each other or were split from the same polygon.
  80977. // This can be used to define per-polygon properties (such as surface color).
  80978. var Polygon = /** @class */ (function () {
  80979. function Polygon(vertices, shared) {
  80980. this.vertices = vertices;
  80981. this.shared = shared;
  80982. this.plane = Plane.FromPoints(vertices[0].pos, vertices[1].pos, vertices[2].pos);
  80983. }
  80984. Polygon.prototype.clone = function () {
  80985. var vertices = this.vertices.map(function (v) { return v.clone(); });
  80986. return new Polygon(vertices, this.shared);
  80987. };
  80988. Polygon.prototype.flip = function () {
  80989. this.vertices.reverse().map(function (v) { v.flip(); });
  80990. this.plane.flip();
  80991. };
  80992. return Polygon;
  80993. }());
  80994. // # class Node
  80995. // Holds a node in a BSP tree. A BSP tree is built from a collection of polygons
  80996. // by picking a polygon to split along. That polygon (and all other coplanar
  80997. // polygons) are added directly to that node and the other polygons are added to
  80998. // the front and/or back subtrees. This is not a leafy BSP tree since there is
  80999. // no distinction between internal and leaf nodes.
  81000. var Node = /** @class */ (function () {
  81001. function Node(polygons) {
  81002. this.plane = null;
  81003. this.front = null;
  81004. this.back = null;
  81005. this.polygons = new Array();
  81006. if (polygons) {
  81007. this.build(polygons);
  81008. }
  81009. }
  81010. Node.prototype.clone = function () {
  81011. var node = new Node();
  81012. node.plane = this.plane && this.plane.clone();
  81013. node.front = this.front && this.front.clone();
  81014. node.back = this.back && this.back.clone();
  81015. node.polygons = this.polygons.map(function (p) { return p.clone(); });
  81016. return node;
  81017. };
  81018. // Convert solid space to empty space and empty space to solid space.
  81019. Node.prototype.invert = function () {
  81020. for (var i = 0; i < this.polygons.length; i++) {
  81021. this.polygons[i].flip();
  81022. }
  81023. if (this.plane) {
  81024. this.plane.flip();
  81025. }
  81026. if (this.front) {
  81027. this.front.invert();
  81028. }
  81029. if (this.back) {
  81030. this.back.invert();
  81031. }
  81032. var temp = this.front;
  81033. this.front = this.back;
  81034. this.back = temp;
  81035. };
  81036. // Recursively remove all polygons in `polygons` that are inside this BSP
  81037. // tree.
  81038. Node.prototype.clipPolygons = function (polygons) {
  81039. if (!this.plane)
  81040. return polygons.slice();
  81041. var front = new Array(), back = new Array();
  81042. for (var i = 0; i < polygons.length; i++) {
  81043. this.plane.splitPolygon(polygons[i], front, back, front, back);
  81044. }
  81045. if (this.front) {
  81046. front = this.front.clipPolygons(front);
  81047. }
  81048. if (this.back) {
  81049. back = this.back.clipPolygons(back);
  81050. }
  81051. else {
  81052. back = [];
  81053. }
  81054. return front.concat(back);
  81055. };
  81056. // Remove all polygons in this BSP tree that are inside the other BSP tree
  81057. // `bsp`.
  81058. Node.prototype.clipTo = function (bsp) {
  81059. this.polygons = bsp.clipPolygons(this.polygons);
  81060. if (this.front)
  81061. this.front.clipTo(bsp);
  81062. if (this.back)
  81063. this.back.clipTo(bsp);
  81064. };
  81065. // Return a list of all polygons in this BSP tree.
  81066. Node.prototype.allPolygons = function () {
  81067. var polygons = this.polygons.slice();
  81068. if (this.front)
  81069. polygons = polygons.concat(this.front.allPolygons());
  81070. if (this.back)
  81071. polygons = polygons.concat(this.back.allPolygons());
  81072. return polygons;
  81073. };
  81074. // Build a BSP tree out of `polygons`. When called on an existing tree, the
  81075. // new polygons are filtered down to the bottom of the tree and become new
  81076. // nodes there. Each set of polygons is partitioned using the first polygon
  81077. // (no heuristic is used to pick a good split).
  81078. Node.prototype.build = function (polygons) {
  81079. if (!polygons.length)
  81080. return;
  81081. if (!this.plane)
  81082. this.plane = polygons[0].plane.clone();
  81083. var front = new Array(), back = new Array();
  81084. for (var i = 0; i < polygons.length; i++) {
  81085. this.plane.splitPolygon(polygons[i], this.polygons, this.polygons, front, back);
  81086. }
  81087. if (front.length) {
  81088. if (!this.front)
  81089. this.front = new Node();
  81090. this.front.build(front);
  81091. }
  81092. if (back.length) {
  81093. if (!this.back)
  81094. this.back = new Node();
  81095. this.back.build(back);
  81096. }
  81097. };
  81098. return Node;
  81099. }());
  81100. var CSG = /** @class */ (function () {
  81101. function CSG() {
  81102. this.polygons = new Array();
  81103. }
  81104. // Convert BABYLON.Mesh to BABYLON.CSG
  81105. CSG.FromMesh = function (mesh) {
  81106. var vertex, normal, uv, position, polygon, polygons = new Array(), vertices;
  81107. var matrix, meshPosition, meshRotation, meshRotationQuaternion = null, meshScaling;
  81108. if (mesh instanceof BABYLON.Mesh) {
  81109. mesh.computeWorldMatrix(true);
  81110. matrix = mesh.getWorldMatrix();
  81111. meshPosition = mesh.position.clone();
  81112. meshRotation = mesh.rotation.clone();
  81113. if (mesh.rotationQuaternion) {
  81114. meshRotationQuaternion = mesh.rotationQuaternion.clone();
  81115. }
  81116. meshScaling = mesh.scaling.clone();
  81117. }
  81118. else {
  81119. throw 'BABYLON.CSG: Wrong Mesh type, must be BABYLON.Mesh';
  81120. }
  81121. var indices = mesh.getIndices(), positions = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind), normals = mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind), uvs = mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  81122. var subMeshes = mesh.subMeshes;
  81123. for (var sm = 0, sml = subMeshes.length; sm < sml; sm++) {
  81124. for (var i = subMeshes[sm].indexStart, il = subMeshes[sm].indexCount + subMeshes[sm].indexStart; i < il; i += 3) {
  81125. vertices = [];
  81126. for (var j = 0; j < 3; j++) {
  81127. var sourceNormal = new BABYLON.Vector3(normals[indices[i + j] * 3], normals[indices[i + j] * 3 + 1], normals[indices[i + j] * 3 + 2]);
  81128. uv = new BABYLON.Vector2(uvs[indices[i + j] * 2], uvs[indices[i + j] * 2 + 1]);
  81129. var sourcePosition = new BABYLON.Vector3(positions[indices[i + j] * 3], positions[indices[i + j] * 3 + 1], positions[indices[i + j] * 3 + 2]);
  81130. position = BABYLON.Vector3.TransformCoordinates(sourcePosition, matrix);
  81131. normal = BABYLON.Vector3.TransformNormal(sourceNormal, matrix);
  81132. vertex = new Vertex(position, normal, uv);
  81133. vertices.push(vertex);
  81134. }
  81135. polygon = new Polygon(vertices, { subMeshId: sm, meshId: currentCSGMeshId, materialIndex: subMeshes[sm].materialIndex });
  81136. // To handle the case of degenerated triangle
  81137. // polygon.plane == null <=> the polygon does not represent 1 single plane <=> the triangle is degenerated
  81138. if (polygon.plane)
  81139. polygons.push(polygon);
  81140. }
  81141. }
  81142. var csg = CSG.FromPolygons(polygons);
  81143. csg.matrix = matrix;
  81144. csg.position = meshPosition;
  81145. csg.rotation = meshRotation;
  81146. csg.scaling = meshScaling;
  81147. csg.rotationQuaternion = meshRotationQuaternion;
  81148. currentCSGMeshId++;
  81149. return csg;
  81150. };
  81151. // Construct a BABYLON.CSG solid from a list of `BABYLON.CSG.Polygon` instances.
  81152. CSG.FromPolygons = function (polygons) {
  81153. var csg = new CSG();
  81154. csg.polygons = polygons;
  81155. return csg;
  81156. };
  81157. CSG.prototype.clone = function () {
  81158. var csg = new CSG();
  81159. csg.polygons = this.polygons.map(function (p) { return p.clone(); });
  81160. csg.copyTransformAttributes(this);
  81161. return csg;
  81162. };
  81163. CSG.prototype.union = function (csg) {
  81164. var a = new Node(this.clone().polygons);
  81165. var b = new Node(csg.clone().polygons);
  81166. a.clipTo(b);
  81167. b.clipTo(a);
  81168. b.invert();
  81169. b.clipTo(a);
  81170. b.invert();
  81171. a.build(b.allPolygons());
  81172. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  81173. };
  81174. CSG.prototype.unionInPlace = function (csg) {
  81175. var a = new Node(this.polygons);
  81176. var b = new Node(csg.polygons);
  81177. a.clipTo(b);
  81178. b.clipTo(a);
  81179. b.invert();
  81180. b.clipTo(a);
  81181. b.invert();
  81182. a.build(b.allPolygons());
  81183. this.polygons = a.allPolygons();
  81184. };
  81185. CSG.prototype.subtract = function (csg) {
  81186. var a = new Node(this.clone().polygons);
  81187. var b = new Node(csg.clone().polygons);
  81188. a.invert();
  81189. a.clipTo(b);
  81190. b.clipTo(a);
  81191. b.invert();
  81192. b.clipTo(a);
  81193. b.invert();
  81194. a.build(b.allPolygons());
  81195. a.invert();
  81196. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  81197. };
  81198. CSG.prototype.subtractInPlace = function (csg) {
  81199. var a = new Node(this.polygons);
  81200. var b = new Node(csg.polygons);
  81201. a.invert();
  81202. a.clipTo(b);
  81203. b.clipTo(a);
  81204. b.invert();
  81205. b.clipTo(a);
  81206. b.invert();
  81207. a.build(b.allPolygons());
  81208. a.invert();
  81209. this.polygons = a.allPolygons();
  81210. };
  81211. CSG.prototype.intersect = function (csg) {
  81212. var a = new Node(this.clone().polygons);
  81213. var b = new Node(csg.clone().polygons);
  81214. a.invert();
  81215. b.clipTo(a);
  81216. b.invert();
  81217. a.clipTo(b);
  81218. b.clipTo(a);
  81219. a.build(b.allPolygons());
  81220. a.invert();
  81221. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  81222. };
  81223. CSG.prototype.intersectInPlace = function (csg) {
  81224. var a = new Node(this.polygons);
  81225. var b = new Node(csg.polygons);
  81226. a.invert();
  81227. b.clipTo(a);
  81228. b.invert();
  81229. a.clipTo(b);
  81230. b.clipTo(a);
  81231. a.build(b.allPolygons());
  81232. a.invert();
  81233. this.polygons = a.allPolygons();
  81234. };
  81235. // Return a new BABYLON.CSG solid with solid and empty space switched. This solid is
  81236. // not modified.
  81237. CSG.prototype.inverse = function () {
  81238. var csg = this.clone();
  81239. csg.inverseInPlace();
  81240. return csg;
  81241. };
  81242. CSG.prototype.inverseInPlace = function () {
  81243. this.polygons.map(function (p) { p.flip(); });
  81244. };
  81245. // This is used to keep meshes transformations so they can be restored
  81246. // when we build back a Babylon Mesh
  81247. // NB : All CSG operations are performed in world coordinates
  81248. CSG.prototype.copyTransformAttributes = function (csg) {
  81249. this.matrix = csg.matrix;
  81250. this.position = csg.position;
  81251. this.rotation = csg.rotation;
  81252. this.scaling = csg.scaling;
  81253. this.rotationQuaternion = csg.rotationQuaternion;
  81254. return this;
  81255. };
  81256. // Build Raw mesh from CSG
  81257. // Coordinates here are in world space
  81258. CSG.prototype.buildMeshGeometry = function (name, scene, keepSubMeshes) {
  81259. var matrix = this.matrix.clone();
  81260. matrix.invert();
  81261. 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;
  81262. if (keepSubMeshes) {
  81263. // Sort Polygons, since subMeshes are indices range
  81264. polygons.sort(function (a, b) {
  81265. if (a.shared.meshId === b.shared.meshId) {
  81266. return a.shared.subMeshId - b.shared.subMeshId;
  81267. }
  81268. else {
  81269. return a.shared.meshId - b.shared.meshId;
  81270. }
  81271. });
  81272. }
  81273. for (var i = 0, il = polygons.length; i < il; i++) {
  81274. polygon = polygons[i];
  81275. // Building SubMeshes
  81276. if (!subMesh_dict[polygon.shared.meshId]) {
  81277. subMesh_dict[polygon.shared.meshId] = {};
  81278. }
  81279. if (!subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId]) {
  81280. subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId] = {
  81281. indexStart: +Infinity,
  81282. indexEnd: -Infinity,
  81283. materialIndex: polygon.shared.materialIndex
  81284. };
  81285. }
  81286. subMesh_obj = subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId];
  81287. for (var j = 2, jl = polygon.vertices.length; j < jl; j++) {
  81288. polygonIndices[0] = 0;
  81289. polygonIndices[1] = j - 1;
  81290. polygonIndices[2] = j;
  81291. for (var k = 0; k < 3; k++) {
  81292. vertex.copyFrom(polygon.vertices[polygonIndices[k]].pos);
  81293. normal.copyFrom(polygon.vertices[polygonIndices[k]].normal);
  81294. uv.copyFrom(polygon.vertices[polygonIndices[k]].uv);
  81295. var localVertex = BABYLON.Vector3.TransformCoordinates(vertex, matrix);
  81296. var localNormal = BABYLON.Vector3.TransformNormal(normal, matrix);
  81297. vertex_idx = vertice_dict[localVertex.x + ',' + localVertex.y + ',' + localVertex.z];
  81298. // Check if 2 points can be merged
  81299. if (!(typeof vertex_idx !== 'undefined' &&
  81300. normals[vertex_idx * 3] === localNormal.x &&
  81301. normals[vertex_idx * 3 + 1] === localNormal.y &&
  81302. normals[vertex_idx * 3 + 2] === localNormal.z &&
  81303. uvs[vertex_idx * 2] === uv.x &&
  81304. uvs[vertex_idx * 2 + 1] === uv.y)) {
  81305. vertices.push(localVertex.x, localVertex.y, localVertex.z);
  81306. uvs.push(uv.x, uv.y);
  81307. normals.push(normal.x, normal.y, normal.z);
  81308. vertex_idx = vertice_dict[localVertex.x + ',' + localVertex.y + ',' + localVertex.z] = (vertices.length / 3) - 1;
  81309. }
  81310. indices.push(vertex_idx);
  81311. subMesh_obj.indexStart = Math.min(currentIndex, subMesh_obj.indexStart);
  81312. subMesh_obj.indexEnd = Math.max(currentIndex, subMesh_obj.indexEnd);
  81313. currentIndex++;
  81314. }
  81315. }
  81316. }
  81317. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, vertices);
  81318. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals);
  81319. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, uvs);
  81320. mesh.setIndices(indices, null);
  81321. if (keepSubMeshes) {
  81322. // We offset the materialIndex by the previous number of materials in the CSG mixed meshes
  81323. var materialIndexOffset = 0, materialMaxIndex;
  81324. mesh.subMeshes = new Array();
  81325. for (var m in subMesh_dict) {
  81326. materialMaxIndex = -1;
  81327. for (var sm in subMesh_dict[m]) {
  81328. subMesh_obj = subMesh_dict[m][sm];
  81329. BABYLON.SubMesh.CreateFromIndices(subMesh_obj.materialIndex + materialIndexOffset, subMesh_obj.indexStart, subMesh_obj.indexEnd - subMesh_obj.indexStart + 1, mesh);
  81330. materialMaxIndex = Math.max(subMesh_obj.materialIndex, materialMaxIndex);
  81331. }
  81332. materialIndexOffset += ++materialMaxIndex;
  81333. }
  81334. }
  81335. return mesh;
  81336. };
  81337. // Build Mesh from CSG taking material and transforms into account
  81338. CSG.prototype.toMesh = function (name, material, scene, keepSubMeshes) {
  81339. var mesh = this.buildMeshGeometry(name, scene, keepSubMeshes);
  81340. mesh.material = material;
  81341. mesh.position.copyFrom(this.position);
  81342. mesh.rotation.copyFrom(this.rotation);
  81343. if (this.rotationQuaternion) {
  81344. mesh.rotationQuaternion = this.rotationQuaternion.clone();
  81345. }
  81346. mesh.scaling.copyFrom(this.scaling);
  81347. mesh.computeWorldMatrix(true);
  81348. return mesh;
  81349. };
  81350. return CSG;
  81351. }());
  81352. BABYLON.CSG = CSG;
  81353. })(BABYLON || (BABYLON = {}));
  81354. //# sourceMappingURL=babylon.csg.js.map
  81355. var BABYLON;
  81356. (function (BABYLON) {
  81357. var LensFlare = /** @class */ (function () {
  81358. function LensFlare(size, position, color, imgUrl, system) {
  81359. this.size = size;
  81360. this.position = position;
  81361. this.alphaMode = BABYLON.Engine.ALPHA_ONEONE;
  81362. this.color = color || new BABYLON.Color3(1, 1, 1);
  81363. this.texture = imgUrl ? new BABYLON.Texture(imgUrl, system.getScene(), true) : null;
  81364. this._system = system;
  81365. system.lensFlares.push(this);
  81366. }
  81367. LensFlare.AddFlare = function (size, position, color, imgUrl, system) {
  81368. return new LensFlare(size, position, color, imgUrl, system);
  81369. };
  81370. LensFlare.prototype.dispose = function () {
  81371. if (this.texture) {
  81372. this.texture.dispose();
  81373. }
  81374. // Remove from scene
  81375. var index = this._system.lensFlares.indexOf(this);
  81376. this._system.lensFlares.splice(index, 1);
  81377. };
  81378. ;
  81379. return LensFlare;
  81380. }());
  81381. BABYLON.LensFlare = LensFlare;
  81382. })(BABYLON || (BABYLON = {}));
  81383. //# sourceMappingURL=babylon.lensFlare.js.map
  81384. var BABYLON;
  81385. (function (BABYLON) {
  81386. var LensFlareSystem = /** @class */ (function () {
  81387. function LensFlareSystem(name, emitter, scene) {
  81388. this.name = name;
  81389. this.lensFlares = new Array();
  81390. this.borderLimit = 300;
  81391. this.viewportBorder = 0;
  81392. this.layerMask = 0x0FFFFFFF;
  81393. this._vertexBuffers = {};
  81394. this._isEnabled = true;
  81395. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  81396. this._emitter = emitter;
  81397. this.id = name;
  81398. scene.lensFlareSystems.push(this);
  81399. this.meshesSelectionPredicate = function (m) { return (scene.activeCamera && m.material && m.isVisible && m.isEnabled() && m.isBlocker && ((m.layerMask & scene.activeCamera.layerMask) != 0)); };
  81400. var engine = scene.getEngine();
  81401. // VBO
  81402. var vertices = [];
  81403. vertices.push(1, 1);
  81404. vertices.push(-1, 1);
  81405. vertices.push(-1, -1);
  81406. vertices.push(1, -1);
  81407. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(engine, vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  81408. // Indices
  81409. var indices = [];
  81410. indices.push(0);
  81411. indices.push(1);
  81412. indices.push(2);
  81413. indices.push(0);
  81414. indices.push(2);
  81415. indices.push(3);
  81416. this._indexBuffer = engine.createIndexBuffer(indices);
  81417. // Effects
  81418. this._effect = engine.createEffect("lensFlare", [BABYLON.VertexBuffer.PositionKind], ["color", "viewportMatrix"], ["textureSampler"], "");
  81419. }
  81420. Object.defineProperty(LensFlareSystem.prototype, "isEnabled", {
  81421. get: function () {
  81422. return this._isEnabled;
  81423. },
  81424. set: function (value) {
  81425. this._isEnabled = value;
  81426. },
  81427. enumerable: true,
  81428. configurable: true
  81429. });
  81430. LensFlareSystem.prototype.getScene = function () {
  81431. return this._scene;
  81432. };
  81433. LensFlareSystem.prototype.getEmitter = function () {
  81434. return this._emitter;
  81435. };
  81436. LensFlareSystem.prototype.setEmitter = function (newEmitter) {
  81437. this._emitter = newEmitter;
  81438. };
  81439. LensFlareSystem.prototype.getEmitterPosition = function () {
  81440. return this._emitter.getAbsolutePosition ? this._emitter.getAbsolutePosition() : this._emitter.position;
  81441. };
  81442. LensFlareSystem.prototype.computeEffectivePosition = function (globalViewport) {
  81443. var position = this.getEmitterPosition();
  81444. position = BABYLON.Vector3.Project(position, BABYLON.Matrix.Identity(), this._scene.getTransformMatrix(), globalViewport);
  81445. this._positionX = position.x;
  81446. this._positionY = position.y;
  81447. position = BABYLON.Vector3.TransformCoordinates(this.getEmitterPosition(), this._scene.getViewMatrix());
  81448. if (this.viewportBorder > 0) {
  81449. globalViewport.x -= this.viewportBorder;
  81450. globalViewport.y -= this.viewportBorder;
  81451. globalViewport.width += this.viewportBorder * 2;
  81452. globalViewport.height += this.viewportBorder * 2;
  81453. position.x += this.viewportBorder;
  81454. position.y += this.viewportBorder;
  81455. this._positionX += this.viewportBorder;
  81456. this._positionY += this.viewportBorder;
  81457. }
  81458. if (position.z > 0) {
  81459. if ((this._positionX > globalViewport.x) && (this._positionX < globalViewport.x + globalViewport.width)) {
  81460. if ((this._positionY > globalViewport.y) && (this._positionY < globalViewport.y + globalViewport.height))
  81461. return true;
  81462. }
  81463. return true;
  81464. }
  81465. return false;
  81466. };
  81467. LensFlareSystem.prototype._isVisible = function () {
  81468. if (!this._isEnabled || !this._scene.activeCamera) {
  81469. return false;
  81470. }
  81471. var emitterPosition = this.getEmitterPosition();
  81472. var direction = emitterPosition.subtract(this._scene.activeCamera.globalPosition);
  81473. var distance = direction.length();
  81474. direction.normalize();
  81475. var ray = new BABYLON.Ray(this._scene.activeCamera.globalPosition, direction);
  81476. var pickInfo = this._scene.pickWithRay(ray, this.meshesSelectionPredicate, true);
  81477. return !pickInfo || !pickInfo.hit || pickInfo.distance > distance;
  81478. };
  81479. LensFlareSystem.prototype.render = function () {
  81480. if (!this._effect.isReady() || !this._scene.activeCamera)
  81481. return false;
  81482. var engine = this._scene.getEngine();
  81483. var viewport = this._scene.activeCamera.viewport;
  81484. var globalViewport = viewport.toGlobal(engine.getRenderWidth(true), engine.getRenderHeight(true));
  81485. // Position
  81486. if (!this.computeEffectivePosition(globalViewport)) {
  81487. return false;
  81488. }
  81489. // Visibility
  81490. if (!this._isVisible()) {
  81491. return false;
  81492. }
  81493. // Intensity
  81494. var awayX;
  81495. var awayY;
  81496. if (this._positionX < this.borderLimit + globalViewport.x) {
  81497. awayX = this.borderLimit + globalViewport.x - this._positionX;
  81498. }
  81499. else if (this._positionX > globalViewport.x + globalViewport.width - this.borderLimit) {
  81500. awayX = this._positionX - globalViewport.x - globalViewport.width + this.borderLimit;
  81501. }
  81502. else {
  81503. awayX = 0;
  81504. }
  81505. if (this._positionY < this.borderLimit + globalViewport.y) {
  81506. awayY = this.borderLimit + globalViewport.y - this._positionY;
  81507. }
  81508. else if (this._positionY > globalViewport.y + globalViewport.height - this.borderLimit) {
  81509. awayY = this._positionY - globalViewport.y - globalViewport.height + this.borderLimit;
  81510. }
  81511. else {
  81512. awayY = 0;
  81513. }
  81514. var away = (awayX > awayY) ? awayX : awayY;
  81515. away -= this.viewportBorder;
  81516. if (away > this.borderLimit) {
  81517. away = this.borderLimit;
  81518. }
  81519. var intensity = 1.0 - (away / this.borderLimit);
  81520. if (intensity < 0) {
  81521. return false;
  81522. }
  81523. if (intensity > 1.0) {
  81524. intensity = 1.0;
  81525. }
  81526. if (this.viewportBorder > 0) {
  81527. globalViewport.x += this.viewportBorder;
  81528. globalViewport.y += this.viewportBorder;
  81529. globalViewport.width -= this.viewportBorder * 2;
  81530. globalViewport.height -= this.viewportBorder * 2;
  81531. this._positionX -= this.viewportBorder;
  81532. this._positionY -= this.viewportBorder;
  81533. }
  81534. // Position
  81535. var centerX = globalViewport.x + globalViewport.width / 2;
  81536. var centerY = globalViewport.y + globalViewport.height / 2;
  81537. var distX = centerX - this._positionX;
  81538. var distY = centerY - this._positionY;
  81539. // Effects
  81540. engine.enableEffect(this._effect);
  81541. engine.setState(false);
  81542. engine.setDepthBuffer(false);
  81543. // VBOs
  81544. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._effect);
  81545. // Flares
  81546. for (var index = 0; index < this.lensFlares.length; index++) {
  81547. var flare = this.lensFlares[index];
  81548. engine.setAlphaMode(flare.alphaMode);
  81549. var x = centerX - (distX * flare.position);
  81550. var y = centerY - (distY * flare.position);
  81551. var cw = flare.size;
  81552. var ch = flare.size * engine.getAspectRatio(this._scene.activeCamera, true);
  81553. var cx = 2 * (x / (globalViewport.width + globalViewport.x * 2)) - 1.0;
  81554. var cy = 1.0 - 2 * (y / (globalViewport.height + globalViewport.y * 2));
  81555. var viewportMatrix = BABYLON.Matrix.FromValues(cw / 2, 0, 0, 0, 0, ch / 2, 0, 0, 0, 0, 1, 0, cx, cy, 0, 1);
  81556. this._effect.setMatrix("viewportMatrix", viewportMatrix);
  81557. // Texture
  81558. this._effect.setTexture("textureSampler", flare.texture);
  81559. // Color
  81560. this._effect.setFloat4("color", flare.color.r * intensity, flare.color.g * intensity, flare.color.b * intensity, 1.0);
  81561. // Draw order
  81562. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  81563. }
  81564. engine.setDepthBuffer(true);
  81565. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  81566. return true;
  81567. };
  81568. LensFlareSystem.prototype.dispose = function () {
  81569. var vertexBuffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  81570. if (vertexBuffer) {
  81571. vertexBuffer.dispose();
  81572. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  81573. }
  81574. if (this._indexBuffer) {
  81575. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  81576. this._indexBuffer = null;
  81577. }
  81578. while (this.lensFlares.length) {
  81579. this.lensFlares[0].dispose();
  81580. }
  81581. // Remove from scene
  81582. var index = this._scene.lensFlareSystems.indexOf(this);
  81583. this._scene.lensFlareSystems.splice(index, 1);
  81584. };
  81585. LensFlareSystem.Parse = function (parsedLensFlareSystem, scene, rootUrl) {
  81586. var emitter = scene.getLastEntryByID(parsedLensFlareSystem.emitterId);
  81587. var name = parsedLensFlareSystem.name || "lensFlareSystem#" + parsedLensFlareSystem.emitterId;
  81588. var lensFlareSystem = new LensFlareSystem(name, emitter, scene);
  81589. lensFlareSystem.id = parsedLensFlareSystem.id || name;
  81590. lensFlareSystem.borderLimit = parsedLensFlareSystem.borderLimit;
  81591. for (var index = 0; index < parsedLensFlareSystem.flares.length; index++) {
  81592. var parsedFlare = parsedLensFlareSystem.flares[index];
  81593. BABYLON.LensFlare.AddFlare(parsedFlare.size, parsedFlare.position, BABYLON.Color3.FromArray(parsedFlare.color), parsedFlare.textureName ? rootUrl + parsedFlare.textureName : "", lensFlareSystem);
  81594. }
  81595. return lensFlareSystem;
  81596. };
  81597. LensFlareSystem.prototype.serialize = function () {
  81598. var serializationObject = {};
  81599. serializationObject.id = this.id;
  81600. serializationObject.name = this.name;
  81601. serializationObject.emitterId = this.getEmitter().id;
  81602. serializationObject.borderLimit = this.borderLimit;
  81603. serializationObject.flares = [];
  81604. for (var index = 0; index < this.lensFlares.length; index++) {
  81605. var flare = this.lensFlares[index];
  81606. serializationObject.flares.push({
  81607. size: flare.size,
  81608. position: flare.position,
  81609. color: flare.color.asArray(),
  81610. textureName: BABYLON.Tools.GetFilename(flare.texture ? flare.texture.name : "")
  81611. });
  81612. }
  81613. return serializationObject;
  81614. };
  81615. return LensFlareSystem;
  81616. }());
  81617. BABYLON.LensFlareSystem = LensFlareSystem;
  81618. })(BABYLON || (BABYLON = {}));
  81619. //# sourceMappingURL=babylon.lensFlareSystem.js.map
  81620. var BABYLON;
  81621. (function (BABYLON) {
  81622. /**
  81623. * This is a holder class for the physics joint created by the physics plugin.
  81624. * It holds a set of functions to control the underlying joint.
  81625. */
  81626. var PhysicsJoint = /** @class */ (function () {
  81627. function PhysicsJoint(type, jointData) {
  81628. this.type = type;
  81629. this.jointData = jointData;
  81630. jointData.nativeParams = jointData.nativeParams || {};
  81631. }
  81632. Object.defineProperty(PhysicsJoint.prototype, "physicsJoint", {
  81633. get: function () {
  81634. return this._physicsJoint;
  81635. },
  81636. set: function (newJoint) {
  81637. if (this._physicsJoint) {
  81638. //remove from the wolrd
  81639. }
  81640. this._physicsJoint = newJoint;
  81641. },
  81642. enumerable: true,
  81643. configurable: true
  81644. });
  81645. Object.defineProperty(PhysicsJoint.prototype, "physicsPlugin", {
  81646. set: function (physicsPlugin) {
  81647. this._physicsPlugin = physicsPlugin;
  81648. },
  81649. enumerable: true,
  81650. configurable: true
  81651. });
  81652. /**
  81653. * Execute a function that is physics-plugin specific.
  81654. * @param {Function} func the function that will be executed.
  81655. * It accepts two parameters: the physics world and the physics joint.
  81656. */
  81657. PhysicsJoint.prototype.executeNativeFunction = function (func) {
  81658. func(this._physicsPlugin.world, this._physicsJoint);
  81659. };
  81660. //TODO check if the native joints are the same
  81661. //Joint Types
  81662. PhysicsJoint.DistanceJoint = 0;
  81663. PhysicsJoint.HingeJoint = 1;
  81664. PhysicsJoint.BallAndSocketJoint = 2;
  81665. PhysicsJoint.WheelJoint = 3;
  81666. PhysicsJoint.SliderJoint = 4;
  81667. //OIMO
  81668. PhysicsJoint.PrismaticJoint = 5;
  81669. //ENERGY FTW! (compare with this - http://ode-wiki.org/wiki/index.php?title=Manual:_Joint_Types_and_Functions)
  81670. PhysicsJoint.UniversalJoint = 6;
  81671. PhysicsJoint.Hinge2Joint = PhysicsJoint.WheelJoint;
  81672. //Cannon
  81673. //Similar to a Ball-Joint. Different in params
  81674. PhysicsJoint.PointToPointJoint = 8;
  81675. //Cannon only at the moment
  81676. PhysicsJoint.SpringJoint = 9;
  81677. PhysicsJoint.LockJoint = 10;
  81678. return PhysicsJoint;
  81679. }());
  81680. BABYLON.PhysicsJoint = PhysicsJoint;
  81681. /**
  81682. * A class representing a physics distance joint.
  81683. */
  81684. var DistanceJoint = /** @class */ (function (_super) {
  81685. __extends(DistanceJoint, _super);
  81686. function DistanceJoint(jointData) {
  81687. return _super.call(this, PhysicsJoint.DistanceJoint, jointData) || this;
  81688. }
  81689. /**
  81690. * Update the predefined distance.
  81691. */
  81692. DistanceJoint.prototype.updateDistance = function (maxDistance, minDistance) {
  81693. this._physicsPlugin.updateDistanceJoint(this, maxDistance, minDistance);
  81694. };
  81695. return DistanceJoint;
  81696. }(PhysicsJoint));
  81697. BABYLON.DistanceJoint = DistanceJoint;
  81698. var MotorEnabledJoint = /** @class */ (function (_super) {
  81699. __extends(MotorEnabledJoint, _super);
  81700. function MotorEnabledJoint(type, jointData) {
  81701. return _super.call(this, type, jointData) || this;
  81702. }
  81703. /**
  81704. * Set the motor values.
  81705. * Attention, this function is plugin specific. Engines won't react 100% the same.
  81706. * @param {number} force the force to apply
  81707. * @param {number} maxForce max force for this motor.
  81708. */
  81709. MotorEnabledJoint.prototype.setMotor = function (force, maxForce) {
  81710. this._physicsPlugin.setMotor(this, force || 0, maxForce);
  81711. };
  81712. /**
  81713. * Set the motor's limits.
  81714. * Attention, this function is plugin specific. Engines won't react 100% the same.
  81715. */
  81716. MotorEnabledJoint.prototype.setLimit = function (upperLimit, lowerLimit) {
  81717. this._physicsPlugin.setLimit(this, upperLimit, lowerLimit);
  81718. };
  81719. return MotorEnabledJoint;
  81720. }(PhysicsJoint));
  81721. BABYLON.MotorEnabledJoint = MotorEnabledJoint;
  81722. /**
  81723. * This class represents a single hinge physics joint
  81724. */
  81725. var HingeJoint = /** @class */ (function (_super) {
  81726. __extends(HingeJoint, _super);
  81727. function HingeJoint(jointData) {
  81728. return _super.call(this, PhysicsJoint.HingeJoint, jointData) || this;
  81729. }
  81730. /**
  81731. * Set the motor values.
  81732. * Attention, this function is plugin specific. Engines won't react 100% the same.
  81733. * @param {number} force the force to apply
  81734. * @param {number} maxForce max force for this motor.
  81735. */
  81736. HingeJoint.prototype.setMotor = function (force, maxForce) {
  81737. this._physicsPlugin.setMotor(this, force || 0, maxForce);
  81738. };
  81739. /**
  81740. * Set the motor's limits.
  81741. * Attention, this function is plugin specific. Engines won't react 100% the same.
  81742. */
  81743. HingeJoint.prototype.setLimit = function (upperLimit, lowerLimit) {
  81744. this._physicsPlugin.setLimit(this, upperLimit, lowerLimit);
  81745. };
  81746. return HingeJoint;
  81747. }(MotorEnabledJoint));
  81748. BABYLON.HingeJoint = HingeJoint;
  81749. /**
  81750. * This class represents a dual hinge physics joint (same as wheel joint)
  81751. */
  81752. var Hinge2Joint = /** @class */ (function (_super) {
  81753. __extends(Hinge2Joint, _super);
  81754. function Hinge2Joint(jointData) {
  81755. return _super.call(this, PhysicsJoint.Hinge2Joint, jointData) || this;
  81756. }
  81757. /**
  81758. * Set the motor values.
  81759. * Attention, this function is plugin specific. Engines won't react 100% the same.
  81760. * @param {number} force the force to apply
  81761. * @param {number} maxForce max force for this motor.
  81762. * @param {motorIndex} the motor's index, 0 or 1.
  81763. */
  81764. Hinge2Joint.prototype.setMotor = function (force, maxForce, motorIndex) {
  81765. if (motorIndex === void 0) { motorIndex = 0; }
  81766. this._physicsPlugin.setMotor(this, force || 0, maxForce, motorIndex);
  81767. };
  81768. /**
  81769. * Set the motor limits.
  81770. * Attention, this function is plugin specific. Engines won't react 100% the same.
  81771. * @param {number} upperLimit the upper limit
  81772. * @param {number} lowerLimit lower limit
  81773. * @param {motorIndex} the motor's index, 0 or 1.
  81774. */
  81775. Hinge2Joint.prototype.setLimit = function (upperLimit, lowerLimit, motorIndex) {
  81776. if (motorIndex === void 0) { motorIndex = 0; }
  81777. this._physicsPlugin.setLimit(this, upperLimit, lowerLimit, motorIndex);
  81778. };
  81779. return Hinge2Joint;
  81780. }(MotorEnabledJoint));
  81781. BABYLON.Hinge2Joint = Hinge2Joint;
  81782. })(BABYLON || (BABYLON = {}));
  81783. //# sourceMappingURL=babylon.physicsJoint.js.map
  81784. var BABYLON;
  81785. (function (BABYLON) {
  81786. var PhysicsImpostor = /** @class */ (function () {
  81787. function PhysicsImpostor(object, type, _options, _scene) {
  81788. if (_options === void 0) { _options = { mass: 0 }; }
  81789. var _this = this;
  81790. this.object = object;
  81791. this.type = type;
  81792. this._options = _options;
  81793. this._scene = _scene;
  81794. this._bodyUpdateRequired = false;
  81795. this._onBeforePhysicsStepCallbacks = new Array();
  81796. this._onAfterPhysicsStepCallbacks = new Array();
  81797. this._onPhysicsCollideCallbacks = [];
  81798. this._deltaPosition = BABYLON.Vector3.Zero();
  81799. this._isDisposed = false;
  81800. //temp variables for parent rotation calculations
  81801. //private _mats: Array<Matrix> = [new Matrix(), new Matrix()];
  81802. this._tmpQuat = new BABYLON.Quaternion();
  81803. this._tmpQuat2 = new BABYLON.Quaternion();
  81804. /**
  81805. * this function is executed by the physics engine.
  81806. */
  81807. this.beforeStep = function () {
  81808. if (!_this._physicsEngine) {
  81809. return;
  81810. }
  81811. _this.object.translate(_this._deltaPosition, -1);
  81812. _this._deltaRotationConjugated && _this.object.rotationQuaternion && _this.object.rotationQuaternion.multiplyToRef(_this._deltaRotationConjugated, _this.object.rotationQuaternion);
  81813. _this.object.computeWorldMatrix(false);
  81814. if (_this.object.parent && _this.object.rotationQuaternion) {
  81815. _this.getParentsRotation();
  81816. _this._tmpQuat.multiplyToRef(_this.object.rotationQuaternion, _this._tmpQuat);
  81817. }
  81818. else {
  81819. _this._tmpQuat.copyFrom(_this.object.rotationQuaternion || new BABYLON.Quaternion());
  81820. }
  81821. if (!_this._options.disableBidirectionalTransformation) {
  81822. _this.object.rotationQuaternion && _this._physicsEngine.getPhysicsPlugin().setPhysicsBodyTransformation(_this, /*bInfo.boundingBox.centerWorld*/ _this.object.getAbsolutePivotPoint(), _this._tmpQuat);
  81823. }
  81824. _this._onBeforePhysicsStepCallbacks.forEach(function (func) {
  81825. func(_this);
  81826. });
  81827. };
  81828. /**
  81829. * this function is executed by the physics engine.
  81830. */
  81831. this.afterStep = function () {
  81832. if (!_this._physicsEngine) {
  81833. return;
  81834. }
  81835. _this._onAfterPhysicsStepCallbacks.forEach(function (func) {
  81836. func(_this);
  81837. });
  81838. _this._physicsEngine.getPhysicsPlugin().setTransformationFromPhysicsBody(_this);
  81839. // object has now its world rotation. needs to be converted to local.
  81840. if (_this.object.parent && _this.object.rotationQuaternion) {
  81841. _this.getParentsRotation();
  81842. _this._tmpQuat.conjugateInPlace();
  81843. _this._tmpQuat.multiplyToRef(_this.object.rotationQuaternion, _this.object.rotationQuaternion);
  81844. }
  81845. // take the position set and make it the absolute position of this object.
  81846. _this.object.setAbsolutePosition(_this.object.position);
  81847. _this._deltaRotation && _this.object.rotationQuaternion && _this.object.rotationQuaternion.multiplyToRef(_this._deltaRotation, _this.object.rotationQuaternion);
  81848. _this.object.translate(_this._deltaPosition, 1);
  81849. };
  81850. /**
  81851. * Legacy collision detection event support
  81852. */
  81853. this.onCollideEvent = null;
  81854. //event and body object due to cannon's event-based architecture.
  81855. this.onCollide = function (e) {
  81856. if (!_this._onPhysicsCollideCallbacks.length && !_this.onCollideEvent) {
  81857. return;
  81858. }
  81859. if (!_this._physicsEngine) {
  81860. return;
  81861. }
  81862. var otherImpostor = _this._physicsEngine.getImpostorWithPhysicsBody(e.body);
  81863. if (otherImpostor) {
  81864. // Legacy collision detection event support
  81865. if (_this.onCollideEvent) {
  81866. _this.onCollideEvent(_this, otherImpostor);
  81867. }
  81868. _this._onPhysicsCollideCallbacks.filter(function (obj) {
  81869. return obj.otherImpostors.indexOf(otherImpostor) !== -1;
  81870. }).forEach(function (obj) {
  81871. obj.callback(_this, otherImpostor);
  81872. });
  81873. }
  81874. };
  81875. //sanity check!
  81876. if (!this.object) {
  81877. BABYLON.Tools.Error("No object was provided. A physics object is obligatory");
  81878. return;
  81879. }
  81880. //legacy support for old syntax.
  81881. if (!this._scene && object.getScene) {
  81882. this._scene = object.getScene();
  81883. }
  81884. if (!this._scene) {
  81885. return;
  81886. }
  81887. this._physicsEngine = this._scene.getPhysicsEngine();
  81888. if (!this._physicsEngine) {
  81889. BABYLON.Tools.Error("Physics not enabled. Please use scene.enablePhysics(...) before creating impostors.");
  81890. }
  81891. else {
  81892. //set the object's quaternion, if not set
  81893. if (!this.object.rotationQuaternion) {
  81894. if (this.object.rotation) {
  81895. this.object.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(this.object.rotation.y, this.object.rotation.x, this.object.rotation.z);
  81896. }
  81897. else {
  81898. this.object.rotationQuaternion = new BABYLON.Quaternion();
  81899. }
  81900. }
  81901. //default options params
  81902. this._options.mass = (_options.mass === void 0) ? 0 : _options.mass;
  81903. this._options.friction = (_options.friction === void 0) ? 0.2 : _options.friction;
  81904. this._options.restitution = (_options.restitution === void 0) ? 0.2 : _options.restitution;
  81905. this._joints = [];
  81906. //If the mesh has a parent, don't initialize the physicsBody. Instead wait for the parent to do that.
  81907. if (!this.object.parent || this._options.ignoreParent) {
  81908. this._init();
  81909. }
  81910. else if (this.object.parent.physicsImpostor) {
  81911. BABYLON.Tools.Warn("You must affect impostors to children before affecting impostor to parent.");
  81912. }
  81913. }
  81914. }
  81915. Object.defineProperty(PhysicsImpostor.prototype, "isDisposed", {
  81916. get: function () {
  81917. return this._isDisposed;
  81918. },
  81919. enumerable: true,
  81920. configurable: true
  81921. });
  81922. Object.defineProperty(PhysicsImpostor.prototype, "mass", {
  81923. get: function () {
  81924. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getBodyMass(this) : 0;
  81925. },
  81926. set: function (value) {
  81927. this.setMass(value);
  81928. },
  81929. enumerable: true,
  81930. configurable: true
  81931. });
  81932. Object.defineProperty(PhysicsImpostor.prototype, "friction", {
  81933. get: function () {
  81934. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getBodyFriction(this) : 0;
  81935. },
  81936. set: function (value) {
  81937. if (!this._physicsEngine) {
  81938. return;
  81939. }
  81940. this._physicsEngine.getPhysicsPlugin().setBodyFriction(this, value);
  81941. },
  81942. enumerable: true,
  81943. configurable: true
  81944. });
  81945. Object.defineProperty(PhysicsImpostor.prototype, "restitution", {
  81946. get: function () {
  81947. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getBodyRestitution(this) : 0;
  81948. },
  81949. set: function (value) {
  81950. if (!this._physicsEngine) {
  81951. return;
  81952. }
  81953. this._physicsEngine.getPhysicsPlugin().setBodyRestitution(this, value);
  81954. },
  81955. enumerable: true,
  81956. configurable: true
  81957. });
  81958. /**
  81959. * This function will completly initialize this impostor.
  81960. * It will create a new body - but only if this mesh has no parent.
  81961. * If it has, this impostor will not be used other than to define the impostor
  81962. * of the child mesh.
  81963. */
  81964. PhysicsImpostor.prototype._init = function () {
  81965. if (!this._physicsEngine) {
  81966. return;
  81967. }
  81968. this._physicsEngine.removeImpostor(this);
  81969. this.physicsBody = null;
  81970. this._parent = this._parent || this._getPhysicsParent();
  81971. if (!this._isDisposed && (!this.parent || this._options.ignoreParent)) {
  81972. this._physicsEngine.addImpostor(this);
  81973. }
  81974. };
  81975. PhysicsImpostor.prototype._getPhysicsParent = function () {
  81976. if (this.object.parent instanceof BABYLON.AbstractMesh) {
  81977. var parentMesh = this.object.parent;
  81978. return parentMesh.physicsImpostor;
  81979. }
  81980. return null;
  81981. };
  81982. /**
  81983. * Should a new body be generated.
  81984. */
  81985. PhysicsImpostor.prototype.isBodyInitRequired = function () {
  81986. return this._bodyUpdateRequired || (!this._physicsBody && !this._parent);
  81987. };
  81988. PhysicsImpostor.prototype.setScalingUpdated = function (updated) {
  81989. this.forceUpdate();
  81990. };
  81991. /**
  81992. * Force a regeneration of this or the parent's impostor's body.
  81993. * Use under cautious - This will remove all joints already implemented.
  81994. */
  81995. PhysicsImpostor.prototype.forceUpdate = function () {
  81996. this._init();
  81997. if (this.parent && !this._options.ignoreParent) {
  81998. this.parent.forceUpdate();
  81999. }
  82000. };
  82001. Object.defineProperty(PhysicsImpostor.prototype, "physicsBody", {
  82002. /*public get mesh(): AbstractMesh {
  82003. return this._mesh;
  82004. }*/
  82005. /**
  82006. * Gets the body that holds this impostor. Either its own, or its parent.
  82007. */
  82008. get: function () {
  82009. return (this._parent && !this._options.ignoreParent) ? this._parent.physicsBody : this._physicsBody;
  82010. },
  82011. /**
  82012. * Set the physics body. Used mainly by the physics engine/plugin
  82013. */
  82014. set: function (physicsBody) {
  82015. if (this._physicsBody && this._physicsEngine) {
  82016. this._physicsEngine.getPhysicsPlugin().removePhysicsBody(this);
  82017. }
  82018. this._physicsBody = physicsBody;
  82019. this.resetUpdateFlags();
  82020. },
  82021. enumerable: true,
  82022. configurable: true
  82023. });
  82024. Object.defineProperty(PhysicsImpostor.prototype, "parent", {
  82025. get: function () {
  82026. return !this._options.ignoreParent && this._parent ? this._parent : null;
  82027. },
  82028. set: function (value) {
  82029. this._parent = value;
  82030. },
  82031. enumerable: true,
  82032. configurable: true
  82033. });
  82034. PhysicsImpostor.prototype.resetUpdateFlags = function () {
  82035. this._bodyUpdateRequired = false;
  82036. };
  82037. PhysicsImpostor.prototype.getObjectExtendSize = function () {
  82038. if (this.object.getBoundingInfo) {
  82039. var q = this.object.rotationQuaternion;
  82040. //reset rotation
  82041. this.object.rotationQuaternion = PhysicsImpostor.IDENTITY_QUATERNION;
  82042. //calculate the world matrix with no rotation
  82043. this.object.computeWorldMatrix && this.object.computeWorldMatrix(true);
  82044. var boundingInfo = this.object.getBoundingInfo();
  82045. var size = boundingInfo.boundingBox.extendSizeWorld.scale(2);
  82046. //bring back the rotation
  82047. this.object.rotationQuaternion = q;
  82048. //calculate the world matrix with the new rotation
  82049. this.object.computeWorldMatrix && this.object.computeWorldMatrix(true);
  82050. return size;
  82051. }
  82052. else {
  82053. return PhysicsImpostor.DEFAULT_OBJECT_SIZE;
  82054. }
  82055. };
  82056. PhysicsImpostor.prototype.getObjectCenter = function () {
  82057. if (this.object.getBoundingInfo) {
  82058. var boundingInfo = this.object.getBoundingInfo();
  82059. return boundingInfo.boundingBox.centerWorld;
  82060. }
  82061. else {
  82062. return this.object.position;
  82063. }
  82064. };
  82065. /**
  82066. * Get a specific parametes from the options parameter.
  82067. */
  82068. PhysicsImpostor.prototype.getParam = function (paramName) {
  82069. return this._options[paramName];
  82070. };
  82071. /**
  82072. * Sets a specific parameter in the options given to the physics plugin
  82073. */
  82074. PhysicsImpostor.prototype.setParam = function (paramName, value) {
  82075. this._options[paramName] = value;
  82076. this._bodyUpdateRequired = true;
  82077. };
  82078. /**
  82079. * Specifically change the body's mass option. Won't recreate the physics body object
  82080. */
  82081. PhysicsImpostor.prototype.setMass = function (mass) {
  82082. if (this.getParam("mass") !== mass) {
  82083. this.setParam("mass", mass);
  82084. }
  82085. if (this._physicsEngine) {
  82086. this._physicsEngine.getPhysicsPlugin().setBodyMass(this, mass);
  82087. }
  82088. };
  82089. PhysicsImpostor.prototype.getLinearVelocity = function () {
  82090. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getLinearVelocity(this) : BABYLON.Vector3.Zero();
  82091. };
  82092. PhysicsImpostor.prototype.setLinearVelocity = function (velocity) {
  82093. if (this._physicsEngine) {
  82094. this._physicsEngine.getPhysicsPlugin().setLinearVelocity(this, velocity);
  82095. }
  82096. };
  82097. PhysicsImpostor.prototype.getAngularVelocity = function () {
  82098. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getAngularVelocity(this) : BABYLON.Vector3.Zero();
  82099. };
  82100. PhysicsImpostor.prototype.setAngularVelocity = function (velocity) {
  82101. if (this._physicsEngine) {
  82102. this._physicsEngine.getPhysicsPlugin().setAngularVelocity(this, velocity);
  82103. }
  82104. };
  82105. /**
  82106. * Execute a function with the physics plugin native code.
  82107. * Provide a function the will have two variables - the world object and the physics body object.
  82108. */
  82109. PhysicsImpostor.prototype.executeNativeFunction = function (func) {
  82110. if (this._physicsEngine) {
  82111. func(this._physicsEngine.getPhysicsPlugin().world, this.physicsBody);
  82112. }
  82113. };
  82114. /**
  82115. * Register a function that will be executed before the physics world is stepping forward.
  82116. */
  82117. PhysicsImpostor.prototype.registerBeforePhysicsStep = function (func) {
  82118. this._onBeforePhysicsStepCallbacks.push(func);
  82119. };
  82120. PhysicsImpostor.prototype.unregisterBeforePhysicsStep = function (func) {
  82121. var index = this._onBeforePhysicsStepCallbacks.indexOf(func);
  82122. if (index > -1) {
  82123. this._onBeforePhysicsStepCallbacks.splice(index, 1);
  82124. }
  82125. else {
  82126. BABYLON.Tools.Warn("Function to remove was not found");
  82127. }
  82128. };
  82129. /**
  82130. * Register a function that will be executed after the physics step
  82131. */
  82132. PhysicsImpostor.prototype.registerAfterPhysicsStep = function (func) {
  82133. this._onAfterPhysicsStepCallbacks.push(func);
  82134. };
  82135. PhysicsImpostor.prototype.unregisterAfterPhysicsStep = function (func) {
  82136. var index = this._onAfterPhysicsStepCallbacks.indexOf(func);
  82137. if (index > -1) {
  82138. this._onAfterPhysicsStepCallbacks.splice(index, 1);
  82139. }
  82140. else {
  82141. BABYLON.Tools.Warn("Function to remove was not found");
  82142. }
  82143. };
  82144. /**
  82145. * register a function that will be executed when this impostor collides against a different body.
  82146. */
  82147. PhysicsImpostor.prototype.registerOnPhysicsCollide = function (collideAgainst, func) {
  82148. var collidedAgainstList = collideAgainst instanceof Array ? collideAgainst : [collideAgainst];
  82149. this._onPhysicsCollideCallbacks.push({ callback: func, otherImpostors: collidedAgainstList });
  82150. };
  82151. PhysicsImpostor.prototype.unregisterOnPhysicsCollide = function (collideAgainst, func) {
  82152. var collidedAgainstList = collideAgainst instanceof Array ? collideAgainst : [collideAgainst];
  82153. var index = this._onPhysicsCollideCallbacks.indexOf({ callback: func, otherImpostors: collidedAgainstList });
  82154. if (index > -1) {
  82155. this._onPhysicsCollideCallbacks.splice(index, 1);
  82156. }
  82157. else {
  82158. BABYLON.Tools.Warn("Function to remove was not found");
  82159. }
  82160. };
  82161. PhysicsImpostor.prototype.getParentsRotation = function () {
  82162. var parent = this.object.parent;
  82163. this._tmpQuat.copyFromFloats(0, 0, 0, 1);
  82164. while (parent) {
  82165. if (parent.rotationQuaternion) {
  82166. this._tmpQuat2.copyFrom(parent.rotationQuaternion);
  82167. }
  82168. else {
  82169. BABYLON.Quaternion.RotationYawPitchRollToRef(parent.rotation.y, parent.rotation.x, parent.rotation.z, this._tmpQuat2);
  82170. }
  82171. this._tmpQuat.multiplyToRef(this._tmpQuat2, this._tmpQuat);
  82172. parent = parent.parent;
  82173. }
  82174. return this._tmpQuat;
  82175. };
  82176. /**
  82177. * Apply a force
  82178. */
  82179. PhysicsImpostor.prototype.applyForce = function (force, contactPoint) {
  82180. if (this._physicsEngine) {
  82181. this._physicsEngine.getPhysicsPlugin().applyForce(this, force, contactPoint);
  82182. }
  82183. return this;
  82184. };
  82185. /**
  82186. * Apply an impulse
  82187. */
  82188. PhysicsImpostor.prototype.applyImpulse = function (force, contactPoint) {
  82189. if (this._physicsEngine) {
  82190. this._physicsEngine.getPhysicsPlugin().applyImpulse(this, force, contactPoint);
  82191. }
  82192. return this;
  82193. };
  82194. /**
  82195. * A help function to create a joint.
  82196. */
  82197. PhysicsImpostor.prototype.createJoint = function (otherImpostor, jointType, jointData) {
  82198. var joint = new BABYLON.PhysicsJoint(jointType, jointData);
  82199. this.addJoint(otherImpostor, joint);
  82200. return this;
  82201. };
  82202. /**
  82203. * Add a joint to this impostor with a different impostor.
  82204. */
  82205. PhysicsImpostor.prototype.addJoint = function (otherImpostor, joint) {
  82206. this._joints.push({
  82207. otherImpostor: otherImpostor,
  82208. joint: joint
  82209. });
  82210. if (this._physicsEngine) {
  82211. this._physicsEngine.addJoint(this, otherImpostor, joint);
  82212. }
  82213. return this;
  82214. };
  82215. /**
  82216. * Will keep this body still, in a sleep mode.
  82217. */
  82218. PhysicsImpostor.prototype.sleep = function () {
  82219. if (this._physicsEngine) {
  82220. this._physicsEngine.getPhysicsPlugin().sleepBody(this);
  82221. }
  82222. return this;
  82223. };
  82224. /**
  82225. * Wake the body up.
  82226. */
  82227. PhysicsImpostor.prototype.wakeUp = function () {
  82228. if (this._physicsEngine) {
  82229. this._physicsEngine.getPhysicsPlugin().wakeUpBody(this);
  82230. }
  82231. return this;
  82232. };
  82233. PhysicsImpostor.prototype.clone = function (newObject) {
  82234. if (!newObject)
  82235. return null;
  82236. return new PhysicsImpostor(newObject, this.type, this._options, this._scene);
  82237. };
  82238. PhysicsImpostor.prototype.dispose = function ( /*disposeChildren: boolean = true*/) {
  82239. var _this = this;
  82240. //no dispose if no physics engine is available.
  82241. if (!this._physicsEngine) {
  82242. return;
  82243. }
  82244. this._joints.forEach(function (j) {
  82245. if (_this._physicsEngine) {
  82246. _this._physicsEngine.removeJoint(_this, j.otherImpostor, j.joint);
  82247. }
  82248. });
  82249. //dispose the physics body
  82250. this._physicsEngine.removeImpostor(this);
  82251. if (this.parent) {
  82252. this.parent.forceUpdate();
  82253. }
  82254. else {
  82255. /*this._object.getChildMeshes().forEach(function(mesh) {
  82256. if (mesh.physicsImpostor) {
  82257. if (disposeChildren) {
  82258. mesh.physicsImpostor.dispose();
  82259. mesh.physicsImpostor = null;
  82260. }
  82261. }
  82262. })*/
  82263. }
  82264. this._isDisposed = true;
  82265. };
  82266. PhysicsImpostor.prototype.setDeltaPosition = function (position) {
  82267. this._deltaPosition.copyFrom(position);
  82268. };
  82269. PhysicsImpostor.prototype.setDeltaRotation = function (rotation) {
  82270. if (!this._deltaRotation) {
  82271. this._deltaRotation = new BABYLON.Quaternion();
  82272. }
  82273. this._deltaRotation.copyFrom(rotation);
  82274. this._deltaRotationConjugated = this._deltaRotation.conjugate();
  82275. };
  82276. PhysicsImpostor.prototype.getBoxSizeToRef = function (result) {
  82277. if (this._physicsEngine) {
  82278. this._physicsEngine.getPhysicsPlugin().getBoxSizeToRef(this, result);
  82279. }
  82280. return this;
  82281. };
  82282. PhysicsImpostor.prototype.getRadius = function () {
  82283. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getRadius(this) : 0;
  82284. };
  82285. /**
  82286. * Sync a bone with this impostor
  82287. * @param bone The bone to sync to the impostor.
  82288. * @param boneMesh The mesh that the bone is influencing.
  82289. * @param jointPivot The pivot of the joint / bone in local space.
  82290. * @param distToJoint Optional distance from the impostor to the joint.
  82291. * @param adjustRotation Optional quaternion for adjusting the local rotation of the bone.
  82292. */
  82293. PhysicsImpostor.prototype.syncBoneWithImpostor = function (bone, boneMesh, jointPivot, distToJoint, adjustRotation) {
  82294. var tempVec = PhysicsImpostor._tmpVecs[0];
  82295. var mesh = this.object;
  82296. if (mesh.rotationQuaternion) {
  82297. if (adjustRotation) {
  82298. var tempQuat = PhysicsImpostor._tmpQuat;
  82299. mesh.rotationQuaternion.multiplyToRef(adjustRotation, tempQuat);
  82300. bone.setRotationQuaternion(tempQuat, BABYLON.Space.WORLD, boneMesh);
  82301. }
  82302. else {
  82303. bone.setRotationQuaternion(mesh.rotationQuaternion, BABYLON.Space.WORLD, boneMesh);
  82304. }
  82305. }
  82306. tempVec.x = 0;
  82307. tempVec.y = 0;
  82308. tempVec.z = 0;
  82309. if (jointPivot) {
  82310. tempVec.x = jointPivot.x;
  82311. tempVec.y = jointPivot.y;
  82312. tempVec.z = jointPivot.z;
  82313. bone.getDirectionToRef(tempVec, boneMesh, tempVec);
  82314. if (distToJoint === undefined || distToJoint === null) {
  82315. distToJoint = jointPivot.length();
  82316. }
  82317. tempVec.x *= distToJoint;
  82318. tempVec.y *= distToJoint;
  82319. tempVec.z *= distToJoint;
  82320. }
  82321. if (bone.getParent()) {
  82322. tempVec.addInPlace(mesh.getAbsolutePosition());
  82323. bone.setAbsolutePosition(tempVec, boneMesh);
  82324. }
  82325. else {
  82326. boneMesh.setAbsolutePosition(mesh.getAbsolutePosition());
  82327. boneMesh.position.x -= tempVec.x;
  82328. boneMesh.position.y -= tempVec.y;
  82329. boneMesh.position.z -= tempVec.z;
  82330. }
  82331. };
  82332. /**
  82333. * Sync impostor to a bone
  82334. * @param bone The bone that the impostor will be synced to.
  82335. * @param boneMesh The mesh that the bone is influencing.
  82336. * @param jointPivot The pivot of the joint / bone in local space.
  82337. * @param distToJoint Optional distance from the impostor to the joint.
  82338. * @param adjustRotation Optional quaternion for adjusting the local rotation of the bone.
  82339. * @param boneAxis Optional vector3 axis the bone is aligned with
  82340. */
  82341. PhysicsImpostor.prototype.syncImpostorWithBone = function (bone, boneMesh, jointPivot, distToJoint, adjustRotation, boneAxis) {
  82342. var mesh = this.object;
  82343. if (mesh.rotationQuaternion) {
  82344. if (adjustRotation) {
  82345. var tempQuat = PhysicsImpostor._tmpQuat;
  82346. bone.getRotationQuaternionToRef(BABYLON.Space.WORLD, boneMesh, tempQuat);
  82347. tempQuat.multiplyToRef(adjustRotation, mesh.rotationQuaternion);
  82348. }
  82349. else {
  82350. bone.getRotationQuaternionToRef(BABYLON.Space.WORLD, boneMesh, mesh.rotationQuaternion);
  82351. }
  82352. }
  82353. var pos = PhysicsImpostor._tmpVecs[0];
  82354. var boneDir = PhysicsImpostor._tmpVecs[1];
  82355. if (!boneAxis) {
  82356. boneAxis = PhysicsImpostor._tmpVecs[2];
  82357. boneAxis.x = 0;
  82358. boneAxis.y = 1;
  82359. boneAxis.z = 0;
  82360. }
  82361. bone.getDirectionToRef(boneAxis, boneMesh, boneDir);
  82362. bone.getAbsolutePositionToRef(boneMesh, pos);
  82363. if ((distToJoint === undefined || distToJoint === null) && jointPivot) {
  82364. distToJoint = jointPivot.length();
  82365. }
  82366. if (distToJoint !== undefined && distToJoint !== null) {
  82367. pos.x += boneDir.x * distToJoint;
  82368. pos.y += boneDir.y * distToJoint;
  82369. pos.z += boneDir.z * distToJoint;
  82370. }
  82371. mesh.setAbsolutePosition(pos);
  82372. };
  82373. PhysicsImpostor.DEFAULT_OBJECT_SIZE = new BABYLON.Vector3(1, 1, 1);
  82374. PhysicsImpostor.IDENTITY_QUATERNION = BABYLON.Quaternion.Identity();
  82375. PhysicsImpostor._tmpVecs = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  82376. PhysicsImpostor._tmpQuat = BABYLON.Quaternion.Identity();
  82377. //Impostor types
  82378. PhysicsImpostor.NoImpostor = 0;
  82379. PhysicsImpostor.SphereImpostor = 1;
  82380. PhysicsImpostor.BoxImpostor = 2;
  82381. PhysicsImpostor.PlaneImpostor = 3;
  82382. PhysicsImpostor.MeshImpostor = 4;
  82383. PhysicsImpostor.CylinderImpostor = 7;
  82384. PhysicsImpostor.ParticleImpostor = 8;
  82385. PhysicsImpostor.HeightmapImpostor = 9;
  82386. return PhysicsImpostor;
  82387. }());
  82388. BABYLON.PhysicsImpostor = PhysicsImpostor;
  82389. })(BABYLON || (BABYLON = {}));
  82390. //# sourceMappingURL=babylon.physicsImpostor.js.map
  82391. var BABYLON;
  82392. (function (BABYLON) {
  82393. var PhysicsEngine = /** @class */ (function () {
  82394. function PhysicsEngine(gravity, _physicsPlugin) {
  82395. if (_physicsPlugin === void 0) { _physicsPlugin = new BABYLON.CannonJSPlugin(); }
  82396. this._physicsPlugin = _physicsPlugin;
  82397. //new methods and parameters
  82398. this._impostors = [];
  82399. this._joints = [];
  82400. if (!this._physicsPlugin.isSupported()) {
  82401. throw new Error("Physics Engine " + this._physicsPlugin.name + " cannot be found. "
  82402. + "Please make sure it is included.");
  82403. }
  82404. gravity = gravity || new BABYLON.Vector3(0, -9.807, 0);
  82405. this.setGravity(gravity);
  82406. this.setTimeStep();
  82407. }
  82408. PhysicsEngine.prototype.setGravity = function (gravity) {
  82409. this.gravity = gravity;
  82410. this._physicsPlugin.setGravity(this.gravity);
  82411. };
  82412. /**
  82413. * Set the time step of the physics engine.
  82414. * default is 1/60.
  82415. * To slow it down, enter 1/600 for example.
  82416. * To speed it up, 1/30
  82417. * @param {number} newTimeStep the new timestep to apply to this world.
  82418. */
  82419. PhysicsEngine.prototype.setTimeStep = function (newTimeStep) {
  82420. if (newTimeStep === void 0) { newTimeStep = 1 / 60; }
  82421. this._physicsPlugin.setTimeStep(newTimeStep);
  82422. };
  82423. /**
  82424. * Get the time step of the physics engine.
  82425. */
  82426. PhysicsEngine.prototype.getTimeStep = function () {
  82427. return this._physicsPlugin.getTimeStep();
  82428. };
  82429. PhysicsEngine.prototype.dispose = function () {
  82430. this._impostors.forEach(function (impostor) {
  82431. impostor.dispose();
  82432. });
  82433. this._physicsPlugin.dispose();
  82434. };
  82435. PhysicsEngine.prototype.getPhysicsPluginName = function () {
  82436. return this._physicsPlugin.name;
  82437. };
  82438. /**
  82439. * Adding a new impostor for the impostor tracking.
  82440. * This will be done by the impostor itself.
  82441. * @param {PhysicsImpostor} impostor the impostor to add
  82442. */
  82443. PhysicsEngine.prototype.addImpostor = function (impostor) {
  82444. impostor.uniqueId = this._impostors.push(impostor);
  82445. //if no parent, generate the body
  82446. if (!impostor.parent) {
  82447. this._physicsPlugin.generatePhysicsBody(impostor);
  82448. }
  82449. };
  82450. /**
  82451. * Remove an impostor from the engine.
  82452. * This impostor and its mesh will not longer be updated by the physics engine.
  82453. * @param {PhysicsImpostor} impostor the impostor to remove
  82454. */
  82455. PhysicsEngine.prototype.removeImpostor = function (impostor) {
  82456. var index = this._impostors.indexOf(impostor);
  82457. if (index > -1) {
  82458. var removed = this._impostors.splice(index, 1);
  82459. //Is it needed?
  82460. if (removed.length) {
  82461. //this will also remove it from the world.
  82462. removed[0].physicsBody = null;
  82463. }
  82464. }
  82465. };
  82466. /**
  82467. * Add a joint to the physics engine
  82468. * @param {PhysicsImpostor} mainImpostor the main impostor to which the joint is added.
  82469. * @param {PhysicsImpostor} connectedImpostor the impostor that is connected to the main impostor using this joint
  82470. * @param {PhysicsJoint} the joint that will connect both impostors.
  82471. */
  82472. PhysicsEngine.prototype.addJoint = function (mainImpostor, connectedImpostor, joint) {
  82473. var impostorJoint = {
  82474. mainImpostor: mainImpostor,
  82475. connectedImpostor: connectedImpostor,
  82476. joint: joint
  82477. };
  82478. joint.physicsPlugin = this._physicsPlugin;
  82479. this._joints.push(impostorJoint);
  82480. this._physicsPlugin.generateJoint(impostorJoint);
  82481. };
  82482. PhysicsEngine.prototype.removeJoint = function (mainImpostor, connectedImpostor, joint) {
  82483. var matchingJoints = this._joints.filter(function (impostorJoint) {
  82484. return (impostorJoint.connectedImpostor === connectedImpostor
  82485. && impostorJoint.joint === joint
  82486. && impostorJoint.mainImpostor === mainImpostor);
  82487. });
  82488. if (matchingJoints.length) {
  82489. this._physicsPlugin.removeJoint(matchingJoints[0]);
  82490. //TODO remove it from the list as well
  82491. }
  82492. };
  82493. /**
  82494. * Called by the scene. no need to call it.
  82495. */
  82496. PhysicsEngine.prototype._step = function (delta) {
  82497. var _this = this;
  82498. //check if any mesh has no body / requires an update
  82499. this._impostors.forEach(function (impostor) {
  82500. if (impostor.isBodyInitRequired()) {
  82501. _this._physicsPlugin.generatePhysicsBody(impostor);
  82502. }
  82503. });
  82504. if (delta > 0.1) {
  82505. delta = 0.1;
  82506. }
  82507. else if (delta <= 0) {
  82508. delta = 1.0 / 60.0;
  82509. }
  82510. this._physicsPlugin.executeStep(delta, this._impostors);
  82511. };
  82512. PhysicsEngine.prototype.getPhysicsPlugin = function () {
  82513. return this._physicsPlugin;
  82514. };
  82515. PhysicsEngine.prototype.getImpostors = function () {
  82516. return this._impostors;
  82517. };
  82518. PhysicsEngine.prototype.getImpostorForPhysicsObject = function (object) {
  82519. for (var i = 0; i < this._impostors.length; ++i) {
  82520. if (this._impostors[i].object === object) {
  82521. return this._impostors[i];
  82522. }
  82523. }
  82524. return null;
  82525. };
  82526. PhysicsEngine.prototype.getImpostorWithPhysicsBody = function (body) {
  82527. for (var i = 0; i < this._impostors.length; ++i) {
  82528. if (this._impostors[i].physicsBody === body) {
  82529. return this._impostors[i];
  82530. }
  82531. }
  82532. return null;
  82533. };
  82534. // Statics
  82535. PhysicsEngine.Epsilon = 0.001;
  82536. return PhysicsEngine;
  82537. }());
  82538. BABYLON.PhysicsEngine = PhysicsEngine;
  82539. })(BABYLON || (BABYLON = {}));
  82540. //# sourceMappingURL=babylon.physicsEngine.js.map
  82541. var BABYLON;
  82542. (function (BABYLON) {
  82543. var PhysicsHelper = /** @class */ (function () {
  82544. function PhysicsHelper(scene) {
  82545. this._scene = scene;
  82546. this._physicsEngine = this._scene.getPhysicsEngine();
  82547. if (!this._physicsEngine) {
  82548. BABYLON.Tools.Warn('Physics engine not enabled. Please enable the physics before you can use the methods.');
  82549. }
  82550. }
  82551. /**
  82552. * @param {Vector3} origin the origin of the explosion
  82553. * @param {number} radius the explosion radius
  82554. * @param {number} strength the explosion strength
  82555. * @param {PhysicsRadialImpulseFalloff} falloff possible options: Constant & Linear. Defaults to Constant
  82556. */
  82557. PhysicsHelper.prototype.applyRadialExplosionImpulse = function (origin, radius, strength, falloff) {
  82558. if (falloff === void 0) { falloff = PhysicsRadialImpulseFalloff.Constant; }
  82559. if (!this._physicsEngine) {
  82560. BABYLON.Tools.Warn('Physics engine not enabled. Please enable the physics before you call this method.');
  82561. return null;
  82562. }
  82563. var impostors = this._physicsEngine.getImpostors();
  82564. if (impostors.length === 0) {
  82565. return null;
  82566. }
  82567. var event = new PhysicsRadialExplosionEvent(this._scene);
  82568. impostors.forEach(function (impostor) {
  82569. var impostorForceAndContactPoint = event.getImpostorForceAndContactPoint(impostor, origin, radius, strength, falloff);
  82570. if (!impostorForceAndContactPoint) {
  82571. return;
  82572. }
  82573. impostor.applyImpulse(impostorForceAndContactPoint.force, impostorForceAndContactPoint.contactPoint);
  82574. });
  82575. event.dispose(false);
  82576. return event;
  82577. };
  82578. /**
  82579. * @param {Vector3} origin the origin of the explosion
  82580. * @param {number} radius the explosion radius
  82581. * @param {number} strength the explosion strength
  82582. * @param {PhysicsRadialImpulseFalloff} falloff possible options: Constant & Linear. Defaults to Constant
  82583. */
  82584. PhysicsHelper.prototype.applyRadialExplosionForce = function (origin, radius, strength, falloff) {
  82585. if (falloff === void 0) { falloff = PhysicsRadialImpulseFalloff.Constant; }
  82586. if (!this._physicsEngine) {
  82587. BABYLON.Tools.Warn('Physics engine not enabled. Please enable the physics before you call the PhysicsHelper.');
  82588. return null;
  82589. }
  82590. var impostors = this._physicsEngine.getImpostors();
  82591. if (impostors.length === 0) {
  82592. return null;
  82593. }
  82594. var event = new PhysicsRadialExplosionEvent(this._scene);
  82595. impostors.forEach(function (impostor) {
  82596. var impostorForceAndContactPoint = event.getImpostorForceAndContactPoint(impostor, origin, radius, strength, falloff);
  82597. if (!impostorForceAndContactPoint) {
  82598. return;
  82599. }
  82600. impostor.applyForce(impostorForceAndContactPoint.force, impostorForceAndContactPoint.contactPoint);
  82601. });
  82602. event.dispose(false);
  82603. return event;
  82604. };
  82605. /**
  82606. * @param {Vector3} origin the origin of the explosion
  82607. * @param {number} radius the explosion radius
  82608. * @param {number} strength the explosion strength
  82609. * @param {PhysicsRadialImpulseFalloff} falloff possible options: Constant & Linear. Defaults to Constant
  82610. */
  82611. PhysicsHelper.prototype.gravitationalField = function (origin, radius, strength, falloff) {
  82612. if (falloff === void 0) { falloff = PhysicsRadialImpulseFalloff.Constant; }
  82613. if (!this._physicsEngine) {
  82614. BABYLON.Tools.Warn('Physics engine not enabled. Please enable the physics before you call the PhysicsHelper.');
  82615. return null;
  82616. }
  82617. var impostors = this._physicsEngine.getImpostors();
  82618. if (impostors.length === 0) {
  82619. return null;
  82620. }
  82621. var event = new PhysicsGravitationalFieldEvent(this, this._scene, origin, radius, strength, falloff);
  82622. event.dispose(false);
  82623. return event;
  82624. };
  82625. /**
  82626. * @param {Vector3} origin the origin of the updraft
  82627. * @param {number} radius the radius of the updraft
  82628. * @param {number} strength the strength of the updraft
  82629. * @param {number} height the height of the updraft
  82630. * @param {PhysicsUpdraftMode} updraftMode possible options: Center & Perpendicular. Defaults to Center
  82631. */
  82632. PhysicsHelper.prototype.updraft = function (origin, radius, strength, height, updraftMode) {
  82633. if (updraftMode === void 0) { updraftMode = PhysicsUpdraftMode.Center; }
  82634. if (!this._physicsEngine) {
  82635. BABYLON.Tools.Warn('Physics engine not enabled. Please enable the physics before you call the PhysicsHelper.');
  82636. return null;
  82637. }
  82638. if (this._physicsEngine.getImpostors().length === 0) {
  82639. return null;
  82640. }
  82641. var event = new PhysicsUpdraftEvent(this._scene, origin, radius, strength, height, updraftMode);
  82642. event.dispose(false);
  82643. return event;
  82644. };
  82645. /**
  82646. * @param {Vector3} origin the of the vortex
  82647. * @param {number} radius the radius of the vortex
  82648. * @param {number} strength the strength of the vortex
  82649. * @param {number} height the height of the vortex
  82650. */
  82651. PhysicsHelper.prototype.vortex = function (origin, radius, strength, height) {
  82652. if (!this._physicsEngine) {
  82653. BABYLON.Tools.Warn('Physics engine not enabled. Please enable the physics before you call the PhysicsHelper.');
  82654. return null;
  82655. }
  82656. if (this._physicsEngine.getImpostors().length === 0) {
  82657. return null;
  82658. }
  82659. var event = new PhysicsVortexEvent(this._scene, origin, radius, strength, height);
  82660. event.dispose(false);
  82661. return event;
  82662. };
  82663. return PhysicsHelper;
  82664. }());
  82665. BABYLON.PhysicsHelper = PhysicsHelper;
  82666. /***** Radial explosion *****/
  82667. var PhysicsRadialExplosionEvent = /** @class */ (function () {
  82668. function PhysicsRadialExplosionEvent(scene) {
  82669. this._sphereOptions = { segments: 32, diameter: 1 }; // TODO: make configurable
  82670. this._rays = [];
  82671. this._dataFetched = false; // check if the data has been fetched. If not, do cleanup
  82672. this._scene = scene;
  82673. }
  82674. /**
  82675. * Returns the data related to the radial explosion event (sphere & rays).
  82676. * @returns {PhysicsRadialExplosionEventData}
  82677. */
  82678. PhysicsRadialExplosionEvent.prototype.getData = function () {
  82679. this._dataFetched = true;
  82680. return {
  82681. sphere: this._sphere,
  82682. rays: this._rays,
  82683. };
  82684. };
  82685. /**
  82686. * Returns the force and contact point of the impostor or false, if the impostor is not affected by the force/impulse.
  82687. * @param impostor
  82688. * @param {Vector3} origin the origin of the explosion
  82689. * @param {number} radius the explosion radius
  82690. * @param {number} strength the explosion strength
  82691. * @param {PhysicsRadialImpulseFalloff} falloff possible options: Constant & Linear
  82692. * @returns {Nullable<PhysicsForceAndContactPoint>}
  82693. */
  82694. PhysicsRadialExplosionEvent.prototype.getImpostorForceAndContactPoint = function (impostor, origin, radius, strength, falloff) {
  82695. if (impostor.mass === 0) {
  82696. return null;
  82697. }
  82698. if (!this._intersectsWithSphere(impostor, origin, radius)) {
  82699. return null;
  82700. }
  82701. if (impostor.object.getClassName() !== 'Mesh' && impostor.object.getClassName() !== 'InstancedMesh') {
  82702. return null;
  82703. }
  82704. var impostorObjectCenter = impostor.getObjectCenter();
  82705. var direction = impostorObjectCenter.subtract(origin);
  82706. var ray = new BABYLON.Ray(origin, direction, radius);
  82707. this._rays.push(ray);
  82708. var hit = ray.intersectsMesh(impostor.object);
  82709. var contactPoint = hit.pickedPoint;
  82710. if (!contactPoint) {
  82711. return null;
  82712. }
  82713. var distanceFromOrigin = BABYLON.Vector3.Distance(origin, contactPoint);
  82714. if (distanceFromOrigin > radius) {
  82715. return null;
  82716. }
  82717. var multiplier = falloff === PhysicsRadialImpulseFalloff.Constant
  82718. ? strength
  82719. : strength * (1 - (distanceFromOrigin / radius));
  82720. var force = direction.multiplyByFloats(multiplier, multiplier, multiplier);
  82721. return { force: force, contactPoint: contactPoint };
  82722. };
  82723. /**
  82724. * Disposes the sphere.
  82725. * @param {bolean} force
  82726. */
  82727. PhysicsRadialExplosionEvent.prototype.dispose = function (force) {
  82728. var _this = this;
  82729. if (force === void 0) { force = true; }
  82730. if (force) {
  82731. this._sphere.dispose();
  82732. }
  82733. else {
  82734. setTimeout(function () {
  82735. if (!_this._dataFetched) {
  82736. _this._sphere.dispose();
  82737. }
  82738. }, 0);
  82739. }
  82740. };
  82741. /*** Helpers ***/
  82742. PhysicsRadialExplosionEvent.prototype._prepareSphere = function () {
  82743. if (!this._sphere) {
  82744. this._sphere = BABYLON.MeshBuilder.CreateSphere("radialExplosionEventSphere", this._sphereOptions, this._scene);
  82745. this._sphere.isVisible = false;
  82746. }
  82747. };
  82748. PhysicsRadialExplosionEvent.prototype._intersectsWithSphere = function (impostor, origin, radius) {
  82749. var impostorObject = impostor.object;
  82750. this._prepareSphere();
  82751. this._sphere.position = origin;
  82752. this._sphere.scaling = new BABYLON.Vector3(radius * 2, radius * 2, radius * 2);
  82753. this._sphere._updateBoundingInfo();
  82754. this._sphere.computeWorldMatrix(true);
  82755. return this._sphere.intersectsMesh(impostorObject, true);
  82756. };
  82757. return PhysicsRadialExplosionEvent;
  82758. }());
  82759. BABYLON.PhysicsRadialExplosionEvent = PhysicsRadialExplosionEvent;
  82760. /***** Gravitational Field *****/
  82761. var PhysicsGravitationalFieldEvent = /** @class */ (function () {
  82762. function PhysicsGravitationalFieldEvent(physicsHelper, scene, origin, radius, strength, falloff) {
  82763. if (falloff === void 0) { falloff = PhysicsRadialImpulseFalloff.Constant; }
  82764. this._dataFetched = false; // check if the has been fetched the data. If not, do cleanup
  82765. this._physicsHelper = physicsHelper;
  82766. this._scene = scene;
  82767. this._origin = origin;
  82768. this._radius = radius;
  82769. this._strength = strength;
  82770. this._falloff = falloff;
  82771. this._tickCallback = this._tick.bind(this);
  82772. }
  82773. /**
  82774. * Returns the data related to the gravitational field event (sphere).
  82775. * @returns {PhysicsGravitationalFieldEventData}
  82776. */
  82777. PhysicsGravitationalFieldEvent.prototype.getData = function () {
  82778. this._dataFetched = true;
  82779. return {
  82780. sphere: this._sphere,
  82781. };
  82782. };
  82783. /**
  82784. * Enables the gravitational field.
  82785. */
  82786. PhysicsGravitationalFieldEvent.prototype.enable = function () {
  82787. this._tickCallback.call(this);
  82788. this._scene.registerBeforeRender(this._tickCallback);
  82789. };
  82790. /**
  82791. * Disables the gravitational field.
  82792. */
  82793. PhysicsGravitationalFieldEvent.prototype.disable = function () {
  82794. this._scene.unregisterBeforeRender(this._tickCallback);
  82795. };
  82796. /**
  82797. * Disposes the sphere.
  82798. * @param {bolean} force
  82799. */
  82800. PhysicsGravitationalFieldEvent.prototype.dispose = function (force) {
  82801. var _this = this;
  82802. if (force === void 0) { force = true; }
  82803. if (force) {
  82804. this._sphere.dispose();
  82805. }
  82806. else {
  82807. setTimeout(function () {
  82808. if (!_this._dataFetched) {
  82809. _this._sphere.dispose();
  82810. }
  82811. }, 0);
  82812. }
  82813. };
  82814. PhysicsGravitationalFieldEvent.prototype._tick = function () {
  82815. // Since the params won't change, we fetch the event only once
  82816. if (this._sphere) {
  82817. this._physicsHelper.applyRadialExplosionForce(this._origin, this._radius, this._strength * -1, this._falloff);
  82818. }
  82819. else {
  82820. var radialExplosionEvent = this._physicsHelper.applyRadialExplosionForce(this._origin, this._radius, this._strength * -1, this._falloff);
  82821. if (radialExplosionEvent) {
  82822. this._sphere = radialExplosionEvent.getData().sphere.clone('radialExplosionEventSphereClone');
  82823. }
  82824. }
  82825. };
  82826. return PhysicsGravitationalFieldEvent;
  82827. }());
  82828. BABYLON.PhysicsGravitationalFieldEvent = PhysicsGravitationalFieldEvent;
  82829. /***** Updraft *****/
  82830. var PhysicsUpdraftEvent = /** @class */ (function () {
  82831. function PhysicsUpdraftEvent(_scene, _origin, _radius, _strength, _height, _updraftMode) {
  82832. this._scene = _scene;
  82833. this._origin = _origin;
  82834. this._radius = _radius;
  82835. this._strength = _strength;
  82836. this._height = _height;
  82837. this._updraftMode = _updraftMode;
  82838. this._originTop = BABYLON.Vector3.Zero(); // the most upper part of the cylinder
  82839. this._originDirection = BABYLON.Vector3.Zero(); // used if the updraftMode is perpendicular
  82840. this._cylinderPosition = BABYLON.Vector3.Zero(); // to keep the cylinders position, because normally the origin is in the center and not on the bottom
  82841. this._dataFetched = false; // check if the has been fetched the data. If not, do cleanup
  82842. this._physicsEngine = this._scene.getPhysicsEngine();
  82843. this._origin.addToRef(new BABYLON.Vector3(0, this._height / 2, 0), this._cylinderPosition);
  82844. this._origin.addToRef(new BABYLON.Vector3(0, this._height, 0), this._originTop);
  82845. if (this._updraftMode === PhysicsUpdraftMode.Perpendicular) {
  82846. this._originDirection = this._origin.subtract(this._originTop).normalize();
  82847. }
  82848. this._tickCallback = this._tick.bind(this);
  82849. }
  82850. /**
  82851. * Returns the data related to the updraft event (cylinder).
  82852. * @returns {PhysicsUpdraftEventData}
  82853. */
  82854. PhysicsUpdraftEvent.prototype.getData = function () {
  82855. this._dataFetched = true;
  82856. return {
  82857. cylinder: this._cylinder,
  82858. };
  82859. };
  82860. /**
  82861. * Enables the updraft.
  82862. */
  82863. PhysicsUpdraftEvent.prototype.enable = function () {
  82864. this._tickCallback.call(this);
  82865. this._scene.registerBeforeRender(this._tickCallback);
  82866. };
  82867. /**
  82868. * Disables the cortex.
  82869. */
  82870. PhysicsUpdraftEvent.prototype.disable = function () {
  82871. this._scene.unregisterBeforeRender(this._tickCallback);
  82872. };
  82873. /**
  82874. * Disposes the sphere.
  82875. * @param {bolean} force
  82876. */
  82877. PhysicsUpdraftEvent.prototype.dispose = function (force) {
  82878. var _this = this;
  82879. if (force === void 0) { force = true; }
  82880. if (force) {
  82881. this._cylinder.dispose();
  82882. }
  82883. else {
  82884. setTimeout(function () {
  82885. if (!_this._dataFetched) {
  82886. _this._cylinder.dispose();
  82887. }
  82888. }, 0);
  82889. }
  82890. };
  82891. PhysicsUpdraftEvent.prototype.getImpostorForceAndContactPoint = function (impostor) {
  82892. if (impostor.mass === 0) {
  82893. return null;
  82894. }
  82895. if (!this._intersectsWithCylinder(impostor)) {
  82896. return null;
  82897. }
  82898. var impostorObjectCenter = impostor.getObjectCenter();
  82899. if (this._updraftMode === PhysicsUpdraftMode.Perpendicular) {
  82900. var direction = this._originDirection;
  82901. }
  82902. else {
  82903. var direction = impostorObjectCenter.subtract(this._originTop);
  82904. }
  82905. var multiplier = this._strength * -1;
  82906. var force = direction.multiplyByFloats(multiplier, multiplier, multiplier);
  82907. return { force: force, contactPoint: impostorObjectCenter };
  82908. };
  82909. PhysicsUpdraftEvent.prototype._tick = function () {
  82910. var _this = this;
  82911. this._physicsEngine.getImpostors().forEach(function (impostor) {
  82912. var impostorForceAndContactPoint = _this.getImpostorForceAndContactPoint(impostor);
  82913. if (!impostorForceAndContactPoint) {
  82914. return;
  82915. }
  82916. impostor.applyForce(impostorForceAndContactPoint.force, impostorForceAndContactPoint.contactPoint);
  82917. });
  82918. };
  82919. /*** Helpers ***/
  82920. PhysicsUpdraftEvent.prototype._prepareCylinder = function () {
  82921. if (!this._cylinder) {
  82922. this._cylinder = BABYLON.MeshBuilder.CreateCylinder("updraftEventCylinder", {
  82923. height: this._height,
  82924. diameter: this._radius * 2,
  82925. }, this._scene);
  82926. this._cylinder.isVisible = false;
  82927. }
  82928. };
  82929. PhysicsUpdraftEvent.prototype._intersectsWithCylinder = function (impostor) {
  82930. var impostorObject = impostor.object;
  82931. this._prepareCylinder();
  82932. this._cylinder.position = this._cylinderPosition;
  82933. return this._cylinder.intersectsMesh(impostorObject, true);
  82934. };
  82935. return PhysicsUpdraftEvent;
  82936. }());
  82937. BABYLON.PhysicsUpdraftEvent = PhysicsUpdraftEvent;
  82938. /***** Vortex *****/
  82939. var PhysicsVortexEvent = /** @class */ (function () {
  82940. function PhysicsVortexEvent(_scene, _origin, _radius, _strength, _height) {
  82941. this._scene = _scene;
  82942. this._origin = _origin;
  82943. this._radius = _radius;
  82944. this._strength = _strength;
  82945. this._height = _height;
  82946. this._originTop = BABYLON.Vector3.Zero(); // the most upper part of the cylinder
  82947. this._centripetalForceThreshold = 0.7; // at which distance, relative to the radius the centripetal forces should kick in
  82948. this._updraftMultiplier = 0.02;
  82949. this._cylinderPosition = BABYLON.Vector3.Zero(); // to keep the cylinders position, because normally the origin is in the center and not on the bottom
  82950. this._dataFetched = false; // check if the has been fetched the data. If not, do cleanup
  82951. this._physicsEngine = this._scene.getPhysicsEngine();
  82952. this._origin.addToRef(new BABYLON.Vector3(0, this._height / 2, 0), this._cylinderPosition);
  82953. this._origin.addToRef(new BABYLON.Vector3(0, this._height, 0), this._originTop);
  82954. this._tickCallback = this._tick.bind(this);
  82955. }
  82956. /**
  82957. * Returns the data related to the vortex event (cylinder).
  82958. * @returns {PhysicsVortexEventData}
  82959. */
  82960. PhysicsVortexEvent.prototype.getData = function () {
  82961. this._dataFetched = true;
  82962. return {
  82963. cylinder: this._cylinder,
  82964. };
  82965. };
  82966. /**
  82967. * Enables the vortex.
  82968. */
  82969. PhysicsVortexEvent.prototype.enable = function () {
  82970. this._tickCallback.call(this);
  82971. this._scene.registerBeforeRender(this._tickCallback);
  82972. };
  82973. /**
  82974. * Disables the cortex.
  82975. */
  82976. PhysicsVortexEvent.prototype.disable = function () {
  82977. this._scene.unregisterBeforeRender(this._tickCallback);
  82978. };
  82979. /**
  82980. * Disposes the sphere.
  82981. * @param {bolean} force
  82982. */
  82983. PhysicsVortexEvent.prototype.dispose = function (force) {
  82984. var _this = this;
  82985. if (force === void 0) { force = true; }
  82986. if (force) {
  82987. this._cylinder.dispose();
  82988. }
  82989. else {
  82990. setTimeout(function () {
  82991. if (!_this._dataFetched) {
  82992. _this._cylinder.dispose();
  82993. }
  82994. }, 0);
  82995. }
  82996. };
  82997. PhysicsVortexEvent.prototype.getImpostorForceAndContactPoint = function (impostor) {
  82998. if (impostor.mass === 0) {
  82999. return null;
  83000. }
  83001. if (!this._intersectsWithCylinder(impostor)) {
  83002. return null;
  83003. }
  83004. if (impostor.object.getClassName() !== 'Mesh' && impostor.object.getClassName() !== 'InstancedMesh') {
  83005. return null;
  83006. }
  83007. var impostorObjectCenter = impostor.getObjectCenter();
  83008. 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)
  83009. var originToImpostorDirection = impostorObjectCenter.subtract(originOnPlane);
  83010. var ray = new BABYLON.Ray(originOnPlane, originToImpostorDirection, this._radius);
  83011. var hit = ray.intersectsMesh(impostor.object);
  83012. var contactPoint = hit.pickedPoint;
  83013. if (!contactPoint) {
  83014. return null;
  83015. }
  83016. var absoluteDistanceFromOrigin = hit.distance / this._radius;
  83017. var perpendicularDirection = BABYLON.Vector3.Cross(originOnPlane, impostorObjectCenter).normalize();
  83018. var directionToOrigin = contactPoint.normalize();
  83019. if (absoluteDistanceFromOrigin > this._centripetalForceThreshold) {
  83020. directionToOrigin = directionToOrigin.negate();
  83021. }
  83022. // TODO: find a more physically based solution
  83023. if (absoluteDistanceFromOrigin > this._centripetalForceThreshold) {
  83024. var forceX = directionToOrigin.x * this._strength / 8;
  83025. var forceY = directionToOrigin.y * this._updraftMultiplier;
  83026. var forceZ = directionToOrigin.z * this._strength / 8;
  83027. }
  83028. else {
  83029. var forceX = (perpendicularDirection.x + directionToOrigin.x) / 2;
  83030. var forceY = this._originTop.y * this._updraftMultiplier;
  83031. var forceZ = (perpendicularDirection.z + directionToOrigin.z) / 2;
  83032. }
  83033. var force = new BABYLON.Vector3(forceX, forceY, forceZ);
  83034. force = force.multiplyByFloats(this._strength, this._strength, this._strength);
  83035. return { force: force, contactPoint: impostorObjectCenter };
  83036. };
  83037. PhysicsVortexEvent.prototype._tick = function () {
  83038. var _this = this;
  83039. this._physicsEngine.getImpostors().forEach(function (impostor) {
  83040. var impostorForceAndContactPoint = _this.getImpostorForceAndContactPoint(impostor);
  83041. if (!impostorForceAndContactPoint) {
  83042. return;
  83043. }
  83044. impostor.applyForce(impostorForceAndContactPoint.force, impostorForceAndContactPoint.contactPoint);
  83045. });
  83046. };
  83047. /*** Helpers ***/
  83048. PhysicsVortexEvent.prototype._prepareCylinder = function () {
  83049. if (!this._cylinder) {
  83050. this._cylinder = BABYLON.MeshBuilder.CreateCylinder("vortexEventCylinder", {
  83051. height: this._height,
  83052. diameter: this._radius * 2,
  83053. }, this._scene);
  83054. this._cylinder.isVisible = false;
  83055. }
  83056. };
  83057. PhysicsVortexEvent.prototype._intersectsWithCylinder = function (impostor) {
  83058. var impostorObject = impostor.object;
  83059. this._prepareCylinder();
  83060. this._cylinder.position = this._cylinderPosition;
  83061. return this._cylinder.intersectsMesh(impostorObject, true);
  83062. };
  83063. return PhysicsVortexEvent;
  83064. }());
  83065. BABYLON.PhysicsVortexEvent = PhysicsVortexEvent;
  83066. /***** Enums *****/
  83067. /**
  83068. * The strenght of the force in correspondence to the distance of the affected object
  83069. */
  83070. var PhysicsRadialImpulseFalloff;
  83071. (function (PhysicsRadialImpulseFalloff) {
  83072. /** Defines that impulse is constant in strength across it's whole radius */
  83073. PhysicsRadialImpulseFalloff[PhysicsRadialImpulseFalloff["Constant"] = 0] = "Constant";
  83074. /** DEfines that impulse gets weaker if it's further from the origin */
  83075. PhysicsRadialImpulseFalloff[PhysicsRadialImpulseFalloff["Linear"] = 1] = "Linear";
  83076. })(PhysicsRadialImpulseFalloff = BABYLON.PhysicsRadialImpulseFalloff || (BABYLON.PhysicsRadialImpulseFalloff = {}));
  83077. /**
  83078. * The strenght of the force in correspondence to the distance of the affected object
  83079. */
  83080. var PhysicsUpdraftMode;
  83081. (function (PhysicsUpdraftMode) {
  83082. /** Defines that the upstream forces will pull towards the top center of the cylinder */
  83083. PhysicsUpdraftMode[PhysicsUpdraftMode["Center"] = 0] = "Center";
  83084. /** Defines that once a impostor is inside the cylinder, it will shoot out perpendicular from the ground of the cylinder */
  83085. PhysicsUpdraftMode[PhysicsUpdraftMode["Perpendicular"] = 1] = "Perpendicular";
  83086. })(PhysicsUpdraftMode = BABYLON.PhysicsUpdraftMode || (BABYLON.PhysicsUpdraftMode = {}));
  83087. })(BABYLON || (BABYLON = {}));
  83088. //# sourceMappingURL=babylon.physicsHelper.js.map
  83089. var BABYLON;
  83090. (function (BABYLON) {
  83091. var CannonJSPlugin = /** @class */ (function () {
  83092. function CannonJSPlugin(_useDeltaForWorldStep, iterations) {
  83093. if (_useDeltaForWorldStep === void 0) { _useDeltaForWorldStep = true; }
  83094. if (iterations === void 0) { iterations = 10; }
  83095. this._useDeltaForWorldStep = _useDeltaForWorldStep;
  83096. this.name = "CannonJSPlugin";
  83097. this._physicsMaterials = new Array();
  83098. this._fixedTimeStep = 1 / 60;
  83099. //See https://github.com/schteppe/CANNON.js/blob/gh-pages/demos/collisionFilter.html
  83100. this.BJSCANNON = CANNON;
  83101. this._minus90X = new BABYLON.Quaternion(-0.7071067811865475, 0, 0, 0.7071067811865475);
  83102. this._plus90X = new BABYLON.Quaternion(0.7071067811865475, 0, 0, 0.7071067811865475);
  83103. this._tmpPosition = BABYLON.Vector3.Zero();
  83104. this._tmpDeltaPosition = BABYLON.Vector3.Zero();
  83105. this._tmpUnityRotation = new BABYLON.Quaternion();
  83106. if (!this.isSupported()) {
  83107. BABYLON.Tools.Error("CannonJS is not available. Please make sure you included the js file.");
  83108. return;
  83109. }
  83110. this._extendNamespace();
  83111. this.world = new this.BJSCANNON.World();
  83112. this.world.broadphase = new this.BJSCANNON.NaiveBroadphase();
  83113. this.world.solver.iterations = iterations;
  83114. }
  83115. CannonJSPlugin.prototype.setGravity = function (gravity) {
  83116. this.world.gravity.copy(gravity);
  83117. };
  83118. CannonJSPlugin.prototype.setTimeStep = function (timeStep) {
  83119. this._fixedTimeStep = timeStep;
  83120. };
  83121. CannonJSPlugin.prototype.getTimeStep = function () {
  83122. return this._fixedTimeStep;
  83123. };
  83124. CannonJSPlugin.prototype.executeStep = function (delta, impostors) {
  83125. this.world.step(this._fixedTimeStep, this._useDeltaForWorldStep ? delta : 0, 3);
  83126. };
  83127. CannonJSPlugin.prototype.applyImpulse = function (impostor, force, contactPoint) {
  83128. var worldPoint = new this.BJSCANNON.Vec3(contactPoint.x, contactPoint.y, contactPoint.z);
  83129. var impulse = new this.BJSCANNON.Vec3(force.x, force.y, force.z);
  83130. impostor.physicsBody.applyImpulse(impulse, worldPoint);
  83131. };
  83132. CannonJSPlugin.prototype.applyForce = function (impostor, force, contactPoint) {
  83133. var worldPoint = new this.BJSCANNON.Vec3(contactPoint.x, contactPoint.y, contactPoint.z);
  83134. var impulse = new this.BJSCANNON.Vec3(force.x, force.y, force.z);
  83135. impostor.physicsBody.applyForce(impulse, worldPoint);
  83136. };
  83137. CannonJSPlugin.prototype.generatePhysicsBody = function (impostor) {
  83138. //parent-child relationship. Does this impostor has a parent impostor?
  83139. if (impostor.parent) {
  83140. if (impostor.physicsBody) {
  83141. this.removePhysicsBody(impostor);
  83142. //TODO is that needed?
  83143. impostor.forceUpdate();
  83144. }
  83145. return;
  83146. }
  83147. //should a new body be created for this impostor?
  83148. if (impostor.isBodyInitRequired()) {
  83149. var shape = this._createShape(impostor);
  83150. //unregister events, if body is being changed
  83151. var oldBody = impostor.physicsBody;
  83152. if (oldBody) {
  83153. this.removePhysicsBody(impostor);
  83154. }
  83155. //create the body and material
  83156. var material = this._addMaterial("mat-" + impostor.uniqueId, impostor.getParam("friction"), impostor.getParam("restitution"));
  83157. var bodyCreationObject = {
  83158. mass: impostor.getParam("mass"),
  83159. material: material
  83160. };
  83161. // A simple extend, in case native options were used.
  83162. var nativeOptions = impostor.getParam("nativeOptions");
  83163. for (var key in nativeOptions) {
  83164. if (nativeOptions.hasOwnProperty(key)) {
  83165. bodyCreationObject[key] = nativeOptions[key];
  83166. }
  83167. }
  83168. impostor.physicsBody = new this.BJSCANNON.Body(bodyCreationObject);
  83169. impostor.physicsBody.addEventListener("collide", impostor.onCollide);
  83170. this.world.addEventListener("preStep", impostor.beforeStep);
  83171. this.world.addEventListener("postStep", impostor.afterStep);
  83172. impostor.physicsBody.addShape(shape);
  83173. this.world.add(impostor.physicsBody);
  83174. //try to keep the body moving in the right direction by taking old properties.
  83175. //Should be tested!
  83176. if (oldBody) {
  83177. ['force', 'torque', 'velocity', 'angularVelocity'].forEach(function (param) {
  83178. impostor.physicsBody[param].copy(oldBody[param]);
  83179. });
  83180. }
  83181. this._processChildMeshes(impostor);
  83182. }
  83183. //now update the body's transformation
  83184. this._updatePhysicsBodyTransformation(impostor);
  83185. };
  83186. CannonJSPlugin.prototype._processChildMeshes = function (mainImpostor) {
  83187. var _this = this;
  83188. var meshChildren = mainImpostor.object.getChildMeshes ? mainImpostor.object.getChildMeshes(true) : [];
  83189. var currentRotation = mainImpostor.object.rotationQuaternion;
  83190. if (meshChildren.length) {
  83191. var processMesh = function (localPosition, mesh) {
  83192. if (!currentRotation || !mesh.rotationQuaternion) {
  83193. return;
  83194. }
  83195. var childImpostor = mesh.getPhysicsImpostor();
  83196. if (childImpostor) {
  83197. var parent = childImpostor.parent;
  83198. if (parent !== mainImpostor) {
  83199. var pPosition = mesh.getAbsolutePosition().subtract(mainImpostor.object.getAbsolutePosition());
  83200. var localRotation = mesh.rotationQuaternion.multiply(BABYLON.Quaternion.Inverse(currentRotation));
  83201. if (childImpostor.physicsBody) {
  83202. _this.removePhysicsBody(childImpostor);
  83203. childImpostor.physicsBody = null;
  83204. }
  83205. childImpostor.parent = mainImpostor;
  83206. childImpostor.resetUpdateFlags();
  83207. 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));
  83208. //Add the mass of the children.
  83209. mainImpostor.physicsBody.mass += childImpostor.getParam("mass");
  83210. }
  83211. }
  83212. currentRotation.multiplyInPlace(mesh.rotationQuaternion);
  83213. mesh.getChildMeshes(true).filter(function (m) { return !!m.physicsImpostor; }).forEach(processMesh.bind(_this, mesh.getAbsolutePosition()));
  83214. };
  83215. meshChildren.filter(function (m) { return !!m.physicsImpostor; }).forEach(processMesh.bind(this, mainImpostor.object.getAbsolutePosition()));
  83216. }
  83217. };
  83218. CannonJSPlugin.prototype.removePhysicsBody = function (impostor) {
  83219. impostor.physicsBody.removeEventListener("collide", impostor.onCollide);
  83220. this.world.removeEventListener("preStep", impostor.beforeStep);
  83221. this.world.removeEventListener("postStep", impostor.afterStep);
  83222. this.world.remove(impostor.physicsBody);
  83223. };
  83224. CannonJSPlugin.prototype.generateJoint = function (impostorJoint) {
  83225. var mainBody = impostorJoint.mainImpostor.physicsBody;
  83226. var connectedBody = impostorJoint.connectedImpostor.physicsBody;
  83227. if (!mainBody || !connectedBody) {
  83228. return;
  83229. }
  83230. var constraint;
  83231. var jointData = impostorJoint.joint.jointData;
  83232. //TODO - https://github.com/schteppe/this.BJSCANNON.js/blob/gh-pages/demos/collisionFilter.html
  83233. var constraintData = {
  83234. pivotA: jointData.mainPivot ? new this.BJSCANNON.Vec3().copy(jointData.mainPivot) : null,
  83235. pivotB: jointData.connectedPivot ? new this.BJSCANNON.Vec3().copy(jointData.connectedPivot) : null,
  83236. axisA: jointData.mainAxis ? new this.BJSCANNON.Vec3().copy(jointData.mainAxis) : null,
  83237. axisB: jointData.connectedAxis ? new this.BJSCANNON.Vec3().copy(jointData.connectedAxis) : null,
  83238. maxForce: jointData.nativeParams.maxForce,
  83239. collideConnected: !!jointData.collision
  83240. };
  83241. switch (impostorJoint.joint.type) {
  83242. case BABYLON.PhysicsJoint.HingeJoint:
  83243. case BABYLON.PhysicsJoint.Hinge2Joint:
  83244. constraint = new this.BJSCANNON.HingeConstraint(mainBody, connectedBody, constraintData);
  83245. break;
  83246. case BABYLON.PhysicsJoint.DistanceJoint:
  83247. constraint = new this.BJSCANNON.DistanceConstraint(mainBody, connectedBody, jointData.maxDistance || 2);
  83248. break;
  83249. case BABYLON.PhysicsJoint.SpringJoint:
  83250. var springData = jointData;
  83251. constraint = new this.BJSCANNON.Spring(mainBody, connectedBody, {
  83252. restLength: springData.length,
  83253. stiffness: springData.stiffness,
  83254. damping: springData.damping,
  83255. localAnchorA: constraintData.pivotA,
  83256. localAnchorB: constraintData.pivotB
  83257. });
  83258. break;
  83259. case BABYLON.PhysicsJoint.LockJoint:
  83260. constraint = new this.BJSCANNON.LockConstraint(mainBody, connectedBody, constraintData);
  83261. break;
  83262. case BABYLON.PhysicsJoint.PointToPointJoint:
  83263. case BABYLON.PhysicsJoint.BallAndSocketJoint:
  83264. default:
  83265. constraint = new this.BJSCANNON.PointToPointConstraint(mainBody, constraintData.pivotA, connectedBody, constraintData.pivotA, constraintData.maxForce);
  83266. break;
  83267. }
  83268. //set the collideConnected flag after the creation, since DistanceJoint ignores it.
  83269. constraint.collideConnected = !!jointData.collision;
  83270. impostorJoint.joint.physicsJoint = constraint;
  83271. //don't add spring as constraint, as it is not one.
  83272. if (impostorJoint.joint.type !== BABYLON.PhysicsJoint.SpringJoint) {
  83273. this.world.addConstraint(constraint);
  83274. }
  83275. else {
  83276. impostorJoint.mainImpostor.registerAfterPhysicsStep(function () {
  83277. constraint.applyForce();
  83278. });
  83279. }
  83280. };
  83281. CannonJSPlugin.prototype.removeJoint = function (impostorJoint) {
  83282. this.world.removeConstraint(impostorJoint.joint.physicsJoint);
  83283. };
  83284. CannonJSPlugin.prototype._addMaterial = function (name, friction, restitution) {
  83285. var index;
  83286. var mat;
  83287. for (index = 0; index < this._physicsMaterials.length; index++) {
  83288. mat = this._physicsMaterials[index];
  83289. if (mat.friction === friction && mat.restitution === restitution) {
  83290. return mat;
  83291. }
  83292. }
  83293. var currentMat = new this.BJSCANNON.Material(name);
  83294. currentMat.friction = friction;
  83295. currentMat.restitution = restitution;
  83296. this._physicsMaterials.push(currentMat);
  83297. return currentMat;
  83298. };
  83299. CannonJSPlugin.prototype._checkWithEpsilon = function (value) {
  83300. return value < BABYLON.PhysicsEngine.Epsilon ? BABYLON.PhysicsEngine.Epsilon : value;
  83301. };
  83302. CannonJSPlugin.prototype._createShape = function (impostor) {
  83303. var object = impostor.object;
  83304. var returnValue;
  83305. var extendSize = impostor.getObjectExtendSize();
  83306. switch (impostor.type) {
  83307. case BABYLON.PhysicsImpostor.SphereImpostor:
  83308. var radiusX = extendSize.x;
  83309. var radiusY = extendSize.y;
  83310. var radiusZ = extendSize.z;
  83311. returnValue = new this.BJSCANNON.Sphere(Math.max(this._checkWithEpsilon(radiusX), this._checkWithEpsilon(radiusY), this._checkWithEpsilon(radiusZ)) / 2);
  83312. break;
  83313. //TMP also for cylinder - TODO Cannon supports cylinder natively.
  83314. case BABYLON.PhysicsImpostor.CylinderImpostor:
  83315. returnValue = new this.BJSCANNON.Cylinder(this._checkWithEpsilon(extendSize.x) / 2, this._checkWithEpsilon(extendSize.x) / 2, this._checkWithEpsilon(extendSize.y), 16);
  83316. break;
  83317. case BABYLON.PhysicsImpostor.BoxImpostor:
  83318. var box = extendSize.scale(0.5);
  83319. returnValue = new this.BJSCANNON.Box(new this.BJSCANNON.Vec3(this._checkWithEpsilon(box.x), this._checkWithEpsilon(box.y), this._checkWithEpsilon(box.z)));
  83320. break;
  83321. case BABYLON.PhysicsImpostor.PlaneImpostor:
  83322. BABYLON.Tools.Warn("Attention, PlaneImposter might not behave as you expect. Consider using BoxImposter instead");
  83323. returnValue = new this.BJSCANNON.Plane();
  83324. break;
  83325. case BABYLON.PhysicsImpostor.MeshImpostor:
  83326. // should transform the vertex data to world coordinates!!
  83327. var rawVerts = object.getVerticesData ? object.getVerticesData(BABYLON.VertexBuffer.PositionKind) : [];
  83328. var rawFaces = object.getIndices ? object.getIndices() : [];
  83329. if (!rawVerts)
  83330. return;
  83331. // get only scale! so the object could transform correctly.
  83332. var oldPosition = object.position.clone();
  83333. var oldRotation = object.rotation && object.rotation.clone();
  83334. var oldQuaternion = object.rotationQuaternion && object.rotationQuaternion.clone();
  83335. object.position.copyFromFloats(0, 0, 0);
  83336. object.rotation && object.rotation.copyFromFloats(0, 0, 0);
  83337. object.rotationQuaternion && object.rotationQuaternion.copyFrom(impostor.getParentsRotation());
  83338. object.rotationQuaternion && object.parent && object.rotationQuaternion.conjugateInPlace();
  83339. var transform = object.computeWorldMatrix(true);
  83340. // convert rawVerts to object space
  83341. var temp = new Array();
  83342. var index;
  83343. for (index = 0; index < rawVerts.length; index += 3) {
  83344. BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.FromArray(rawVerts, index), transform).toArray(temp, index);
  83345. }
  83346. BABYLON.Tools.Warn("MeshImpostor only collides against spheres.");
  83347. returnValue = new this.BJSCANNON.Trimesh(temp, rawFaces);
  83348. //now set back the transformation!
  83349. object.position.copyFrom(oldPosition);
  83350. oldRotation && object.rotation && object.rotation.copyFrom(oldRotation);
  83351. oldQuaternion && object.rotationQuaternion && object.rotationQuaternion.copyFrom(oldQuaternion);
  83352. break;
  83353. case BABYLON.PhysicsImpostor.HeightmapImpostor:
  83354. var oldPosition2 = object.position.clone();
  83355. var oldRotation2 = object.rotation && object.rotation.clone();
  83356. var oldQuaternion2 = object.rotationQuaternion && object.rotationQuaternion.clone();
  83357. object.position.copyFromFloats(0, 0, 0);
  83358. object.rotation && object.rotation.copyFromFloats(0, 0, 0);
  83359. object.rotationQuaternion && object.rotationQuaternion.copyFrom(impostor.getParentsRotation());
  83360. object.rotationQuaternion && object.parent && object.rotationQuaternion.conjugateInPlace();
  83361. object.rotationQuaternion && object.rotationQuaternion.multiplyInPlace(this._minus90X);
  83362. returnValue = this._createHeightmap(object);
  83363. object.position.copyFrom(oldPosition2);
  83364. oldRotation2 && object.rotation && object.rotation.copyFrom(oldRotation2);
  83365. oldQuaternion2 && object.rotationQuaternion && object.rotationQuaternion.copyFrom(oldQuaternion2);
  83366. object.computeWorldMatrix(true);
  83367. break;
  83368. case BABYLON.PhysicsImpostor.ParticleImpostor:
  83369. returnValue = new this.BJSCANNON.Particle();
  83370. break;
  83371. }
  83372. return returnValue;
  83373. };
  83374. CannonJSPlugin.prototype._createHeightmap = function (object, pointDepth) {
  83375. var pos = (object.getVerticesData(BABYLON.VertexBuffer.PositionKind));
  83376. var transform = object.computeWorldMatrix(true);
  83377. // convert rawVerts to object space
  83378. var temp = new Array();
  83379. var index;
  83380. for (index = 0; index < pos.length; index += 3) {
  83381. BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.FromArray(pos, index), transform).toArray(temp, index);
  83382. }
  83383. pos = temp;
  83384. var matrix = new Array();
  83385. //For now pointDepth will not be used and will be automatically calculated.
  83386. //Future reference - try and find the best place to add a reference to the pointDepth variable.
  83387. var arraySize = pointDepth || ~~(Math.sqrt(pos.length / 3) - 1);
  83388. var boundingInfo = object.getBoundingInfo();
  83389. var dim = Math.min(boundingInfo.boundingBox.extendSizeWorld.x, boundingInfo.boundingBox.extendSizeWorld.y);
  83390. var minY = boundingInfo.boundingBox.extendSizeWorld.z;
  83391. var elementSize = dim * 2 / arraySize;
  83392. for (var i = 0; i < pos.length; i = i + 3) {
  83393. var x = Math.round((pos[i + 0]) / elementSize + arraySize / 2);
  83394. var z = Math.round(((pos[i + 1]) / elementSize - arraySize / 2) * -1);
  83395. var y = -pos[i + 2] + minY;
  83396. if (!matrix[x]) {
  83397. matrix[x] = [];
  83398. }
  83399. if (!matrix[x][z]) {
  83400. matrix[x][z] = y;
  83401. }
  83402. matrix[x][z] = Math.max(y, matrix[x][z]);
  83403. }
  83404. for (var x = 0; x <= arraySize; ++x) {
  83405. if (!matrix[x]) {
  83406. var loc = 1;
  83407. while (!matrix[(x + loc) % arraySize]) {
  83408. loc++;
  83409. }
  83410. matrix[x] = matrix[(x + loc) % arraySize].slice();
  83411. //console.log("missing x", x);
  83412. }
  83413. for (var z = 0; z <= arraySize; ++z) {
  83414. if (!matrix[x][z]) {
  83415. var loc = 1;
  83416. var newValue;
  83417. while (newValue === undefined) {
  83418. newValue = matrix[x][(z + loc++) % arraySize];
  83419. }
  83420. matrix[x][z] = newValue;
  83421. }
  83422. }
  83423. }
  83424. var shape = new this.BJSCANNON.Heightfield(matrix, {
  83425. elementSize: elementSize
  83426. });
  83427. //For future reference, needed for body transformation
  83428. shape.minY = minY;
  83429. return shape;
  83430. };
  83431. CannonJSPlugin.prototype._updatePhysicsBodyTransformation = function (impostor) {
  83432. var object = impostor.object;
  83433. //make sure it is updated...
  83434. object.computeWorldMatrix && object.computeWorldMatrix(true);
  83435. // The delta between the mesh position and the mesh bounding box center
  83436. var bInfo = object.getBoundingInfo();
  83437. if (!bInfo)
  83438. return;
  83439. var center = impostor.getObjectCenter();
  83440. //m.getAbsolutePosition().subtract(m.getBoundingInfo().boundingBox.centerWorld)
  83441. this._tmpDeltaPosition.copyFrom(object.getAbsolutePivotPoint().subtract(center));
  83442. this._tmpDeltaPosition.divideInPlace(impostor.object.scaling);
  83443. this._tmpPosition.copyFrom(center);
  83444. var quaternion = object.rotationQuaternion;
  83445. if (!quaternion) {
  83446. return;
  83447. }
  83448. //is shape is a plane or a heightmap, it must be rotated 90 degs in the X axis.
  83449. if (impostor.type === BABYLON.PhysicsImpostor.PlaneImpostor || impostor.type === BABYLON.PhysicsImpostor.HeightmapImpostor || impostor.type === BABYLON.PhysicsImpostor.CylinderImpostor) {
  83450. //-90 DEG in X, precalculated
  83451. quaternion = quaternion.multiply(this._minus90X);
  83452. //Invert! (Precalculated, 90 deg in X)
  83453. //No need to clone. this will never change.
  83454. impostor.setDeltaRotation(this._plus90X);
  83455. }
  83456. //If it is a heightfield, if should be centered.
  83457. if (impostor.type === BABYLON.PhysicsImpostor.HeightmapImpostor) {
  83458. var mesh = object;
  83459. var boundingInfo = mesh.getBoundingInfo();
  83460. //calculate the correct body position:
  83461. var rotationQuaternion = mesh.rotationQuaternion;
  83462. mesh.rotationQuaternion = this._tmpUnityRotation;
  83463. mesh.computeWorldMatrix(true);
  83464. //get original center with no rotation
  83465. var c = center.clone();
  83466. var oldPivot = mesh.getPivotMatrix() || BABYLON.Matrix.Translation(0, 0, 0);
  83467. //calculate the new center using a pivot (since this.BJSCANNON.js doesn't center height maps)
  83468. var p = BABYLON.Matrix.Translation(boundingInfo.boundingBox.extendSizeWorld.x, 0, -boundingInfo.boundingBox.extendSizeWorld.z);
  83469. mesh.setPreTransformMatrix(p);
  83470. mesh.computeWorldMatrix(true);
  83471. //calculate the translation
  83472. var translation = boundingInfo.boundingBox.centerWorld.subtract(center).subtract(mesh.position).negate();
  83473. this._tmpPosition.copyFromFloats(translation.x, translation.y - boundingInfo.boundingBox.extendSizeWorld.y, translation.z);
  83474. //add it inverted to the delta
  83475. this._tmpDeltaPosition.copyFrom(boundingInfo.boundingBox.centerWorld.subtract(c));
  83476. this._tmpDeltaPosition.y += boundingInfo.boundingBox.extendSizeWorld.y;
  83477. //rotation is back
  83478. mesh.rotationQuaternion = rotationQuaternion;
  83479. mesh.setPreTransformMatrix(oldPivot);
  83480. mesh.computeWorldMatrix(true);
  83481. }
  83482. else if (impostor.type === BABYLON.PhysicsImpostor.MeshImpostor) {
  83483. this._tmpDeltaPosition.copyFromFloats(0, 0, 0);
  83484. //this._tmpPosition.copyFrom(object.position);
  83485. }
  83486. impostor.setDeltaPosition(this._tmpDeltaPosition);
  83487. //Now update the impostor object
  83488. impostor.physicsBody.position.copy(this._tmpPosition);
  83489. impostor.physicsBody.quaternion.copy(quaternion);
  83490. };
  83491. CannonJSPlugin.prototype.setTransformationFromPhysicsBody = function (impostor) {
  83492. impostor.object.position.copyFrom(impostor.physicsBody.position);
  83493. if (impostor.object.rotationQuaternion) {
  83494. impostor.object.rotationQuaternion.copyFrom(impostor.physicsBody.quaternion);
  83495. }
  83496. };
  83497. CannonJSPlugin.prototype.setPhysicsBodyTransformation = function (impostor, newPosition, newRotation) {
  83498. impostor.physicsBody.position.copy(newPosition);
  83499. impostor.physicsBody.quaternion.copy(newRotation);
  83500. };
  83501. CannonJSPlugin.prototype.isSupported = function () {
  83502. return this.BJSCANNON !== undefined;
  83503. };
  83504. CannonJSPlugin.prototype.setLinearVelocity = function (impostor, velocity) {
  83505. impostor.physicsBody.velocity.copy(velocity);
  83506. };
  83507. CannonJSPlugin.prototype.setAngularVelocity = function (impostor, velocity) {
  83508. impostor.physicsBody.angularVelocity.copy(velocity);
  83509. };
  83510. CannonJSPlugin.prototype.getLinearVelocity = function (impostor) {
  83511. var v = impostor.physicsBody.velocity;
  83512. if (!v) {
  83513. return null;
  83514. }
  83515. return new BABYLON.Vector3(v.x, v.y, v.z);
  83516. };
  83517. CannonJSPlugin.prototype.getAngularVelocity = function (impostor) {
  83518. var v = impostor.physicsBody.angularVelocity;
  83519. if (!v) {
  83520. return null;
  83521. }
  83522. return new BABYLON.Vector3(v.x, v.y, v.z);
  83523. };
  83524. CannonJSPlugin.prototype.setBodyMass = function (impostor, mass) {
  83525. impostor.physicsBody.mass = mass;
  83526. impostor.physicsBody.updateMassProperties();
  83527. };
  83528. CannonJSPlugin.prototype.getBodyMass = function (impostor) {
  83529. return impostor.physicsBody.mass;
  83530. };
  83531. CannonJSPlugin.prototype.getBodyFriction = function (impostor) {
  83532. return impostor.physicsBody.material.friction;
  83533. };
  83534. CannonJSPlugin.prototype.setBodyFriction = function (impostor, friction) {
  83535. impostor.physicsBody.material.friction = friction;
  83536. };
  83537. CannonJSPlugin.prototype.getBodyRestitution = function (impostor) {
  83538. return impostor.physicsBody.material.restitution;
  83539. };
  83540. CannonJSPlugin.prototype.setBodyRestitution = function (impostor, restitution) {
  83541. impostor.physicsBody.material.restitution = restitution;
  83542. };
  83543. CannonJSPlugin.prototype.sleepBody = function (impostor) {
  83544. impostor.physicsBody.sleep();
  83545. };
  83546. CannonJSPlugin.prototype.wakeUpBody = function (impostor) {
  83547. impostor.physicsBody.wakeUp();
  83548. };
  83549. CannonJSPlugin.prototype.updateDistanceJoint = function (joint, maxDistance, minDistance) {
  83550. joint.physicsJoint.distance = maxDistance;
  83551. };
  83552. // private enableMotor(joint: IMotorEnabledJoint, motorIndex?: number) {
  83553. // if (!motorIndex) {
  83554. // joint.physicsJoint.enableMotor();
  83555. // }
  83556. // }
  83557. // private disableMotor(joint: IMotorEnabledJoint, motorIndex?: number) {
  83558. // if (!motorIndex) {
  83559. // joint.physicsJoint.disableMotor();
  83560. // }
  83561. // }
  83562. CannonJSPlugin.prototype.setMotor = function (joint, speed, maxForce, motorIndex) {
  83563. if (!motorIndex) {
  83564. joint.physicsJoint.enableMotor();
  83565. joint.physicsJoint.setMotorSpeed(speed);
  83566. if (maxForce) {
  83567. this.setLimit(joint, maxForce);
  83568. }
  83569. }
  83570. };
  83571. CannonJSPlugin.prototype.setLimit = function (joint, upperLimit, lowerLimit) {
  83572. joint.physicsJoint.motorEquation.maxForce = upperLimit;
  83573. joint.physicsJoint.motorEquation.minForce = lowerLimit === void 0 ? -upperLimit : lowerLimit;
  83574. };
  83575. CannonJSPlugin.prototype.syncMeshWithImpostor = function (mesh, impostor) {
  83576. var body = impostor.physicsBody;
  83577. mesh.position.x = body.position.x;
  83578. mesh.position.y = body.position.y;
  83579. mesh.position.z = body.position.z;
  83580. if (mesh.rotationQuaternion) {
  83581. mesh.rotationQuaternion.x = body.quaternion.x;
  83582. mesh.rotationQuaternion.y = body.quaternion.y;
  83583. mesh.rotationQuaternion.z = body.quaternion.z;
  83584. mesh.rotationQuaternion.w = body.quaternion.w;
  83585. }
  83586. };
  83587. CannonJSPlugin.prototype.getRadius = function (impostor) {
  83588. var shape = impostor.physicsBody.shapes[0];
  83589. return shape.boundingSphereRadius;
  83590. };
  83591. CannonJSPlugin.prototype.getBoxSizeToRef = function (impostor, result) {
  83592. var shape = impostor.physicsBody.shapes[0];
  83593. result.x = shape.halfExtents.x * 2;
  83594. result.y = shape.halfExtents.y * 2;
  83595. result.z = shape.halfExtents.z * 2;
  83596. };
  83597. CannonJSPlugin.prototype.dispose = function () {
  83598. };
  83599. CannonJSPlugin.prototype._extendNamespace = function () {
  83600. //this will force cannon to execute at least one step when using interpolation
  83601. var step_tmp1 = new this.BJSCANNON.Vec3();
  83602. var Engine = this.BJSCANNON;
  83603. this.BJSCANNON.World.prototype.step = function (dt, timeSinceLastCalled, maxSubSteps) {
  83604. maxSubSteps = maxSubSteps || 10;
  83605. timeSinceLastCalled = timeSinceLastCalled || 0;
  83606. if (timeSinceLastCalled === 0) {
  83607. this.internalStep(dt);
  83608. this.time += dt;
  83609. }
  83610. else {
  83611. var internalSteps = Math.floor((this.time + timeSinceLastCalled) / dt) - Math.floor(this.time / dt);
  83612. internalSteps = Math.min(internalSteps, maxSubSteps) || 1;
  83613. var t0 = performance.now();
  83614. for (var i = 0; i !== internalSteps; i++) {
  83615. this.internalStep(dt);
  83616. if (performance.now() - t0 > dt * 1000) {
  83617. break;
  83618. }
  83619. }
  83620. this.time += timeSinceLastCalled;
  83621. var h = this.time % dt;
  83622. var h_div_dt = h / dt;
  83623. var interpvelo = step_tmp1;
  83624. var bodies = this.bodies;
  83625. for (var j = 0; j !== bodies.length; j++) {
  83626. var b = bodies[j];
  83627. if (b.type !== Engine.Body.STATIC && b.sleepState !== Engine.Body.SLEEPING) {
  83628. b.position.vsub(b.previousPosition, interpvelo);
  83629. interpvelo.scale(h_div_dt, interpvelo);
  83630. b.position.vadd(interpvelo, b.interpolatedPosition);
  83631. }
  83632. else {
  83633. b.interpolatedPosition.copy(b.position);
  83634. b.interpolatedQuaternion.copy(b.quaternion);
  83635. }
  83636. }
  83637. }
  83638. };
  83639. };
  83640. return CannonJSPlugin;
  83641. }());
  83642. BABYLON.CannonJSPlugin = CannonJSPlugin;
  83643. })(BABYLON || (BABYLON = {}));
  83644. //# sourceMappingURL=babylon.cannonJSPlugin.js.map
  83645. var BABYLON;
  83646. (function (BABYLON) {
  83647. var OimoJSPlugin = /** @class */ (function () {
  83648. function OimoJSPlugin(iterations) {
  83649. this.name = "OimoJSPlugin";
  83650. this._tmpImpostorsArray = [];
  83651. this._tmpPositionVector = BABYLON.Vector3.Zero();
  83652. this.BJSOIMO = OIMO;
  83653. this.world = new this.BJSOIMO.World({
  83654. iterations: iterations
  83655. });
  83656. this.world.clear();
  83657. }
  83658. OimoJSPlugin.prototype.setGravity = function (gravity) {
  83659. this.world.gravity.copy(gravity);
  83660. };
  83661. OimoJSPlugin.prototype.setTimeStep = function (timeStep) {
  83662. this.world.timeStep = timeStep;
  83663. };
  83664. OimoJSPlugin.prototype.getTimeStep = function () {
  83665. return this.world.timeStep;
  83666. };
  83667. OimoJSPlugin.prototype.executeStep = function (delta, impostors) {
  83668. var _this = this;
  83669. impostors.forEach(function (impostor) {
  83670. impostor.beforeStep();
  83671. });
  83672. this.world.step();
  83673. impostors.forEach(function (impostor) {
  83674. impostor.afterStep();
  83675. //update the ordered impostors array
  83676. _this._tmpImpostorsArray[impostor.uniqueId] = impostor;
  83677. });
  83678. //check for collisions
  83679. var contact = this.world.contacts;
  83680. while (contact !== null) {
  83681. if (contact.touching && !contact.body1.sleeping && !contact.body2.sleeping) {
  83682. contact = contact.next;
  83683. continue;
  83684. }
  83685. //is this body colliding with any other? get the impostor
  83686. var mainImpostor = this._tmpImpostorsArray[+contact.body1.name];
  83687. var collidingImpostor = this._tmpImpostorsArray[+contact.body2.name];
  83688. if (!mainImpostor || !collidingImpostor) {
  83689. contact = contact.next;
  83690. continue;
  83691. }
  83692. mainImpostor.onCollide({ body: collidingImpostor.physicsBody });
  83693. collidingImpostor.onCollide({ body: mainImpostor.physicsBody });
  83694. contact = contact.next;
  83695. }
  83696. };
  83697. OimoJSPlugin.prototype.applyImpulse = function (impostor, force, contactPoint) {
  83698. var mass = impostor.physicsBody.mass;
  83699. impostor.physicsBody.applyImpulse(contactPoint.scale(this.world.invScale), force.scale(this.world.invScale * mass));
  83700. };
  83701. OimoJSPlugin.prototype.applyForce = function (impostor, force, contactPoint) {
  83702. BABYLON.Tools.Warn("Oimo doesn't support applying force. Using impule instead.");
  83703. this.applyImpulse(impostor, force, contactPoint);
  83704. };
  83705. OimoJSPlugin.prototype.generatePhysicsBody = function (impostor) {
  83706. var _this = this;
  83707. //parent-child relationship. Does this impostor has a parent impostor?
  83708. if (impostor.parent) {
  83709. if (impostor.physicsBody) {
  83710. this.removePhysicsBody(impostor);
  83711. //TODO is that needed?
  83712. impostor.forceUpdate();
  83713. }
  83714. return;
  83715. }
  83716. if (impostor.isBodyInitRequired()) {
  83717. var bodyConfig = {
  83718. name: impostor.uniqueId,
  83719. //Oimo must have mass, also for static objects.
  83720. config: [impostor.getParam("mass") || 1, impostor.getParam("friction"), impostor.getParam("restitution")],
  83721. size: [],
  83722. type: [],
  83723. pos: [],
  83724. posShape: [],
  83725. rot: [],
  83726. rotShape: [],
  83727. move: impostor.getParam("mass") !== 0,
  83728. density: impostor.getParam("mass"),
  83729. friction: impostor.getParam("friction"),
  83730. restitution: impostor.getParam("restitution"),
  83731. //Supporting older versions of Oimo
  83732. world: this.world
  83733. };
  83734. var impostors = [impostor];
  83735. var addToArray = function (parent) {
  83736. if (!parent.getChildMeshes)
  83737. return;
  83738. parent.getChildMeshes().forEach(function (m) {
  83739. if (m.physicsImpostor) {
  83740. impostors.push(m.physicsImpostor);
  83741. //m.physicsImpostor._init();
  83742. }
  83743. });
  83744. };
  83745. addToArray(impostor.object);
  83746. var checkWithEpsilon_1 = function (value) {
  83747. return Math.max(value, BABYLON.PhysicsEngine.Epsilon);
  83748. };
  83749. impostors.forEach(function (i) {
  83750. if (!i.object.rotationQuaternion) {
  83751. return;
  83752. }
  83753. //get the correct bounding box
  83754. var oldQuaternion = i.object.rotationQuaternion;
  83755. var rot = oldQuaternion.toEulerAngles();
  83756. var extendSize = i.getObjectExtendSize();
  83757. var radToDeg = 57.295779513082320876;
  83758. if (i === impostor) {
  83759. var center = impostor.getObjectCenter();
  83760. impostor.object.getAbsolutePivotPoint().subtractToRef(center, _this._tmpPositionVector);
  83761. _this._tmpPositionVector.divideInPlace(impostor.object.scaling);
  83762. //Can also use Array.prototype.push.apply
  83763. bodyConfig.pos.push(center.x);
  83764. bodyConfig.pos.push(center.y);
  83765. bodyConfig.pos.push(center.z);
  83766. bodyConfig.posShape.push(0, 0, 0);
  83767. //tmp solution
  83768. bodyConfig.rot.push(rot.x * radToDeg);
  83769. bodyConfig.rot.push(rot.y * radToDeg);
  83770. bodyConfig.rot.push(rot.z * radToDeg);
  83771. bodyConfig.rotShape.push(0, 0, 0);
  83772. }
  83773. else {
  83774. var localPosition = i.object.getAbsolutePosition().subtract(impostor.object.getAbsolutePosition());
  83775. bodyConfig.posShape.push(localPosition.x);
  83776. bodyConfig.posShape.push(localPosition.y);
  83777. bodyConfig.posShape.push(localPosition.z);
  83778. bodyConfig.pos.push(0, 0, 0);
  83779. //tmp solution until https://github.com/lo-th/OIMO.js/pull/37 is merged
  83780. bodyConfig.rot.push(0);
  83781. bodyConfig.rot.push(0);
  83782. bodyConfig.rot.push(0);
  83783. bodyConfig.rotShape.push(rot.x * radToDeg);
  83784. bodyConfig.rotShape.push(rot.y * radToDeg);
  83785. bodyConfig.rotShape.push(rot.z * radToDeg);
  83786. }
  83787. // register mesh
  83788. switch (i.type) {
  83789. case BABYLON.PhysicsImpostor.ParticleImpostor:
  83790. BABYLON.Tools.Warn("No Particle support in OIMO.js. using SphereImpostor instead");
  83791. case BABYLON.PhysicsImpostor.SphereImpostor:
  83792. var radiusX = extendSize.x;
  83793. var radiusY = extendSize.y;
  83794. var radiusZ = extendSize.z;
  83795. var size = Math.max(checkWithEpsilon_1(radiusX), checkWithEpsilon_1(radiusY), checkWithEpsilon_1(radiusZ)) / 2;
  83796. bodyConfig.type.push('sphere');
  83797. //due to the way oimo works with compounds, add 3 times
  83798. bodyConfig.size.push(size);
  83799. bodyConfig.size.push(size);
  83800. bodyConfig.size.push(size);
  83801. break;
  83802. case BABYLON.PhysicsImpostor.CylinderImpostor:
  83803. var sizeX = checkWithEpsilon_1(extendSize.x) / 2;
  83804. var sizeY = checkWithEpsilon_1(extendSize.y);
  83805. bodyConfig.type.push('cylinder');
  83806. bodyConfig.size.push(sizeX);
  83807. bodyConfig.size.push(sizeY);
  83808. //due to the way oimo works with compounds, add one more value.
  83809. bodyConfig.size.push(sizeY);
  83810. break;
  83811. case BABYLON.PhysicsImpostor.PlaneImpostor:
  83812. case BABYLON.PhysicsImpostor.BoxImpostor:
  83813. default:
  83814. var sizeX = checkWithEpsilon_1(extendSize.x);
  83815. var sizeY = checkWithEpsilon_1(extendSize.y);
  83816. var sizeZ = checkWithEpsilon_1(extendSize.z);
  83817. bodyConfig.type.push('box');
  83818. //if (i === impostor) {
  83819. bodyConfig.size.push(sizeX);
  83820. bodyConfig.size.push(sizeY);
  83821. bodyConfig.size.push(sizeZ);
  83822. //} else {
  83823. // bodyConfig.size.push(0,0,0);
  83824. //}
  83825. break;
  83826. }
  83827. //actually not needed, but hey...
  83828. i.object.rotationQuaternion = oldQuaternion;
  83829. });
  83830. impostor.physicsBody = this.world.add(bodyConfig);
  83831. }
  83832. else {
  83833. this._tmpPositionVector.copyFromFloats(0, 0, 0);
  83834. }
  83835. impostor.setDeltaPosition(this._tmpPositionVector);
  83836. //this._tmpPositionVector.addInPlace(impostor.mesh.getBoundingInfo().boundingBox.center);
  83837. //this.setPhysicsBodyTransformation(impostor, this._tmpPositionVector, impostor.mesh.rotationQuaternion);
  83838. };
  83839. OimoJSPlugin.prototype.removePhysicsBody = function (impostor) {
  83840. //impostor.physicsBody.dispose();
  83841. //Same as : (older oimo versions)
  83842. this.world.removeRigidBody(impostor.physicsBody);
  83843. };
  83844. OimoJSPlugin.prototype.generateJoint = function (impostorJoint) {
  83845. var mainBody = impostorJoint.mainImpostor.physicsBody;
  83846. var connectedBody = impostorJoint.connectedImpostor.physicsBody;
  83847. if (!mainBody || !connectedBody) {
  83848. return;
  83849. }
  83850. var jointData = impostorJoint.joint.jointData;
  83851. var options = jointData.nativeParams || {};
  83852. var type;
  83853. var nativeJointData = {
  83854. body1: mainBody,
  83855. body2: connectedBody,
  83856. axe1: options.axe1 || (jointData.mainAxis ? jointData.mainAxis.asArray() : null),
  83857. axe2: options.axe2 || (jointData.connectedAxis ? jointData.connectedAxis.asArray() : null),
  83858. pos1: options.pos1 || (jointData.mainPivot ? jointData.mainPivot.asArray() : null),
  83859. pos2: options.pos2 || (jointData.connectedPivot ? jointData.connectedPivot.asArray() : null),
  83860. min: options.min,
  83861. max: options.max,
  83862. collision: options.collision || jointData.collision,
  83863. spring: options.spring,
  83864. //supporting older version of Oimo
  83865. world: this.world
  83866. };
  83867. switch (impostorJoint.joint.type) {
  83868. case BABYLON.PhysicsJoint.BallAndSocketJoint:
  83869. type = "jointBall";
  83870. break;
  83871. case BABYLON.PhysicsJoint.SpringJoint:
  83872. BABYLON.Tools.Warn("OIMO.js doesn't support Spring Constraint. Simulating using DistanceJoint instead");
  83873. var springData = jointData;
  83874. nativeJointData.min = springData.length || nativeJointData.min;
  83875. //Max should also be set, just make sure it is at least min
  83876. nativeJointData.max = Math.max(nativeJointData.min, nativeJointData.max);
  83877. case BABYLON.PhysicsJoint.DistanceJoint:
  83878. type = "jointDistance";
  83879. nativeJointData.max = jointData.maxDistance;
  83880. break;
  83881. case BABYLON.PhysicsJoint.PrismaticJoint:
  83882. type = "jointPrisme";
  83883. break;
  83884. case BABYLON.PhysicsJoint.SliderJoint:
  83885. type = "jointSlide";
  83886. break;
  83887. case BABYLON.PhysicsJoint.WheelJoint:
  83888. type = "jointWheel";
  83889. break;
  83890. case BABYLON.PhysicsJoint.HingeJoint:
  83891. default:
  83892. type = "jointHinge";
  83893. break;
  83894. }
  83895. nativeJointData.type = type;
  83896. impostorJoint.joint.physicsJoint = this.world.add(nativeJointData);
  83897. };
  83898. OimoJSPlugin.prototype.removeJoint = function (impostorJoint) {
  83899. //Bug in Oimo prevents us from disposing a joint in the playground
  83900. //joint.joint.physicsJoint.dispose();
  83901. //So we will bruteforce it!
  83902. try {
  83903. this.world.removeJoint(impostorJoint.joint.physicsJoint);
  83904. }
  83905. catch (e) {
  83906. BABYLON.Tools.Warn(e);
  83907. }
  83908. };
  83909. OimoJSPlugin.prototype.isSupported = function () {
  83910. return this.BJSOIMO !== undefined;
  83911. };
  83912. OimoJSPlugin.prototype.setTransformationFromPhysicsBody = function (impostor) {
  83913. if (!impostor.physicsBody.sleeping) {
  83914. //TODO check that
  83915. /*if (impostor.physicsBody.shapes.next) {
  83916. var parentShape = this._getLastShape(impostor.physicsBody);
  83917. impostor.object.position.copyFrom(parentShape.position);
  83918. console.log(parentShape.position);
  83919. } else {*/
  83920. impostor.object.position.copyFrom(impostor.physicsBody.getPosition());
  83921. //}
  83922. if (impostor.object.rotationQuaternion) {
  83923. impostor.object.rotationQuaternion.copyFrom(impostor.physicsBody.getQuaternion());
  83924. }
  83925. }
  83926. };
  83927. OimoJSPlugin.prototype.setPhysicsBodyTransformation = function (impostor, newPosition, newRotation) {
  83928. var body = impostor.physicsBody;
  83929. body.position.copy(newPosition);
  83930. body.orientation.copy(newRotation);
  83931. body.syncShapes();
  83932. body.awake();
  83933. };
  83934. /*private _getLastShape(body: any): any {
  83935. var lastShape = body.shapes;
  83936. while (lastShape.next) {
  83937. lastShape = lastShape.next;
  83938. }
  83939. return lastShape;
  83940. }*/
  83941. OimoJSPlugin.prototype.setLinearVelocity = function (impostor, velocity) {
  83942. impostor.physicsBody.linearVelocity.init(velocity.x, velocity.y, velocity.z);
  83943. };
  83944. OimoJSPlugin.prototype.setAngularVelocity = function (impostor, velocity) {
  83945. impostor.physicsBody.angularVelocity.init(velocity.x, velocity.y, velocity.z);
  83946. };
  83947. OimoJSPlugin.prototype.getLinearVelocity = function (impostor) {
  83948. var v = impostor.physicsBody.linearVelocity;
  83949. if (!v) {
  83950. return null;
  83951. }
  83952. return new BABYLON.Vector3(v.x, v.y, v.z);
  83953. };
  83954. OimoJSPlugin.prototype.getAngularVelocity = function (impostor) {
  83955. var v = impostor.physicsBody.angularVelocity;
  83956. if (!v) {
  83957. return null;
  83958. }
  83959. return new BABYLON.Vector3(v.x, v.y, v.z);
  83960. };
  83961. OimoJSPlugin.prototype.setBodyMass = function (impostor, mass) {
  83962. var staticBody = mass === 0;
  83963. //this will actually set the body's density and not its mass.
  83964. //But this is how oimo treats the mass variable.
  83965. impostor.physicsBody.shapes.density = staticBody ? 1 : mass;
  83966. impostor.physicsBody.setupMass(staticBody ? 0x2 : 0x1);
  83967. };
  83968. OimoJSPlugin.prototype.getBodyMass = function (impostor) {
  83969. return impostor.physicsBody.shapes.density;
  83970. };
  83971. OimoJSPlugin.prototype.getBodyFriction = function (impostor) {
  83972. return impostor.physicsBody.shapes.friction;
  83973. };
  83974. OimoJSPlugin.prototype.setBodyFriction = function (impostor, friction) {
  83975. impostor.physicsBody.shapes.friction = friction;
  83976. };
  83977. OimoJSPlugin.prototype.getBodyRestitution = function (impostor) {
  83978. return impostor.physicsBody.shapes.restitution;
  83979. };
  83980. OimoJSPlugin.prototype.setBodyRestitution = function (impostor, restitution) {
  83981. impostor.physicsBody.shapes.restitution = restitution;
  83982. };
  83983. OimoJSPlugin.prototype.sleepBody = function (impostor) {
  83984. impostor.physicsBody.sleep();
  83985. };
  83986. OimoJSPlugin.prototype.wakeUpBody = function (impostor) {
  83987. impostor.physicsBody.awake();
  83988. };
  83989. OimoJSPlugin.prototype.updateDistanceJoint = function (joint, maxDistance, minDistance) {
  83990. joint.physicsJoint.limitMotor.upperLimit = maxDistance;
  83991. if (minDistance !== void 0) {
  83992. joint.physicsJoint.limitMotor.lowerLimit = minDistance;
  83993. }
  83994. };
  83995. OimoJSPlugin.prototype.setMotor = function (joint, speed, maxForce, motorIndex) {
  83996. //TODO separate rotational and transational motors.
  83997. var motor = motorIndex ? joint.physicsJoint.rotationalLimitMotor2 : joint.physicsJoint.rotationalLimitMotor1 || joint.physicsJoint.rotationalLimitMotor || joint.physicsJoint.limitMotor;
  83998. if (motor) {
  83999. motor.setMotor(speed, maxForce);
  84000. }
  84001. };
  84002. OimoJSPlugin.prototype.setLimit = function (joint, upperLimit, lowerLimit, motorIndex) {
  84003. //TODO separate rotational and transational motors.
  84004. var motor = motorIndex ? joint.physicsJoint.rotationalLimitMotor2 : joint.physicsJoint.rotationalLimitMotor1 || joint.physicsJoint.rotationalLimitMotor || joint.physicsJoint.limitMotor;
  84005. if (motor) {
  84006. motor.setLimit(upperLimit, lowerLimit === void 0 ? -upperLimit : lowerLimit);
  84007. }
  84008. };
  84009. OimoJSPlugin.prototype.syncMeshWithImpostor = function (mesh, impostor) {
  84010. var body = impostor.physicsBody;
  84011. mesh.position.x = body.position.x;
  84012. mesh.position.y = body.position.y;
  84013. mesh.position.z = body.position.z;
  84014. if (mesh.rotationQuaternion) {
  84015. mesh.rotationQuaternion.x = body.orientation.x;
  84016. mesh.rotationQuaternion.y = body.orientation.y;
  84017. mesh.rotationQuaternion.z = body.orientation.z;
  84018. mesh.rotationQuaternion.w = body.orientation.s;
  84019. }
  84020. };
  84021. OimoJSPlugin.prototype.getRadius = function (impostor) {
  84022. return impostor.physicsBody.shapes.radius;
  84023. };
  84024. OimoJSPlugin.prototype.getBoxSizeToRef = function (impostor, result) {
  84025. var shape = impostor.physicsBody.shapes;
  84026. result.x = shape.halfWidth * 2;
  84027. result.y = shape.halfHeight * 2;
  84028. result.z = shape.halfDepth * 2;
  84029. };
  84030. OimoJSPlugin.prototype.dispose = function () {
  84031. this.world.clear();
  84032. };
  84033. return OimoJSPlugin;
  84034. }());
  84035. BABYLON.OimoJSPlugin = OimoJSPlugin;
  84036. })(BABYLON || (BABYLON = {}));
  84037. //# sourceMappingURL=babylon.oimoJSPlugin.js.map
  84038. var BABYLON;
  84039. (function (BABYLON) {
  84040. /*
  84041. * Based on jsTGALoader - Javascript loader for TGA file
  84042. * By Vincent Thibault
  84043. * @blog http://blog.robrowser.com/javascript-tga-loader.html
  84044. */
  84045. var TGATools = /** @class */ (function () {
  84046. function TGATools() {
  84047. }
  84048. TGATools.GetTGAHeader = function (data) {
  84049. var offset = 0;
  84050. var header = {
  84051. id_length: data[offset++],
  84052. colormap_type: data[offset++],
  84053. image_type: data[offset++],
  84054. colormap_index: data[offset++] | data[offset++] << 8,
  84055. colormap_length: data[offset++] | data[offset++] << 8,
  84056. colormap_size: data[offset++],
  84057. origin: [
  84058. data[offset++] | data[offset++] << 8,
  84059. data[offset++] | data[offset++] << 8
  84060. ],
  84061. width: data[offset++] | data[offset++] << 8,
  84062. height: data[offset++] | data[offset++] << 8,
  84063. pixel_size: data[offset++],
  84064. flags: data[offset++]
  84065. };
  84066. return header;
  84067. };
  84068. TGATools.UploadContent = function (gl, data) {
  84069. // Not enough data to contain header ?
  84070. if (data.length < 19) {
  84071. BABYLON.Tools.Error("Unable to load TGA file - Not enough data to contain header");
  84072. return;
  84073. }
  84074. // Read Header
  84075. var offset = 18;
  84076. var header = TGATools.GetTGAHeader(data);
  84077. // Assume it's a valid Targa file.
  84078. if (header.id_length + offset > data.length) {
  84079. BABYLON.Tools.Error("Unable to load TGA file - Not enough data");
  84080. return;
  84081. }
  84082. // Skip not needed data
  84083. offset += header.id_length;
  84084. var use_rle = false;
  84085. var use_pal = false;
  84086. var use_grey = false;
  84087. // Get some informations.
  84088. switch (header.image_type) {
  84089. case TGATools._TYPE_RLE_INDEXED:
  84090. use_rle = true;
  84091. case TGATools._TYPE_INDEXED:
  84092. use_pal = true;
  84093. break;
  84094. case TGATools._TYPE_RLE_RGB:
  84095. use_rle = true;
  84096. case TGATools._TYPE_RGB:
  84097. // use_rgb = true;
  84098. break;
  84099. case TGATools._TYPE_RLE_GREY:
  84100. use_rle = true;
  84101. case TGATools._TYPE_GREY:
  84102. use_grey = true;
  84103. break;
  84104. }
  84105. var pixel_data;
  84106. // var numAlphaBits = header.flags & 0xf;
  84107. var pixel_size = header.pixel_size >> 3;
  84108. var pixel_total = header.width * header.height * pixel_size;
  84109. // Read palettes
  84110. var palettes;
  84111. if (use_pal) {
  84112. palettes = data.subarray(offset, offset += header.colormap_length * (header.colormap_size >> 3));
  84113. }
  84114. // Read LRE
  84115. if (use_rle) {
  84116. pixel_data = new Uint8Array(pixel_total);
  84117. var c, count, i;
  84118. var localOffset = 0;
  84119. var pixels = new Uint8Array(pixel_size);
  84120. while (offset < pixel_total && localOffset < pixel_total) {
  84121. c = data[offset++];
  84122. count = (c & 0x7f) + 1;
  84123. // RLE pixels
  84124. if (c & 0x80) {
  84125. // Bind pixel tmp array
  84126. for (i = 0; i < pixel_size; ++i) {
  84127. pixels[i] = data[offset++];
  84128. }
  84129. // Copy pixel array
  84130. for (i = 0; i < count; ++i) {
  84131. pixel_data.set(pixels, localOffset + i * pixel_size);
  84132. }
  84133. localOffset += pixel_size * count;
  84134. }
  84135. // Raw pixels
  84136. else {
  84137. count *= pixel_size;
  84138. for (i = 0; i < count; ++i) {
  84139. pixel_data[localOffset + i] = data[offset++];
  84140. }
  84141. localOffset += count;
  84142. }
  84143. }
  84144. }
  84145. // RAW Pixels
  84146. else {
  84147. pixel_data = data.subarray(offset, offset += (use_pal ? header.width * header.height : pixel_total));
  84148. }
  84149. // Load to texture
  84150. var x_start, y_start, x_step, y_step, y_end, x_end;
  84151. switch ((header.flags & TGATools._ORIGIN_MASK) >> TGATools._ORIGIN_SHIFT) {
  84152. default:
  84153. case TGATools._ORIGIN_UL:
  84154. x_start = 0;
  84155. x_step = 1;
  84156. x_end = header.width;
  84157. y_start = 0;
  84158. y_step = 1;
  84159. y_end = header.height;
  84160. break;
  84161. case TGATools._ORIGIN_BL:
  84162. x_start = 0;
  84163. x_step = 1;
  84164. x_end = header.width;
  84165. y_start = header.height - 1;
  84166. y_step = -1;
  84167. y_end = -1;
  84168. break;
  84169. case TGATools._ORIGIN_UR:
  84170. x_start = header.width - 1;
  84171. x_step = -1;
  84172. x_end = -1;
  84173. y_start = 0;
  84174. y_step = 1;
  84175. y_end = header.height;
  84176. break;
  84177. case TGATools._ORIGIN_BR:
  84178. x_start = header.width - 1;
  84179. x_step = -1;
  84180. x_end = -1;
  84181. y_start = header.height - 1;
  84182. y_step = -1;
  84183. y_end = -1;
  84184. break;
  84185. }
  84186. // Load the specify method
  84187. var func = '_getImageData' + (use_grey ? 'Grey' : '') + (header.pixel_size) + 'bits';
  84188. var imageData = TGATools[func](header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end);
  84189. gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, header.width, header.height, 0, gl.RGBA, gl.UNSIGNED_BYTE, imageData);
  84190. };
  84191. TGATools._getImageData8bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  84192. var image = pixel_data, colormap = palettes;
  84193. var width = header.width, height = header.height;
  84194. var color, i = 0, x, y;
  84195. var imageData = new Uint8Array(width * height * 4);
  84196. for (y = y_start; y !== y_end; y += y_step) {
  84197. for (x = x_start; x !== x_end; x += x_step, i++) {
  84198. color = image[i];
  84199. imageData[(x + width * y) * 4 + 3] = 255;
  84200. imageData[(x + width * y) * 4 + 2] = colormap[(color * 3) + 0];
  84201. imageData[(x + width * y) * 4 + 1] = colormap[(color * 3) + 1];
  84202. imageData[(x + width * y) * 4 + 0] = colormap[(color * 3) + 2];
  84203. }
  84204. }
  84205. return imageData;
  84206. };
  84207. TGATools._getImageData16bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  84208. var image = pixel_data;
  84209. var width = header.width, height = header.height;
  84210. var color, i = 0, x, y;
  84211. var imageData = new Uint8Array(width * height * 4);
  84212. for (y = y_start; y !== y_end; y += y_step) {
  84213. for (x = x_start; x !== x_end; x += x_step, i += 2) {
  84214. color = image[i + 0] + (image[i + 1] << 8); // Inversed ?
  84215. var r = (((color & 0x7C00) >> 10) * 255) / 0x1F | 0;
  84216. var g = (((color & 0x03E0) >> 5) * 255) / 0x1F | 0;
  84217. var b = ((color & 0x001F) * 255) / 0x1F | 0;
  84218. imageData[(x + width * y) * 4 + 0] = r;
  84219. imageData[(x + width * y) * 4 + 1] = g;
  84220. imageData[(x + width * y) * 4 + 2] = b;
  84221. imageData[(x + width * y) * 4 + 3] = (color & 0x8000) ? 0 : 255;
  84222. }
  84223. }
  84224. return imageData;
  84225. };
  84226. TGATools._getImageData24bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  84227. var image = pixel_data;
  84228. var width = header.width, height = header.height;
  84229. var i = 0, x, y;
  84230. var imageData = new Uint8Array(width * height * 4);
  84231. for (y = y_start; y !== y_end; y += y_step) {
  84232. for (x = x_start; x !== x_end; x += x_step, i += 3) {
  84233. imageData[(x + width * y) * 4 + 3] = 255;
  84234. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  84235. imageData[(x + width * y) * 4 + 1] = image[i + 1];
  84236. imageData[(x + width * y) * 4 + 0] = image[i + 2];
  84237. }
  84238. }
  84239. return imageData;
  84240. };
  84241. TGATools._getImageData32bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  84242. var image = pixel_data;
  84243. var width = header.width, height = header.height;
  84244. var i = 0, x, y;
  84245. var imageData = new Uint8Array(width * height * 4);
  84246. for (y = y_start; y !== y_end; y += y_step) {
  84247. for (x = x_start; x !== x_end; x += x_step, i += 4) {
  84248. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  84249. imageData[(x + width * y) * 4 + 1] = image[i + 1];
  84250. imageData[(x + width * y) * 4 + 0] = image[i + 2];
  84251. imageData[(x + width * y) * 4 + 3] = image[i + 3];
  84252. }
  84253. }
  84254. return imageData;
  84255. };
  84256. TGATools._getImageDataGrey8bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  84257. var image = pixel_data;
  84258. var width = header.width, height = header.height;
  84259. var color, i = 0, x, y;
  84260. var imageData = new Uint8Array(width * height * 4);
  84261. for (y = y_start; y !== y_end; y += y_step) {
  84262. for (x = x_start; x !== x_end; x += x_step, i++) {
  84263. color = image[i];
  84264. imageData[(x + width * y) * 4 + 0] = color;
  84265. imageData[(x + width * y) * 4 + 1] = color;
  84266. imageData[(x + width * y) * 4 + 2] = color;
  84267. imageData[(x + width * y) * 4 + 3] = 255;
  84268. }
  84269. }
  84270. return imageData;
  84271. };
  84272. TGATools._getImageDataGrey16bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  84273. var image = pixel_data;
  84274. var width = header.width, height = header.height;
  84275. var i = 0, x, y;
  84276. var imageData = new Uint8Array(width * height * 4);
  84277. for (y = y_start; y !== y_end; y += y_step) {
  84278. for (x = x_start; x !== x_end; x += x_step, i += 2) {
  84279. imageData[(x + width * y) * 4 + 0] = image[i + 0];
  84280. imageData[(x + width * y) * 4 + 1] = image[i + 0];
  84281. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  84282. imageData[(x + width * y) * 4 + 3] = image[i + 1];
  84283. }
  84284. }
  84285. return imageData;
  84286. };
  84287. //private static _TYPE_NO_DATA = 0;
  84288. TGATools._TYPE_INDEXED = 1;
  84289. TGATools._TYPE_RGB = 2;
  84290. TGATools._TYPE_GREY = 3;
  84291. TGATools._TYPE_RLE_INDEXED = 9;
  84292. TGATools._TYPE_RLE_RGB = 10;
  84293. TGATools._TYPE_RLE_GREY = 11;
  84294. TGATools._ORIGIN_MASK = 0x30;
  84295. TGATools._ORIGIN_SHIFT = 0x04;
  84296. TGATools._ORIGIN_BL = 0x00;
  84297. TGATools._ORIGIN_BR = 0x01;
  84298. TGATools._ORIGIN_UL = 0x02;
  84299. TGATools._ORIGIN_UR = 0x03;
  84300. return TGATools;
  84301. }());
  84302. BABYLON.TGATools = TGATools;
  84303. })(BABYLON || (BABYLON = {}));
  84304. //# sourceMappingURL=babylon.tga.js.map
  84305. var BABYLON;
  84306. (function (BABYLON) {
  84307. // Based on demo done by Brandon Jones - http://media.tojicode.com/webgl-samples/dds.html
  84308. // All values and structures referenced from:
  84309. // http://msdn.microsoft.com/en-us/library/bb943991.aspx/
  84310. var DDS_MAGIC = 0x20534444;
  84311. var
  84312. //DDSD_CAPS = 0x1,
  84313. //DDSD_HEIGHT = 0x2,
  84314. //DDSD_WIDTH = 0x4,
  84315. //DDSD_PITCH = 0x8,
  84316. //DDSD_PIXELFORMAT = 0x1000,
  84317. DDSD_MIPMAPCOUNT = 0x20000;
  84318. //DDSD_LINEARSIZE = 0x80000,
  84319. //DDSD_DEPTH = 0x800000;
  84320. // var DDSCAPS_COMPLEX = 0x8,
  84321. // DDSCAPS_MIPMAP = 0x400000,
  84322. // DDSCAPS_TEXTURE = 0x1000;
  84323. var DDSCAPS2_CUBEMAP = 0x200;
  84324. // DDSCAPS2_CUBEMAP_POSITIVEX = 0x400,
  84325. // DDSCAPS2_CUBEMAP_NEGATIVEX = 0x800,
  84326. // DDSCAPS2_CUBEMAP_POSITIVEY = 0x1000,
  84327. // DDSCAPS2_CUBEMAP_NEGATIVEY = 0x2000,
  84328. // DDSCAPS2_CUBEMAP_POSITIVEZ = 0x4000,
  84329. // DDSCAPS2_CUBEMAP_NEGATIVEZ = 0x8000,
  84330. // DDSCAPS2_VOLUME = 0x200000;
  84331. var
  84332. //DDPF_ALPHAPIXELS = 0x1,
  84333. //DDPF_ALPHA = 0x2,
  84334. DDPF_FOURCC = 0x4, DDPF_RGB = 0x40,
  84335. //DDPF_YUV = 0x200,
  84336. DDPF_LUMINANCE = 0x20000;
  84337. function FourCCToInt32(value) {
  84338. return value.charCodeAt(0) +
  84339. (value.charCodeAt(1) << 8) +
  84340. (value.charCodeAt(2) << 16) +
  84341. (value.charCodeAt(3) << 24);
  84342. }
  84343. function Int32ToFourCC(value) {
  84344. return String.fromCharCode(value & 0xff, (value >> 8) & 0xff, (value >> 16) & 0xff, (value >> 24) & 0xff);
  84345. }
  84346. var FOURCC_DXT1 = FourCCToInt32("DXT1");
  84347. var FOURCC_DXT3 = FourCCToInt32("DXT3");
  84348. var FOURCC_DXT5 = FourCCToInt32("DXT5");
  84349. var FOURCC_DX10 = FourCCToInt32("DX10");
  84350. var FOURCC_D3DFMT_R16G16B16A16F = 113;
  84351. var FOURCC_D3DFMT_R32G32B32A32F = 116;
  84352. var DXGI_FORMAT_R16G16B16A16_FLOAT = 10;
  84353. var DXGI_FORMAT_B8G8R8X8_UNORM = 88;
  84354. var headerLengthInt = 31; // The header length in 32 bit ints
  84355. // Offsets into the header array
  84356. var off_magic = 0;
  84357. var off_size = 1;
  84358. var off_flags = 2;
  84359. var off_height = 3;
  84360. var off_width = 4;
  84361. var off_mipmapCount = 7;
  84362. var off_pfFlags = 20;
  84363. var off_pfFourCC = 21;
  84364. var off_RGBbpp = 22;
  84365. var off_RMask = 23;
  84366. var off_GMask = 24;
  84367. var off_BMask = 25;
  84368. var off_AMask = 26;
  84369. // var off_caps1 = 27;
  84370. var off_caps2 = 28;
  84371. // var off_caps3 = 29;
  84372. // var off_caps4 = 30;
  84373. var off_dxgiFormat = 32;
  84374. ;
  84375. var DDSTools = /** @class */ (function () {
  84376. function DDSTools() {
  84377. }
  84378. DDSTools.GetDDSInfo = function (arrayBuffer) {
  84379. var header = new Int32Array(arrayBuffer, 0, headerLengthInt);
  84380. var extendedHeader = new Int32Array(arrayBuffer, 0, headerLengthInt + 4);
  84381. var mipmapCount = 1;
  84382. if (header[off_flags] & DDSD_MIPMAPCOUNT) {
  84383. mipmapCount = Math.max(1, header[off_mipmapCount]);
  84384. }
  84385. var fourCC = header[off_pfFourCC];
  84386. var dxgiFormat = (fourCC === FOURCC_DX10) ? extendedHeader[off_dxgiFormat] : 0;
  84387. var textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  84388. switch (fourCC) {
  84389. case FOURCC_D3DFMT_R16G16B16A16F:
  84390. textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  84391. break;
  84392. case FOURCC_D3DFMT_R32G32B32A32F:
  84393. textureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  84394. break;
  84395. case FOURCC_DX10:
  84396. if (dxgiFormat === DXGI_FORMAT_R16G16B16A16_FLOAT) {
  84397. textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  84398. break;
  84399. }
  84400. }
  84401. return {
  84402. width: header[off_width],
  84403. height: header[off_height],
  84404. mipmapCount: mipmapCount,
  84405. isFourCC: (header[off_pfFlags] & DDPF_FOURCC) === DDPF_FOURCC,
  84406. isRGB: (header[off_pfFlags] & DDPF_RGB) === DDPF_RGB,
  84407. isLuminance: (header[off_pfFlags] & DDPF_LUMINANCE) === DDPF_LUMINANCE,
  84408. isCube: (header[off_caps2] & DDSCAPS2_CUBEMAP) === DDSCAPS2_CUBEMAP,
  84409. isCompressed: (fourCC === FOURCC_DXT1 || fourCC === FOURCC_DXT3 || fourCC === FOURCC_DXT5),
  84410. dxgiFormat: dxgiFormat,
  84411. textureType: textureType
  84412. };
  84413. };
  84414. DDSTools._ToHalfFloat = function (value) {
  84415. if (!DDSTools._FloatView) {
  84416. DDSTools._FloatView = new Float32Array(1);
  84417. DDSTools._Int32View = new Int32Array(DDSTools._FloatView.buffer);
  84418. }
  84419. DDSTools._FloatView[0] = value;
  84420. var x = DDSTools._Int32View[0];
  84421. var bits = (x >> 16) & 0x8000; /* Get the sign */
  84422. var m = (x >> 12) & 0x07ff; /* Keep one extra bit for rounding */
  84423. var e = (x >> 23) & 0xff; /* Using int is faster here */
  84424. /* If zero, or denormal, or exponent underflows too much for a denormal
  84425. * half, return signed zero. */
  84426. if (e < 103) {
  84427. return bits;
  84428. }
  84429. /* If NaN, return NaN. If Inf or exponent overflow, return Inf. */
  84430. if (e > 142) {
  84431. bits |= 0x7c00;
  84432. /* If exponent was 0xff and one mantissa bit was set, it means NaN,
  84433. * not Inf, so make sure we set one mantissa bit too. */
  84434. bits |= ((e == 255) ? 0 : 1) && (x & 0x007fffff);
  84435. return bits;
  84436. }
  84437. /* If exponent underflows but not too much, return a denormal */
  84438. if (e < 113) {
  84439. m |= 0x0800;
  84440. /* Extra rounding may overflow and set mantissa to 0 and exponent
  84441. * to 1, which is OK. */
  84442. bits |= (m >> (114 - e)) + ((m >> (113 - e)) & 1);
  84443. return bits;
  84444. }
  84445. bits |= ((e - 112) << 10) | (m >> 1);
  84446. bits += m & 1;
  84447. return bits;
  84448. };
  84449. DDSTools._FromHalfFloat = function (value) {
  84450. var s = (value & 0x8000) >> 15;
  84451. var e = (value & 0x7C00) >> 10;
  84452. var f = value & 0x03FF;
  84453. if (e === 0) {
  84454. return (s ? -1 : 1) * Math.pow(2, -14) * (f / Math.pow(2, 10));
  84455. }
  84456. else if (e == 0x1F) {
  84457. return f ? NaN : ((s ? -1 : 1) * Infinity);
  84458. }
  84459. return (s ? -1 : 1) * Math.pow(2, e - 15) * (1 + (f / Math.pow(2, 10)));
  84460. };
  84461. DDSTools._GetHalfFloatAsFloatRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, lod) {
  84462. var destArray = new Float32Array(dataLength);
  84463. var srcData = new Uint16Array(arrayBuffer, dataOffset);
  84464. var index = 0;
  84465. for (var y = 0; y < height; y++) {
  84466. for (var x = 0; x < width; x++) {
  84467. var srcPos = (x + y * width) * 4;
  84468. destArray[index] = DDSTools._FromHalfFloat(srcData[srcPos]);
  84469. destArray[index + 1] = DDSTools._FromHalfFloat(srcData[srcPos + 1]);
  84470. destArray[index + 2] = DDSTools._FromHalfFloat(srcData[srcPos + 2]);
  84471. if (DDSTools.StoreLODInAlphaChannel) {
  84472. destArray[index + 3] = lod;
  84473. }
  84474. else {
  84475. destArray[index + 3] = DDSTools._FromHalfFloat(srcData[srcPos + 3]);
  84476. }
  84477. index += 4;
  84478. }
  84479. }
  84480. return destArray;
  84481. };
  84482. DDSTools._GetHalfFloatRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, lod) {
  84483. if (DDSTools.StoreLODInAlphaChannel) {
  84484. var destArray = new Uint16Array(dataLength);
  84485. var srcData = new Uint16Array(arrayBuffer, dataOffset);
  84486. var index = 0;
  84487. for (var y = 0; y < height; y++) {
  84488. for (var x = 0; x < width; x++) {
  84489. var srcPos = (x + y * width) * 4;
  84490. destArray[index] = srcData[srcPos];
  84491. destArray[index + 1] = srcData[srcPos + 1];
  84492. destArray[index + 2] = srcData[srcPos + 2];
  84493. destArray[index + 3] = DDSTools._ToHalfFloat(lod);
  84494. index += 4;
  84495. }
  84496. }
  84497. return destArray;
  84498. }
  84499. return new Uint16Array(arrayBuffer, dataOffset, dataLength);
  84500. };
  84501. DDSTools._GetFloatRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, lod) {
  84502. if (DDSTools.StoreLODInAlphaChannel) {
  84503. var destArray = new Float32Array(dataLength);
  84504. var srcData = new Float32Array(arrayBuffer, dataOffset);
  84505. var index = 0;
  84506. for (var y = 0; y < height; y++) {
  84507. for (var x = 0; x < width; x++) {
  84508. var srcPos = (x + y * width) * 4;
  84509. destArray[index] = srcData[srcPos];
  84510. destArray[index + 1] = srcData[srcPos + 1];
  84511. destArray[index + 2] = srcData[srcPos + 2];
  84512. destArray[index + 3] = lod;
  84513. index += 4;
  84514. }
  84515. }
  84516. return destArray;
  84517. }
  84518. return new Float32Array(arrayBuffer, dataOffset, dataLength);
  84519. };
  84520. DDSTools._GetFloatAsUIntRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, lod) {
  84521. var destArray = new Uint8Array(dataLength);
  84522. var srcData = new Float32Array(arrayBuffer, dataOffset);
  84523. var index = 0;
  84524. for (var y = 0; y < height; y++) {
  84525. for (var x = 0; x < width; x++) {
  84526. var srcPos = (x + y * width) * 4;
  84527. destArray[index] = BABYLON.Scalar.Clamp(srcData[srcPos]) * 255;
  84528. destArray[index + 1] = BABYLON.Scalar.Clamp(srcData[srcPos + 1]) * 255;
  84529. destArray[index + 2] = BABYLON.Scalar.Clamp(srcData[srcPos + 2]) * 255;
  84530. if (DDSTools.StoreLODInAlphaChannel) {
  84531. destArray[index + 3] = lod;
  84532. }
  84533. else {
  84534. destArray[index + 3] = BABYLON.Scalar.Clamp(srcData[srcPos + 3]) * 255;
  84535. }
  84536. index += 4;
  84537. }
  84538. }
  84539. return destArray;
  84540. };
  84541. DDSTools._GetHalfFloatAsUIntRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, lod) {
  84542. var destArray = new Uint8Array(dataLength);
  84543. var srcData = new Uint16Array(arrayBuffer, dataOffset);
  84544. var index = 0;
  84545. for (var y = 0; y < height; y++) {
  84546. for (var x = 0; x < width; x++) {
  84547. var srcPos = (x + y * width) * 4;
  84548. destArray[index] = BABYLON.Scalar.Clamp(DDSTools._FromHalfFloat(srcData[srcPos])) * 255;
  84549. destArray[index + 1] = BABYLON.Scalar.Clamp(DDSTools._FromHalfFloat(srcData[srcPos + 1])) * 255;
  84550. destArray[index + 2] = BABYLON.Scalar.Clamp(DDSTools._FromHalfFloat(srcData[srcPos + 2])) * 255;
  84551. if (DDSTools.StoreLODInAlphaChannel) {
  84552. destArray[index + 3] = lod;
  84553. }
  84554. else {
  84555. destArray[index + 3] = BABYLON.Scalar.Clamp(DDSTools._FromHalfFloat(srcData[srcPos + 3])) * 255;
  84556. }
  84557. index += 4;
  84558. }
  84559. }
  84560. return destArray;
  84561. };
  84562. DDSTools._GetRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, rOffset, gOffset, bOffset, aOffset) {
  84563. var byteArray = new Uint8Array(dataLength);
  84564. var srcData = new Uint8Array(arrayBuffer, dataOffset);
  84565. var index = 0;
  84566. for (var y = 0; y < height; y++) {
  84567. for (var x = 0; x < width; x++) {
  84568. var srcPos = (x + y * width) * 4;
  84569. byteArray[index] = srcData[srcPos + rOffset];
  84570. byteArray[index + 1] = srcData[srcPos + gOffset];
  84571. byteArray[index + 2] = srcData[srcPos + bOffset];
  84572. byteArray[index + 3] = srcData[srcPos + aOffset];
  84573. index += 4;
  84574. }
  84575. }
  84576. return byteArray;
  84577. };
  84578. DDSTools._ExtractLongWordOrder = function (value) {
  84579. if (value === 0 || value === 255 || value === -16777216) {
  84580. return 0;
  84581. }
  84582. return 1 + DDSTools._ExtractLongWordOrder(value >> 8);
  84583. };
  84584. DDSTools._GetRGBArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, rOffset, gOffset, bOffset) {
  84585. var byteArray = new Uint8Array(dataLength);
  84586. var srcData = new Uint8Array(arrayBuffer, dataOffset);
  84587. var index = 0;
  84588. for (var y = 0; y < height; y++) {
  84589. for (var x = 0; x < width; x++) {
  84590. var srcPos = (x + y * width) * 3;
  84591. byteArray[index] = srcData[srcPos + rOffset];
  84592. byteArray[index + 1] = srcData[srcPos + gOffset];
  84593. byteArray[index + 2] = srcData[srcPos + bOffset];
  84594. index += 3;
  84595. }
  84596. }
  84597. return byteArray;
  84598. };
  84599. DDSTools._GetLuminanceArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer) {
  84600. var byteArray = new Uint8Array(dataLength);
  84601. var srcData = new Uint8Array(arrayBuffer, dataOffset);
  84602. var index = 0;
  84603. for (var y = 0; y < height; y++) {
  84604. for (var x = 0; x < width; x++) {
  84605. var srcPos = (x + y * width);
  84606. byteArray[index] = srcData[srcPos];
  84607. index++;
  84608. }
  84609. }
  84610. return byteArray;
  84611. };
  84612. DDSTools.UploadDDSLevels = function (engine, gl, arrayBuffer, info, loadMipmaps, faces, lodIndex, currentFace) {
  84613. if (lodIndex === void 0) { lodIndex = -1; }
  84614. var sphericalPolynomialFaces = null;
  84615. if (info.sphericalPolynomial) {
  84616. sphericalPolynomialFaces = new Array();
  84617. }
  84618. var ext = engine.getCaps().s3tc;
  84619. var header = new Int32Array(arrayBuffer, 0, headerLengthInt);
  84620. var fourCC, width, height, dataLength = 0, dataOffset;
  84621. var byteArray, mipmapCount, mip;
  84622. var internalFormat = 0;
  84623. var format = 0;
  84624. var blockBytes = 1;
  84625. if (header[off_magic] !== DDS_MAGIC) {
  84626. BABYLON.Tools.Error("Invalid magic number in DDS header");
  84627. return;
  84628. }
  84629. if (!info.isFourCC && !info.isRGB && !info.isLuminance) {
  84630. BABYLON.Tools.Error("Unsupported format, must contain a FourCC, RGB or LUMINANCE code");
  84631. return;
  84632. }
  84633. if (info.isCompressed && !ext) {
  84634. BABYLON.Tools.Error("Compressed textures are not supported on this platform.");
  84635. return;
  84636. }
  84637. var bpp = header[off_RGBbpp];
  84638. dataOffset = header[off_size] + 4;
  84639. var computeFormats = false;
  84640. if (info.isFourCC) {
  84641. fourCC = header[off_pfFourCC];
  84642. switch (fourCC) {
  84643. case FOURCC_DXT1:
  84644. blockBytes = 8;
  84645. internalFormat = ext.COMPRESSED_RGBA_S3TC_DXT1_EXT;
  84646. break;
  84647. case FOURCC_DXT3:
  84648. blockBytes = 16;
  84649. internalFormat = ext.COMPRESSED_RGBA_S3TC_DXT3_EXT;
  84650. break;
  84651. case FOURCC_DXT5:
  84652. blockBytes = 16;
  84653. internalFormat = ext.COMPRESSED_RGBA_S3TC_DXT5_EXT;
  84654. break;
  84655. case FOURCC_D3DFMT_R16G16B16A16F:
  84656. computeFormats = true;
  84657. break;
  84658. case FOURCC_D3DFMT_R32G32B32A32F:
  84659. computeFormats = true;
  84660. break;
  84661. case FOURCC_DX10:
  84662. // There is an additionnal header so dataOffset need to be changed
  84663. dataOffset += 5 * 4; // 5 uints
  84664. var supported = false;
  84665. switch (info.dxgiFormat) {
  84666. case DXGI_FORMAT_R16G16B16A16_FLOAT:
  84667. computeFormats = true;
  84668. supported = true;
  84669. break;
  84670. case DXGI_FORMAT_B8G8R8X8_UNORM:
  84671. info.isRGB = true;
  84672. info.isFourCC = false;
  84673. bpp = 32;
  84674. supported = true;
  84675. break;
  84676. }
  84677. if (supported) {
  84678. break;
  84679. }
  84680. default:
  84681. console.error("Unsupported FourCC code:", Int32ToFourCC(fourCC));
  84682. return;
  84683. }
  84684. }
  84685. var rOffset = DDSTools._ExtractLongWordOrder(header[off_RMask]);
  84686. var gOffset = DDSTools._ExtractLongWordOrder(header[off_GMask]);
  84687. var bOffset = DDSTools._ExtractLongWordOrder(header[off_BMask]);
  84688. var aOffset = DDSTools._ExtractLongWordOrder(header[off_AMask]);
  84689. if (computeFormats) {
  84690. format = engine._getWebGLTextureType(info.textureType);
  84691. internalFormat = engine._getRGBABufferInternalSizedFormat(info.textureType);
  84692. }
  84693. mipmapCount = 1;
  84694. if (header[off_flags] & DDSD_MIPMAPCOUNT && loadMipmaps !== false) {
  84695. mipmapCount = Math.max(1, header[off_mipmapCount]);
  84696. }
  84697. for (var face = 0; face < faces; face++) {
  84698. var sampler = faces === 1 ? gl.TEXTURE_2D : (gl.TEXTURE_CUBE_MAP_POSITIVE_X + face + (currentFace ? currentFace : 0));
  84699. width = header[off_width];
  84700. height = header[off_height];
  84701. for (mip = 0; mip < mipmapCount; ++mip) {
  84702. if (lodIndex === -1 || lodIndex === mip) {
  84703. // In case of fixed LOD, if the lod has just been uploaded, early exit.
  84704. var i = (lodIndex === -1) ? mip : 0;
  84705. if (!info.isCompressed && info.isFourCC) {
  84706. dataLength = width * height * 4;
  84707. var floatArray = null;
  84708. if (engine._badOS || engine._badDesktopOS || (!engine.getCaps().textureHalfFloat && !engine.getCaps().textureFloat)) { // Required because iOS has many issues with float and half float generation
  84709. if (bpp === 128) {
  84710. floatArray = DDSTools._GetFloatAsUIntRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i);
  84711. if (sphericalPolynomialFaces && i == 0) {
  84712. sphericalPolynomialFaces.push(DDSTools._GetFloatRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i));
  84713. }
  84714. }
  84715. else if (bpp === 64) {
  84716. floatArray = DDSTools._GetHalfFloatAsUIntRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i);
  84717. if (sphericalPolynomialFaces && i == 0) {
  84718. sphericalPolynomialFaces.push(DDSTools._GetHalfFloatAsFloatRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i));
  84719. }
  84720. }
  84721. info.textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  84722. format = engine._getWebGLTextureType(info.textureType);
  84723. internalFormat = engine._getRGBABufferInternalSizedFormat(info.textureType);
  84724. }
  84725. else {
  84726. if (bpp === 128) {
  84727. floatArray = DDSTools._GetFloatRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i);
  84728. if (sphericalPolynomialFaces && i == 0) {
  84729. sphericalPolynomialFaces.push(floatArray);
  84730. }
  84731. }
  84732. else if (bpp === 64 && !engine.getCaps().textureHalfFloat) {
  84733. floatArray = DDSTools._GetHalfFloatAsFloatRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i);
  84734. if (sphericalPolynomialFaces && i == 0) {
  84735. sphericalPolynomialFaces.push(floatArray);
  84736. }
  84737. info.textureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  84738. format = engine._getWebGLTextureType(info.textureType);
  84739. internalFormat = engine._getRGBABufferInternalSizedFormat(info.textureType);
  84740. }
  84741. else { // 64
  84742. floatArray = DDSTools._GetHalfFloatRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i);
  84743. if (sphericalPolynomialFaces && i == 0) {
  84744. sphericalPolynomialFaces.push(DDSTools._GetHalfFloatAsFloatRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i));
  84745. }
  84746. }
  84747. }
  84748. if (floatArray) {
  84749. engine._uploadDataToTexture(sampler, i, internalFormat, width, height, gl.RGBA, format, floatArray);
  84750. }
  84751. }
  84752. else if (info.isRGB) {
  84753. if (bpp === 24) {
  84754. dataLength = width * height * 3;
  84755. byteArray = DDSTools._GetRGBArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, rOffset, gOffset, bOffset);
  84756. engine._uploadDataToTexture(sampler, i, gl.RGB, width, height, gl.RGB, gl.UNSIGNED_BYTE, byteArray);
  84757. }
  84758. else { // 32
  84759. dataLength = width * height * 4;
  84760. byteArray = DDSTools._GetRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, rOffset, gOffset, bOffset, aOffset);
  84761. engine._uploadDataToTexture(sampler, i, gl.RGBA, width, height, gl.RGBA, gl.UNSIGNED_BYTE, byteArray);
  84762. }
  84763. }
  84764. else if (info.isLuminance) {
  84765. var unpackAlignment = gl.getParameter(gl.UNPACK_ALIGNMENT);
  84766. var unpaddedRowSize = width;
  84767. var paddedRowSize = Math.floor((width + unpackAlignment - 1) / unpackAlignment) * unpackAlignment;
  84768. dataLength = paddedRowSize * (height - 1) + unpaddedRowSize;
  84769. byteArray = DDSTools._GetLuminanceArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer);
  84770. engine._uploadDataToTexture(sampler, i, gl.LUMINANCE, width, height, gl.LUMINANCE, gl.UNSIGNED_BYTE, byteArray);
  84771. }
  84772. else {
  84773. dataLength = Math.max(4, width) / 4 * Math.max(4, height) / 4 * blockBytes;
  84774. byteArray = new Uint8Array(arrayBuffer, dataOffset, dataLength);
  84775. engine._uploadCompressedDataToTexture(sampler, i, internalFormat, width, height, byteArray);
  84776. }
  84777. }
  84778. dataOffset += bpp ? (width * height * (bpp / 8)) : dataLength;
  84779. width *= 0.5;
  84780. height *= 0.5;
  84781. width = Math.max(1.0, width);
  84782. height = Math.max(1.0, height);
  84783. }
  84784. if (currentFace !== undefined) {
  84785. // Loading a single face
  84786. break;
  84787. }
  84788. }
  84789. if (sphericalPolynomialFaces && sphericalPolynomialFaces.length > 0) {
  84790. info.sphericalPolynomial = BABYLON.CubeMapToSphericalPolynomialTools.ConvertCubeMapToSphericalPolynomial({
  84791. size: header[off_width],
  84792. right: sphericalPolynomialFaces[0],
  84793. left: sphericalPolynomialFaces[1],
  84794. up: sphericalPolynomialFaces[2],
  84795. down: sphericalPolynomialFaces[3],
  84796. front: sphericalPolynomialFaces[4],
  84797. back: sphericalPolynomialFaces[5],
  84798. format: BABYLON.Engine.TEXTUREFORMAT_RGBA,
  84799. type: BABYLON.Engine.TEXTURETYPE_FLOAT,
  84800. gammaSpace: false,
  84801. });
  84802. }
  84803. else {
  84804. info.sphericalPolynomial = undefined;
  84805. }
  84806. };
  84807. DDSTools.StoreLODInAlphaChannel = false;
  84808. return DDSTools;
  84809. }());
  84810. BABYLON.DDSTools = DDSTools;
  84811. })(BABYLON || (BABYLON = {}));
  84812. //# sourceMappingURL=babylon.dds.js.map
  84813. var BABYLON;
  84814. (function (BABYLON) {
  84815. /**
  84816. * for description see https://www.khronos.org/opengles/sdk/tools/KTX/
  84817. * for file layout see https://www.khronos.org/opengles/sdk/tools/KTX/file_format_spec/
  84818. */
  84819. var KhronosTextureContainer = /** @class */ (function () {
  84820. /**
  84821. * @param {ArrayBuffer} arrayBuffer- contents of the KTX container file
  84822. * @param {number} facesExpected- should be either 1 or 6, based whether a cube texture or or
  84823. * @param {boolean} threeDExpected- provision for indicating that data should be a 3D texture, not implemented
  84824. * @param {boolean} textureArrayExpected- provision for indicating that data should be a texture array, not implemented
  84825. */
  84826. function KhronosTextureContainer(arrayBuffer, facesExpected, threeDExpected, textureArrayExpected) {
  84827. this.arrayBuffer = arrayBuffer;
  84828. // Test that it is a ktx formatted file, based on the first 12 bytes, character representation is:
  84829. // '�', 'K', 'T', 'X', ' ', '1', '1', '�', '\r', '\n', '\x1A', '\n'
  84830. // 0xAB, 0x4B, 0x54, 0x58, 0x20, 0x31, 0x31, 0xBB, 0x0D, 0x0A, 0x1A, 0x0A
  84831. var identifier = new Uint8Array(this.arrayBuffer, 0, 12);
  84832. if (identifier[0] !== 0xAB || identifier[1] !== 0x4B || identifier[2] !== 0x54 || identifier[3] !== 0x58 || identifier[4] !== 0x20 || identifier[5] !== 0x31 ||
  84833. identifier[6] !== 0x31 || identifier[7] !== 0xBB || identifier[8] !== 0x0D || identifier[9] !== 0x0A || identifier[10] !== 0x1A || identifier[11] !== 0x0A) {
  84834. BABYLON.Tools.Error("texture missing KTX identifier");
  84835. return;
  84836. }
  84837. // load the reset of the header in native 32 bit int
  84838. var header = new Int32Array(this.arrayBuffer, 12, 13);
  84839. // determine of the remaining header values are recorded in the opposite endianness & require conversion
  84840. var oppositeEndianess = header[0] === 0x01020304;
  84841. // read all the header elements in order they exist in the file, without modification (sans endainness)
  84842. this.glType = oppositeEndianess ? this.switchEndainness(header[1]) : header[1]; // must be 0 for compressed textures
  84843. this.glTypeSize = oppositeEndianess ? this.switchEndainness(header[2]) : header[2]; // must be 1 for compressed textures
  84844. this.glFormat = oppositeEndianess ? this.switchEndainness(header[3]) : header[3]; // must be 0 for compressed textures
  84845. this.glInternalFormat = oppositeEndianess ? this.switchEndainness(header[4]) : header[4]; // the value of arg passed to gl.compressedTexImage2D(,,x,,,,)
  84846. this.glBaseInternalFormat = oppositeEndianess ? this.switchEndainness(header[5]) : header[5]; // specify GL_RGB, GL_RGBA, GL_ALPHA, etc (un-compressed only)
  84847. this.pixelWidth = oppositeEndianess ? this.switchEndainness(header[6]) : header[6]; // level 0 value of arg passed to gl.compressedTexImage2D(,,,x,,,)
  84848. this.pixelHeight = oppositeEndianess ? this.switchEndainness(header[7]) : header[7]; // level 0 value of arg passed to gl.compressedTexImage2D(,,,,x,,)
  84849. this.pixelDepth = oppositeEndianess ? this.switchEndainness(header[8]) : header[8]; // level 0 value of arg passed to gl.compressedTexImage3D(,,,,,x,,)
  84850. this.numberOfArrayElements = oppositeEndianess ? this.switchEndainness(header[9]) : header[9]; // used for texture arrays
  84851. this.numberOfFaces = oppositeEndianess ? this.switchEndainness(header[10]) : header[10]; // used for cubemap textures, should either be 1 or 6
  84852. this.numberOfMipmapLevels = oppositeEndianess ? this.switchEndainness(header[11]) : header[11]; // number of levels; disregard possibility of 0 for compressed textures
  84853. this.bytesOfKeyValueData = oppositeEndianess ? this.switchEndainness(header[12]) : header[12]; // the amount of space after the header for meta-data
  84854. // Make sure we have a compressed type. Not only reduces work, but probably better to let dev know they are not compressing.
  84855. if (this.glType !== 0) {
  84856. BABYLON.Tools.Error("only compressed formats currently supported");
  84857. return;
  84858. }
  84859. else {
  84860. // value of zero is an indication to generate mipmaps @ runtime. Not usually allowed for compressed, so disregard.
  84861. this.numberOfMipmapLevels = Math.max(1, this.numberOfMipmapLevels);
  84862. }
  84863. if (this.pixelHeight === 0 || this.pixelDepth !== 0) {
  84864. BABYLON.Tools.Error("only 2D textures currently supported");
  84865. return;
  84866. }
  84867. if (this.numberOfArrayElements !== 0) {
  84868. BABYLON.Tools.Error("texture arrays not currently supported");
  84869. return;
  84870. }
  84871. if (this.numberOfFaces !== facesExpected) {
  84872. BABYLON.Tools.Error("number of faces expected" + facesExpected + ", but found " + this.numberOfFaces);
  84873. return;
  84874. }
  84875. // we now have a completely validated file, so could use existence of loadType as success
  84876. // would need to make this more elaborate & adjust checks above to support more than one load type
  84877. this.loadType = KhronosTextureContainer.COMPRESSED_2D;
  84878. }
  84879. // not as fast hardware based, but will probably never need to use
  84880. KhronosTextureContainer.prototype.switchEndainness = function (val) {
  84881. return ((val & 0xFF) << 24)
  84882. | ((val & 0xFF00) << 8)
  84883. | ((val >> 8) & 0xFF00)
  84884. | ((val >> 24) & 0xFF);
  84885. };
  84886. /**
  84887. * It is assumed that the texture has already been created & is currently bound
  84888. */
  84889. KhronosTextureContainer.prototype.uploadLevels = function (gl, loadMipmaps) {
  84890. switch (this.loadType) {
  84891. case KhronosTextureContainer.COMPRESSED_2D:
  84892. this._upload2DCompressedLevels(gl, loadMipmaps);
  84893. break;
  84894. case KhronosTextureContainer.TEX_2D:
  84895. case KhronosTextureContainer.COMPRESSED_3D:
  84896. case KhronosTextureContainer.TEX_3D:
  84897. }
  84898. };
  84899. KhronosTextureContainer.prototype._upload2DCompressedLevels = function (gl, loadMipmaps) {
  84900. // initialize width & height for level 1
  84901. var dataOffset = KhronosTextureContainer.HEADER_LEN + this.bytesOfKeyValueData;
  84902. var width = this.pixelWidth;
  84903. var height = this.pixelHeight;
  84904. var mipmapCount = loadMipmaps ? this.numberOfMipmapLevels : 1;
  84905. for (var level = 0; level < mipmapCount; level++) {
  84906. var imageSize = new Int32Array(this.arrayBuffer, dataOffset, 1)[0]; // size per face, since not supporting array cubemaps
  84907. for (var face = 0; face < this.numberOfFaces; face++) {
  84908. var sampler = this.numberOfFaces === 1 ? gl.TEXTURE_2D : (gl.TEXTURE_CUBE_MAP_POSITIVE_X + face);
  84909. var byteArray = new Uint8Array(this.arrayBuffer, dataOffset + 4, imageSize);
  84910. gl.compressedTexImage2D(sampler, level, this.glInternalFormat, width, height, 0, byteArray);
  84911. dataOffset += imageSize + 4; // size of the image + 4 for the imageSize field
  84912. dataOffset += 3 - ((imageSize + 3) % 4); // add padding for odd sized image
  84913. }
  84914. width = Math.max(1.0, width * 0.5);
  84915. height = Math.max(1.0, height * 0.5);
  84916. }
  84917. };
  84918. KhronosTextureContainer.HEADER_LEN = 12 + (13 * 4); // identifier + header elements (not including key value meta-data pairs)
  84919. // load types
  84920. KhronosTextureContainer.COMPRESSED_2D = 0; // uses a gl.compressedTexImage2D()
  84921. KhronosTextureContainer.COMPRESSED_3D = 1; // uses a gl.compressedTexImage3D()
  84922. KhronosTextureContainer.TEX_2D = 2; // uses a gl.texImage2D()
  84923. KhronosTextureContainer.TEX_3D = 3; // uses a gl.texImage3D()
  84924. return KhronosTextureContainer;
  84925. }());
  84926. BABYLON.KhronosTextureContainer = KhronosTextureContainer;
  84927. })(BABYLON || (BABYLON = {}));
  84928. //# sourceMappingURL=babylon.khronosTextureContainer.js.map
  84929. var BABYLON;
  84930. (function (BABYLON) {
  84931. var Debug;
  84932. (function (Debug) {
  84933. /**
  84934. * Demo available here: http://www.babylonjs-playground.com/#1BZJVJ#8
  84935. */
  84936. var SkeletonViewer = /** @class */ (function () {
  84937. function SkeletonViewer(skeleton, mesh, scene, autoUpdateBonesMatrices, renderingGroupId) {
  84938. if (autoUpdateBonesMatrices === void 0) { autoUpdateBonesMatrices = true; }
  84939. if (renderingGroupId === void 0) { renderingGroupId = 1; }
  84940. this.skeleton = skeleton;
  84941. this.mesh = mesh;
  84942. this.autoUpdateBonesMatrices = autoUpdateBonesMatrices;
  84943. this.renderingGroupId = renderingGroupId;
  84944. this.color = BABYLON.Color3.White();
  84945. this._debugLines = new Array();
  84946. this._isEnabled = false;
  84947. this._scene = scene;
  84948. this.update();
  84949. this._renderFunction = this.update.bind(this);
  84950. }
  84951. Object.defineProperty(SkeletonViewer.prototype, "isEnabled", {
  84952. get: function () {
  84953. return this._isEnabled;
  84954. },
  84955. set: function (value) {
  84956. if (this._isEnabled === value) {
  84957. return;
  84958. }
  84959. this._isEnabled = value;
  84960. if (value) {
  84961. this._scene.registerBeforeRender(this._renderFunction);
  84962. }
  84963. else {
  84964. this._scene.unregisterBeforeRender(this._renderFunction);
  84965. }
  84966. },
  84967. enumerable: true,
  84968. configurable: true
  84969. });
  84970. SkeletonViewer.prototype._getBonePosition = function (position, bone, meshMat, x, y, z) {
  84971. if (x === void 0) { x = 0; }
  84972. if (y === void 0) { y = 0; }
  84973. if (z === void 0) { z = 0; }
  84974. var tmat = BABYLON.Tmp.Matrix[0];
  84975. var parentBone = bone.getParent();
  84976. tmat.copyFrom(bone.getLocalMatrix());
  84977. if (x !== 0 || y !== 0 || z !== 0) {
  84978. var tmat2 = BABYLON.Tmp.Matrix[1];
  84979. BABYLON.Matrix.IdentityToRef(tmat2);
  84980. tmat2.m[12] = x;
  84981. tmat2.m[13] = y;
  84982. tmat2.m[14] = z;
  84983. tmat2.multiplyToRef(tmat, tmat);
  84984. }
  84985. if (parentBone) {
  84986. tmat.multiplyToRef(parentBone.getAbsoluteTransform(), tmat);
  84987. }
  84988. tmat.multiplyToRef(meshMat, tmat);
  84989. position.x = tmat.m[12];
  84990. position.y = tmat.m[13];
  84991. position.z = tmat.m[14];
  84992. };
  84993. SkeletonViewer.prototype._getLinesForBonesWithLength = function (bones, meshMat) {
  84994. var len = bones.length;
  84995. var meshPos = this.mesh.position;
  84996. for (var i = 0; i < len; i++) {
  84997. var bone = bones[i];
  84998. var points = this._debugLines[i];
  84999. if (!points) {
  85000. points = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  85001. this._debugLines[i] = points;
  85002. }
  85003. this._getBonePosition(points[0], bone, meshMat);
  85004. this._getBonePosition(points[1], bone, meshMat, 0, bone.length, 0);
  85005. points[0].subtractInPlace(meshPos);
  85006. points[1].subtractInPlace(meshPos);
  85007. }
  85008. };
  85009. SkeletonViewer.prototype._getLinesForBonesNoLength = function (bones, meshMat) {
  85010. var len = bones.length;
  85011. var boneNum = 0;
  85012. var meshPos = this.mesh.position;
  85013. for (var i = len - 1; i >= 0; i--) {
  85014. var childBone = bones[i];
  85015. var parentBone = childBone.getParent();
  85016. if (!parentBone) {
  85017. continue;
  85018. }
  85019. var points = this._debugLines[boneNum];
  85020. if (!points) {
  85021. points = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  85022. this._debugLines[boneNum] = points;
  85023. }
  85024. childBone.getAbsolutePositionToRef(this.mesh, points[0]);
  85025. parentBone.getAbsolutePositionToRef(this.mesh, points[1]);
  85026. points[0].subtractInPlace(meshPos);
  85027. points[1].subtractInPlace(meshPos);
  85028. boneNum++;
  85029. }
  85030. };
  85031. SkeletonViewer.prototype.update = function () {
  85032. if (this.autoUpdateBonesMatrices) {
  85033. this.skeleton.computeAbsoluteTransforms();
  85034. }
  85035. if (this.skeleton.bones[0].length === undefined) {
  85036. this._getLinesForBonesNoLength(this.skeleton.bones, this.mesh.getWorldMatrix());
  85037. }
  85038. else {
  85039. this._getLinesForBonesWithLength(this.skeleton.bones, this.mesh.getWorldMatrix());
  85040. }
  85041. if (!this._debugMesh) {
  85042. this._debugMesh = BABYLON.MeshBuilder.CreateLineSystem("", { lines: this._debugLines, updatable: true, instance: null }, this._scene);
  85043. this._debugMesh.renderingGroupId = this.renderingGroupId;
  85044. }
  85045. else {
  85046. BABYLON.MeshBuilder.CreateLineSystem("", { lines: this._debugLines, updatable: true, instance: this._debugMesh }, this._scene);
  85047. }
  85048. this._debugMesh.position.copyFrom(this.mesh.position);
  85049. this._debugMesh.color = this.color;
  85050. };
  85051. SkeletonViewer.prototype.dispose = function () {
  85052. if (this._debugMesh) {
  85053. this.isEnabled = false;
  85054. this._debugMesh.dispose();
  85055. this._debugMesh = null;
  85056. }
  85057. };
  85058. return SkeletonViewer;
  85059. }());
  85060. Debug.SkeletonViewer = SkeletonViewer;
  85061. })(Debug = BABYLON.Debug || (BABYLON.Debug = {}));
  85062. })(BABYLON || (BABYLON = {}));
  85063. //# sourceMappingURL=babylon.skeletonViewer.js.map
  85064. /**
  85065. * Module Debug contains the (visual) components to debug a scene correctly
  85066. */
  85067. var BABYLON;
  85068. (function (BABYLON) {
  85069. var Debug;
  85070. (function (Debug) {
  85071. /**
  85072. * The Axes viewer will show 3 axes in a specific point in space
  85073. */
  85074. var AxesViewer = /** @class */ (function () {
  85075. function AxesViewer(scene, scaleLines) {
  85076. if (scaleLines === void 0) { scaleLines = 1; }
  85077. this._xline = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  85078. this._yline = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  85079. this._zline = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  85080. this.scaleLines = 1;
  85081. this.scaleLines = scaleLines;
  85082. this._xmesh = BABYLON.Mesh.CreateLines("xline", this._xline, scene, true);
  85083. this._ymesh = BABYLON.Mesh.CreateLines("yline", this._yline, scene, true);
  85084. this._zmesh = BABYLON.Mesh.CreateLines("zline", this._zline, scene, true);
  85085. this._xmesh.renderingGroupId = 2;
  85086. this._ymesh.renderingGroupId = 2;
  85087. this._zmesh.renderingGroupId = 2;
  85088. this._xmesh.material.checkReadyOnlyOnce = true;
  85089. this._xmesh.color = new BABYLON.Color3(1, 0, 0);
  85090. this._ymesh.material.checkReadyOnlyOnce = true;
  85091. this._ymesh.color = new BABYLON.Color3(0, 1, 0);
  85092. this._zmesh.material.checkReadyOnlyOnce = true;
  85093. this._zmesh.color = new BABYLON.Color3(0, 0, 1);
  85094. this.scene = scene;
  85095. }
  85096. AxesViewer.prototype.update = function (position, xaxis, yaxis, zaxis) {
  85097. var scaleLines = this.scaleLines;
  85098. if (this._xmesh) {
  85099. this._xmesh.position.copyFrom(position);
  85100. }
  85101. if (this._ymesh) {
  85102. this._ymesh.position.copyFrom(position);
  85103. }
  85104. if (this._zmesh) {
  85105. this._zmesh.position.copyFrom(position);
  85106. }
  85107. var point2 = this._xline[1];
  85108. point2.x = xaxis.x * scaleLines;
  85109. point2.y = xaxis.y * scaleLines;
  85110. point2.z = xaxis.z * scaleLines;
  85111. BABYLON.Mesh.CreateLines("", this._xline, null, false, this._xmesh);
  85112. point2 = this._yline[1];
  85113. point2.x = yaxis.x * scaleLines;
  85114. point2.y = yaxis.y * scaleLines;
  85115. point2.z = yaxis.z * scaleLines;
  85116. BABYLON.Mesh.CreateLines("", this._yline, null, false, this._ymesh);
  85117. point2 = this._zline[1];
  85118. point2.x = zaxis.x * scaleLines;
  85119. point2.y = zaxis.y * scaleLines;
  85120. point2.z = zaxis.z * scaleLines;
  85121. BABYLON.Mesh.CreateLines("", this._zline, null, false, this._zmesh);
  85122. };
  85123. AxesViewer.prototype.dispose = function () {
  85124. if (this._xmesh) {
  85125. this._xmesh.dispose();
  85126. }
  85127. if (this._ymesh) {
  85128. this._ymesh.dispose();
  85129. }
  85130. if (this._zmesh) {
  85131. this._zmesh.dispose();
  85132. }
  85133. this._xmesh = null;
  85134. this._ymesh = null;
  85135. this._zmesh = null;
  85136. this.scene = null;
  85137. };
  85138. return AxesViewer;
  85139. }());
  85140. Debug.AxesViewer = AxesViewer;
  85141. })(Debug = BABYLON.Debug || (BABYLON.Debug = {}));
  85142. })(BABYLON || (BABYLON = {}));
  85143. //# sourceMappingURL=babylon.axesViewer.js.map
  85144. var BABYLON;
  85145. (function (BABYLON) {
  85146. var Debug;
  85147. (function (Debug) {
  85148. /**
  85149. * The BoneAxesViewer will attach 3 axes to a specific bone of a specific mesh
  85150. */
  85151. var BoneAxesViewer = /** @class */ (function (_super) {
  85152. __extends(BoneAxesViewer, _super);
  85153. function BoneAxesViewer(scene, bone, mesh, scaleLines) {
  85154. if (scaleLines === void 0) { scaleLines = 1; }
  85155. var _this = _super.call(this, scene, scaleLines) || this;
  85156. _this.pos = BABYLON.Vector3.Zero();
  85157. _this.xaxis = BABYLON.Vector3.Zero();
  85158. _this.yaxis = BABYLON.Vector3.Zero();
  85159. _this.zaxis = BABYLON.Vector3.Zero();
  85160. _this.mesh = mesh;
  85161. _this.bone = bone;
  85162. return _this;
  85163. }
  85164. BoneAxesViewer.prototype.update = function () {
  85165. if (!this.mesh || !this.bone) {
  85166. return;
  85167. }
  85168. var bone = this.bone;
  85169. bone.getAbsolutePositionToRef(this.mesh, this.pos);
  85170. bone.getDirectionToRef(BABYLON.Axis.X, this.mesh, this.xaxis);
  85171. bone.getDirectionToRef(BABYLON.Axis.Y, this.mesh, this.yaxis);
  85172. bone.getDirectionToRef(BABYLON.Axis.Z, this.mesh, this.zaxis);
  85173. _super.prototype.update.call(this, this.pos, this.xaxis, this.yaxis, this.zaxis);
  85174. };
  85175. BoneAxesViewer.prototype.dispose = function () {
  85176. if (this.mesh) {
  85177. this.mesh = null;
  85178. this.bone = null;
  85179. _super.prototype.dispose.call(this);
  85180. }
  85181. };
  85182. return BoneAxesViewer;
  85183. }(Debug.AxesViewer));
  85184. Debug.BoneAxesViewer = BoneAxesViewer;
  85185. })(Debug = BABYLON.Debug || (BABYLON.Debug = {}));
  85186. })(BABYLON || (BABYLON = {}));
  85187. //# sourceMappingURL=babylon.boneAxesViewer.js.map
  85188. var BABYLON;
  85189. (function (BABYLON) {
  85190. var RayHelper = /** @class */ (function () {
  85191. function RayHelper(ray) {
  85192. this.ray = ray;
  85193. }
  85194. RayHelper.CreateAndShow = function (ray, scene, color) {
  85195. var helper = new RayHelper(ray);
  85196. helper.show(scene, color);
  85197. return helper;
  85198. };
  85199. RayHelper.prototype.show = function (scene, color) {
  85200. if (!this._renderFunction && this.ray) {
  85201. var ray = this.ray;
  85202. this._renderFunction = this._render.bind(this);
  85203. this._scene = scene;
  85204. this._renderPoints = [ray.origin, ray.origin.add(ray.direction.scale(ray.length))];
  85205. this._renderLine = BABYLON.Mesh.CreateLines("ray", this._renderPoints, scene, true);
  85206. if (this._renderFunction) {
  85207. this._scene.registerBeforeRender(this._renderFunction);
  85208. }
  85209. }
  85210. if (color && this._renderLine) {
  85211. this._renderLine.color.copyFrom(color);
  85212. }
  85213. };
  85214. RayHelper.prototype.hide = function () {
  85215. if (this._renderFunction && this._scene) {
  85216. this._scene.unregisterBeforeRender(this._renderFunction);
  85217. this._scene = null;
  85218. this._renderFunction = null;
  85219. if (this._renderLine) {
  85220. this._renderLine.dispose();
  85221. this._renderLine = null;
  85222. }
  85223. this._renderPoints = [];
  85224. }
  85225. };
  85226. RayHelper.prototype._render = function () {
  85227. var ray = this.ray;
  85228. if (!ray) {
  85229. return;
  85230. }
  85231. var point = this._renderPoints[1];
  85232. var len = Math.min(ray.length, 1000000);
  85233. point.copyFrom(ray.direction);
  85234. point.scaleInPlace(len);
  85235. point.addInPlace(ray.origin);
  85236. BABYLON.Mesh.CreateLines("ray", this._renderPoints, this._scene, true, this._renderLine);
  85237. };
  85238. RayHelper.prototype.attachToMesh = function (mesh, meshSpaceDirection, meshSpaceOrigin, length) {
  85239. this._attachedToMesh = mesh;
  85240. var ray = this.ray;
  85241. if (!ray) {
  85242. return;
  85243. }
  85244. if (!ray.direction) {
  85245. ray.direction = BABYLON.Vector3.Zero();
  85246. }
  85247. if (!ray.origin) {
  85248. ray.origin = BABYLON.Vector3.Zero();
  85249. }
  85250. if (length) {
  85251. ray.length = length;
  85252. }
  85253. if (!meshSpaceOrigin) {
  85254. meshSpaceOrigin = BABYLON.Vector3.Zero();
  85255. }
  85256. if (!meshSpaceDirection) {
  85257. // -1 so that this will work with Mesh.lookAt
  85258. meshSpaceDirection = new BABYLON.Vector3(0, 0, -1);
  85259. }
  85260. if (!this._meshSpaceDirection) {
  85261. this._meshSpaceDirection = meshSpaceDirection.clone();
  85262. this._meshSpaceOrigin = meshSpaceOrigin.clone();
  85263. }
  85264. else {
  85265. this._meshSpaceDirection.copyFrom(meshSpaceDirection);
  85266. this._meshSpaceOrigin.copyFrom(meshSpaceOrigin);
  85267. }
  85268. if (!this._updateToMeshFunction) {
  85269. this._updateToMeshFunction = this._updateToMesh.bind(this);
  85270. this._attachedToMesh.getScene().registerBeforeRender(this._updateToMeshFunction);
  85271. }
  85272. this._updateToMesh();
  85273. };
  85274. RayHelper.prototype.detachFromMesh = function () {
  85275. if (this._attachedToMesh) {
  85276. if (this._updateToMeshFunction) {
  85277. this._attachedToMesh.getScene().unregisterBeforeRender(this._updateToMeshFunction);
  85278. }
  85279. this._attachedToMesh = null;
  85280. this._updateToMeshFunction = null;
  85281. }
  85282. };
  85283. RayHelper.prototype._updateToMesh = function () {
  85284. var ray = this.ray;
  85285. if (!this._attachedToMesh || !ray) {
  85286. return;
  85287. }
  85288. if (this._attachedToMesh._isDisposed) {
  85289. this.detachFromMesh();
  85290. return;
  85291. }
  85292. this._attachedToMesh.getDirectionToRef(this._meshSpaceDirection, ray.direction);
  85293. BABYLON.Vector3.TransformCoordinatesToRef(this._meshSpaceOrigin, this._attachedToMesh.getWorldMatrix(), ray.origin);
  85294. };
  85295. RayHelper.prototype.dispose = function () {
  85296. this.hide();
  85297. this.detachFromMesh();
  85298. this.ray = null;
  85299. };
  85300. return RayHelper;
  85301. }());
  85302. BABYLON.RayHelper = RayHelper;
  85303. })(BABYLON || (BABYLON = {}));
  85304. //# sourceMappingURL=babylon.rayHelper.js.map
  85305. var BABYLON;
  85306. (function (BABYLON) {
  85307. // load the inspector using require, if not present in the global namespace.
  85308. var DebugLayer = /** @class */ (function () {
  85309. function DebugLayer(scene) {
  85310. this.BJSINSPECTOR = typeof INSPECTOR !== 'undefined' ? INSPECTOR : undefined;
  85311. this._scene = scene;
  85312. // load inspector using require, if it doesn't exist on the global namespace.
  85313. }
  85314. /** Creates the inspector window. */
  85315. DebugLayer.prototype._createInspector = function (config) {
  85316. if (config === void 0) { config = {}; }
  85317. var popup = config.popup || false;
  85318. var initialTab = config.initialTab || 0;
  85319. var parentElement = config.parentElement || null;
  85320. if (!this._inspector) {
  85321. this.BJSINSPECTOR = this.BJSINSPECTOR || typeof INSPECTOR !== 'undefined' ? INSPECTOR : undefined;
  85322. this._inspector = new this.BJSINSPECTOR.Inspector(this._scene, popup, initialTab, parentElement, config.newColors);
  85323. } // else nothing to do,; instance is already existing
  85324. };
  85325. DebugLayer.prototype.isVisible = function () {
  85326. if (!this._inspector) {
  85327. return false;
  85328. }
  85329. return true;
  85330. };
  85331. DebugLayer.prototype.hide = function () {
  85332. if (this._inspector) {
  85333. try {
  85334. this._inspector.dispose();
  85335. }
  85336. catch (e) {
  85337. // If the inspector has been removed directly from the inspector tool
  85338. }
  85339. this._inspector = null;
  85340. }
  85341. };
  85342. DebugLayer.prototype.show = function (config) {
  85343. if (config === void 0) { config = {}; }
  85344. if (typeof this.BJSINSPECTOR == 'undefined') {
  85345. // Load inspector and add it to the DOM
  85346. BABYLON.Tools.LoadScript(DebugLayer.InspectorURL, this._createInspector.bind(this, config));
  85347. }
  85348. else {
  85349. // Otherwise creates the inspector
  85350. this._createInspector(config);
  85351. }
  85352. };
  85353. DebugLayer.InspectorURL = 'https://preview.babylonjs.com/inspector/babylon.inspector.bundle.js';
  85354. return DebugLayer;
  85355. }());
  85356. BABYLON.DebugLayer = DebugLayer;
  85357. })(BABYLON || (BABYLON = {}));
  85358. //# sourceMappingURL=babylon.debugLayer.js.map
  85359. var BABYLON;
  85360. (function (BABYLON) {
  85361. var Debug;
  85362. (function (Debug) {
  85363. /**
  85364. * Used to show the physics impostor around the specific mesh.
  85365. */
  85366. var PhysicsViewer = /** @class */ (function () {
  85367. function PhysicsViewer(scene) {
  85368. this._impostors = [];
  85369. this._meshes = [];
  85370. this._numMeshes = 0;
  85371. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  85372. var physicEngine = this._scene.getPhysicsEngine();
  85373. if (physicEngine) {
  85374. this._physicsEnginePlugin = physicEngine.getPhysicsPlugin();
  85375. }
  85376. }
  85377. PhysicsViewer.prototype._updateDebugMeshes = function () {
  85378. var plugin = this._physicsEnginePlugin;
  85379. for (var i = 0; i < this._numMeshes; i++) {
  85380. var impostor = this._impostors[i];
  85381. if (!impostor) {
  85382. continue;
  85383. }
  85384. if (impostor.isDisposed) {
  85385. this.hideImpostor(this._impostors[i--]);
  85386. }
  85387. else {
  85388. var mesh = this._meshes[i];
  85389. if (mesh && plugin) {
  85390. plugin.syncMeshWithImpostor(mesh, impostor);
  85391. }
  85392. }
  85393. }
  85394. };
  85395. PhysicsViewer.prototype.showImpostor = function (impostor) {
  85396. if (!this._scene) {
  85397. return;
  85398. }
  85399. for (var i = 0; i < this._numMeshes; i++) {
  85400. if (this._impostors[i] == impostor) {
  85401. return;
  85402. }
  85403. }
  85404. var debugMesh = this._getDebugMesh(impostor, this._scene);
  85405. if (debugMesh) {
  85406. this._impostors[this._numMeshes] = impostor;
  85407. this._meshes[this._numMeshes] = debugMesh;
  85408. if (this._numMeshes === 0) {
  85409. this._renderFunction = this._updateDebugMeshes.bind(this);
  85410. this._scene.registerBeforeRender(this._renderFunction);
  85411. }
  85412. this._numMeshes++;
  85413. }
  85414. };
  85415. PhysicsViewer.prototype.hideImpostor = function (impostor) {
  85416. if (!impostor || !this._scene) {
  85417. return;
  85418. }
  85419. var removed = false;
  85420. for (var i = 0; i < this._numMeshes; i++) {
  85421. if (this._impostors[i] == impostor) {
  85422. var mesh = this._meshes[i];
  85423. if (!mesh) {
  85424. continue;
  85425. }
  85426. this._scene.removeMesh(mesh);
  85427. mesh.dispose();
  85428. this._numMeshes--;
  85429. if (this._numMeshes > 0) {
  85430. this._meshes[i] = this._meshes[this._numMeshes];
  85431. this._impostors[i] = this._impostors[this._numMeshes];
  85432. this._meshes[this._numMeshes] = null;
  85433. this._impostors[this._numMeshes] = null;
  85434. }
  85435. else {
  85436. this._meshes[0] = null;
  85437. this._impostors[0] = null;
  85438. }
  85439. removed = true;
  85440. break;
  85441. }
  85442. }
  85443. if (removed && this._numMeshes === 0) {
  85444. this._scene.unregisterBeforeRender(this._renderFunction);
  85445. }
  85446. };
  85447. PhysicsViewer.prototype._getDebugMaterial = function (scene) {
  85448. if (!this._debugMaterial) {
  85449. this._debugMaterial = new BABYLON.StandardMaterial('', scene);
  85450. this._debugMaterial.wireframe = true;
  85451. }
  85452. return this._debugMaterial;
  85453. };
  85454. PhysicsViewer.prototype._getDebugBoxMesh = function (scene) {
  85455. if (!this._debugBoxMesh) {
  85456. this._debugBoxMesh = BABYLON.MeshBuilder.CreateBox('physicsBodyBoxViewMesh', { size: 1 }, scene);
  85457. this._debugBoxMesh.renderingGroupId = 1;
  85458. this._debugBoxMesh.rotationQuaternion = BABYLON.Quaternion.Identity();
  85459. this._debugBoxMesh.material = this._getDebugMaterial(scene);
  85460. scene.removeMesh(this._debugBoxMesh);
  85461. }
  85462. return this._debugBoxMesh.createInstance('physicsBodyBoxViewInstance');
  85463. };
  85464. PhysicsViewer.prototype._getDebugSphereMesh = function (scene) {
  85465. if (!this._debugSphereMesh) {
  85466. this._debugSphereMesh = BABYLON.MeshBuilder.CreateSphere('physicsBodySphereViewMesh', { diameter: 1 }, scene);
  85467. this._debugSphereMesh.renderingGroupId = 1;
  85468. this._debugSphereMesh.rotationQuaternion = BABYLON.Quaternion.Identity();
  85469. this._debugSphereMesh.material = this._getDebugMaterial(scene);
  85470. scene.removeMesh(this._debugSphereMesh);
  85471. }
  85472. return this._debugSphereMesh.createInstance('physicsBodyBoxViewInstance');
  85473. };
  85474. PhysicsViewer.prototype._getDebugMesh = function (impostor, scene) {
  85475. var mesh = null;
  85476. if (impostor.type == BABYLON.PhysicsImpostor.BoxImpostor) {
  85477. mesh = this._getDebugBoxMesh(scene);
  85478. impostor.getBoxSizeToRef(mesh.scaling);
  85479. }
  85480. else if (impostor.type == BABYLON.PhysicsImpostor.SphereImpostor) {
  85481. mesh = this._getDebugSphereMesh(scene);
  85482. var radius = impostor.getRadius();
  85483. mesh.scaling.x = radius * 2;
  85484. mesh.scaling.y = radius * 2;
  85485. mesh.scaling.z = radius * 2;
  85486. }
  85487. return mesh;
  85488. };
  85489. PhysicsViewer.prototype.dispose = function () {
  85490. for (var i = 0; i < this._numMeshes; i++) {
  85491. this.hideImpostor(this._impostors[i]);
  85492. }
  85493. if (this._debugBoxMesh) {
  85494. this._debugBoxMesh.dispose();
  85495. }
  85496. if (this._debugSphereMesh) {
  85497. this._debugSphereMesh.dispose();
  85498. }
  85499. if (this._debugMaterial) {
  85500. this._debugMaterial.dispose();
  85501. }
  85502. this._impostors.length = 0;
  85503. this._scene = null;
  85504. this._physicsEnginePlugin = null;
  85505. };
  85506. return PhysicsViewer;
  85507. }());
  85508. Debug.PhysicsViewer = PhysicsViewer;
  85509. })(Debug = BABYLON.Debug || (BABYLON.Debug = {}));
  85510. })(BABYLON || (BABYLON = {}));
  85511. //# sourceMappingURL=babylon.physicsViewer.js.map
  85512. var BABYLON;
  85513. (function (BABYLON) {
  85514. var BoundingBoxRenderer = /** @class */ (function () {
  85515. function BoundingBoxRenderer(scene) {
  85516. this.frontColor = new BABYLON.Color3(1, 1, 1);
  85517. this.backColor = new BABYLON.Color3(0.1, 0.1, 0.1);
  85518. this.showBackLines = true;
  85519. this.renderList = new BABYLON.SmartArray(32);
  85520. this._vertexBuffers = {};
  85521. this._scene = scene;
  85522. }
  85523. BoundingBoxRenderer.prototype._prepareRessources = function () {
  85524. if (this._colorShader) {
  85525. return;
  85526. }
  85527. this._colorShader = new BABYLON.ShaderMaterial("colorShader", this._scene, "color", {
  85528. attributes: [BABYLON.VertexBuffer.PositionKind],
  85529. uniforms: ["world", "viewProjection", "color"]
  85530. });
  85531. var engine = this._scene.getEngine();
  85532. var boxdata = BABYLON.VertexData.CreateBox({ size: 1.0 });
  85533. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(engine, boxdata.positions, BABYLON.VertexBuffer.PositionKind, false);
  85534. this._createIndexBuffer();
  85535. };
  85536. BoundingBoxRenderer.prototype._createIndexBuffer = function () {
  85537. var engine = this._scene.getEngine();
  85538. 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]);
  85539. };
  85540. BoundingBoxRenderer.prototype._rebuild = function () {
  85541. var vb = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  85542. if (vb) {
  85543. vb._rebuild();
  85544. }
  85545. this._createIndexBuffer();
  85546. };
  85547. BoundingBoxRenderer.prototype.reset = function () {
  85548. this.renderList.reset();
  85549. };
  85550. BoundingBoxRenderer.prototype.render = function () {
  85551. if (this.renderList.length === 0) {
  85552. return;
  85553. }
  85554. this._prepareRessources();
  85555. if (!this._colorShader.isReady()) {
  85556. return;
  85557. }
  85558. var engine = this._scene.getEngine();
  85559. engine.setDepthWrite(false);
  85560. this._colorShader._preBind();
  85561. for (var boundingBoxIndex = 0; boundingBoxIndex < this.renderList.length; boundingBoxIndex++) {
  85562. var boundingBox = this.renderList.data[boundingBoxIndex];
  85563. var min = boundingBox.minimum;
  85564. var max = boundingBox.maximum;
  85565. var diff = max.subtract(min);
  85566. var median = min.add(diff.scale(0.5));
  85567. var worldMatrix = BABYLON.Matrix.Scaling(diff.x, diff.y, diff.z)
  85568. .multiply(BABYLON.Matrix.Translation(median.x, median.y, median.z))
  85569. .multiply(boundingBox.getWorldMatrix());
  85570. // VBOs
  85571. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._colorShader.getEffect());
  85572. if (this.showBackLines) {
  85573. // Back
  85574. engine.setDepthFunctionToGreaterOrEqual();
  85575. this._scene.resetCachedMaterial();
  85576. this._colorShader.setColor4("color", this.backColor.toColor4());
  85577. this._colorShader.bind(worldMatrix);
  85578. // Draw order
  85579. engine.drawElementsType(BABYLON.Material.LineListDrawMode, 0, 24);
  85580. }
  85581. // Front
  85582. engine.setDepthFunctionToLess();
  85583. this._scene.resetCachedMaterial();
  85584. this._colorShader.setColor4("color", this.frontColor.toColor4());
  85585. this._colorShader.bind(worldMatrix);
  85586. // Draw order
  85587. engine.drawElementsType(BABYLON.Material.LineListDrawMode, 0, 24);
  85588. }
  85589. this._colorShader.unbind();
  85590. engine.setDepthFunctionToLessOrEqual();
  85591. engine.setDepthWrite(true);
  85592. };
  85593. BoundingBoxRenderer.prototype.renderOcclusionBoundingBox = function (mesh) {
  85594. this._prepareRessources();
  85595. if (!this._colorShader.isReady() || !mesh._boundingInfo) {
  85596. return;
  85597. }
  85598. var engine = this._scene.getEngine();
  85599. engine.setDepthWrite(false);
  85600. engine.setColorWrite(false);
  85601. this._colorShader._preBind();
  85602. var boundingBox = mesh._boundingInfo.boundingBox;
  85603. var min = boundingBox.minimum;
  85604. var max = boundingBox.maximum;
  85605. var diff = max.subtract(min);
  85606. var median = min.add(diff.scale(0.5));
  85607. var worldMatrix = BABYLON.Matrix.Scaling(diff.x, diff.y, diff.z)
  85608. .multiply(BABYLON.Matrix.Translation(median.x, median.y, median.z))
  85609. .multiply(boundingBox.getWorldMatrix());
  85610. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._colorShader.getEffect());
  85611. engine.setDepthFunctionToLess();
  85612. this._scene.resetCachedMaterial();
  85613. this._colorShader.bind(worldMatrix);
  85614. engine.drawElementsType(BABYLON.Material.LineListDrawMode, 0, 24);
  85615. this._colorShader.unbind();
  85616. engine.setDepthFunctionToLessOrEqual();
  85617. engine.setDepthWrite(true);
  85618. engine.setColorWrite(true);
  85619. };
  85620. BoundingBoxRenderer.prototype.dispose = function () {
  85621. if (!this._colorShader) {
  85622. return;
  85623. }
  85624. this.renderList.dispose();
  85625. this._colorShader.dispose();
  85626. var buffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  85627. if (buffer) {
  85628. buffer.dispose();
  85629. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  85630. }
  85631. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  85632. };
  85633. return BoundingBoxRenderer;
  85634. }());
  85635. BABYLON.BoundingBoxRenderer = BoundingBoxRenderer;
  85636. })(BABYLON || (BABYLON = {}));
  85637. //# sourceMappingURL=babylon.boundingBoxRenderer.js.map
  85638. var BABYLON;
  85639. (function (BABYLON) {
  85640. /**
  85641. * Defines a target to use with MorphTargetManager
  85642. * @see http://doc.babylonjs.com/how_to/how_to_use_morphtargets
  85643. */
  85644. var MorphTarget = /** @class */ (function () {
  85645. /**
  85646. * Creates a new MorphTarget
  85647. * @param name defines the name of the target
  85648. * @param influence defines the influence to use
  85649. */
  85650. function MorphTarget(
  85651. /** defines the name of the target */
  85652. name, influence) {
  85653. if (influence === void 0) { influence = 0; }
  85654. this.name = name;
  85655. /**
  85656. * Gets or sets the list of animations
  85657. */
  85658. this.animations = new Array();
  85659. this._positions = null;
  85660. this._normals = null;
  85661. this._tangents = null;
  85662. /**
  85663. * Observable raised when the influence changes
  85664. */
  85665. this.onInfluenceChanged = new BABYLON.Observable();
  85666. this.influence = influence;
  85667. }
  85668. Object.defineProperty(MorphTarget.prototype, "influence", {
  85669. /**
  85670. * Gets or sets the influence of this target (ie. its weight in the overall morphing)
  85671. */
  85672. get: function () {
  85673. return this._influence;
  85674. },
  85675. set: function (influence) {
  85676. if (this._influence === influence) {
  85677. return;
  85678. }
  85679. var previous = this._influence;
  85680. this._influence = influence;
  85681. if (this.onInfluenceChanged.hasObservers) {
  85682. this.onInfluenceChanged.notifyObservers(previous === 0 || influence === 0);
  85683. }
  85684. },
  85685. enumerable: true,
  85686. configurable: true
  85687. });
  85688. Object.defineProperty(MorphTarget.prototype, "hasPositions", {
  85689. /**
  85690. * Gets a boolean defining if the target contains position data
  85691. */
  85692. get: function () {
  85693. return !!this._positions;
  85694. },
  85695. enumerable: true,
  85696. configurable: true
  85697. });
  85698. Object.defineProperty(MorphTarget.prototype, "hasNormals", {
  85699. /**
  85700. * Gets a boolean defining if the target contains normal data
  85701. */
  85702. get: function () {
  85703. return !!this._normals;
  85704. },
  85705. enumerable: true,
  85706. configurable: true
  85707. });
  85708. Object.defineProperty(MorphTarget.prototype, "hasTangents", {
  85709. /**
  85710. * Gets a boolean defining if the target contains tangent data
  85711. */
  85712. get: function () {
  85713. return !!this._tangents;
  85714. },
  85715. enumerable: true,
  85716. configurable: true
  85717. });
  85718. /**
  85719. * Affects position data to this target
  85720. * @param data defines the position data to use
  85721. */
  85722. MorphTarget.prototype.setPositions = function (data) {
  85723. this._positions = data;
  85724. };
  85725. /**
  85726. * Gets the position data stored in this target
  85727. * @returns a FloatArray containing the position data (or null if not present)
  85728. */
  85729. MorphTarget.prototype.getPositions = function () {
  85730. return this._positions;
  85731. };
  85732. /**
  85733. * Affects normal data to this target
  85734. * @param data defines the normal data to use
  85735. */
  85736. MorphTarget.prototype.setNormals = function (data) {
  85737. this._normals = data;
  85738. };
  85739. /**
  85740. * Gets the normal data stored in this target
  85741. * @returns a FloatArray containing the normal data (or null if not present)
  85742. */
  85743. MorphTarget.prototype.getNormals = function () {
  85744. return this._normals;
  85745. };
  85746. /**
  85747. * Affects tangent data to this target
  85748. * @param data defines the tangent data to use
  85749. */
  85750. MorphTarget.prototype.setTangents = function (data) {
  85751. this._tangents = data;
  85752. };
  85753. /**
  85754. * Gets the tangent data stored in this target
  85755. * @returns a FloatArray containing the tangent data (or null if not present)
  85756. */
  85757. MorphTarget.prototype.getTangents = function () {
  85758. return this._tangents;
  85759. };
  85760. /**
  85761. * Serializes the current target into a Serialization object
  85762. * @returns the serialized object
  85763. */
  85764. MorphTarget.prototype.serialize = function () {
  85765. var serializationObject = {};
  85766. serializationObject.name = this.name;
  85767. serializationObject.influence = this.influence;
  85768. serializationObject.positions = Array.prototype.slice.call(this.getPositions());
  85769. if (this.hasNormals) {
  85770. serializationObject.normals = Array.prototype.slice.call(this.getNormals());
  85771. }
  85772. if (this.hasTangents) {
  85773. serializationObject.tangents = Array.prototype.slice.call(this.getTangents());
  85774. }
  85775. // Animations
  85776. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  85777. return serializationObject;
  85778. };
  85779. // Statics
  85780. /**
  85781. * Creates a new target from serialized data
  85782. * @param serializationObject defines the serialized data to use
  85783. * @returns a new MorphTarget
  85784. */
  85785. MorphTarget.Parse = function (serializationObject) {
  85786. var result = new MorphTarget(serializationObject.name, serializationObject.influence);
  85787. result.setPositions(serializationObject.positions);
  85788. if (serializationObject.normals) {
  85789. result.setNormals(serializationObject.normals);
  85790. }
  85791. if (serializationObject.tangents) {
  85792. result.setTangents(serializationObject.tangents);
  85793. }
  85794. // Animations
  85795. if (serializationObject.animations) {
  85796. for (var animationIndex = 0; animationIndex < serializationObject.animations.length; animationIndex++) {
  85797. var parsedAnimation = serializationObject.animations[animationIndex];
  85798. result.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  85799. }
  85800. }
  85801. return result;
  85802. };
  85803. /**
  85804. * Creates a MorphTarget from mesh data
  85805. * @param mesh defines the source mesh
  85806. * @param name defines the name to use for the new target
  85807. * @param influence defines the influence to attach to the target
  85808. * @returns a new MorphTarget
  85809. */
  85810. MorphTarget.FromMesh = function (mesh, name, influence) {
  85811. if (!name) {
  85812. name = mesh.name;
  85813. }
  85814. var result = new MorphTarget(name, influence);
  85815. result.setPositions(mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind));
  85816. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  85817. result.setNormals(mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind));
  85818. }
  85819. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind)) {
  85820. result.setTangents(mesh.getVerticesData(BABYLON.VertexBuffer.TangentKind));
  85821. }
  85822. return result;
  85823. };
  85824. return MorphTarget;
  85825. }());
  85826. BABYLON.MorphTarget = MorphTarget;
  85827. })(BABYLON || (BABYLON = {}));
  85828. //# sourceMappingURL=babylon.morphTarget.js.map
  85829. var BABYLON;
  85830. (function (BABYLON) {
  85831. /**
  85832. * This class is used to deform meshes using morphing between different targets
  85833. * @see http://doc.babylonjs.com/how_to/how_to_use_morphtargets
  85834. */
  85835. var MorphTargetManager = /** @class */ (function () {
  85836. /**
  85837. * Creates a new MorphTargetManager
  85838. * @param scene defines the current scene
  85839. */
  85840. function MorphTargetManager(scene) {
  85841. if (scene === void 0) { scene = null; }
  85842. this._targets = new Array();
  85843. this._targetObservable = new Array();
  85844. this._activeTargets = new BABYLON.SmartArray(16);
  85845. this._supportsNormals = false;
  85846. this._supportsTangents = false;
  85847. this._vertexCount = 0;
  85848. this._uniqueId = 0;
  85849. this._tempInfluences = new Array();
  85850. if (!scene) {
  85851. scene = BABYLON.Engine.LastCreatedScene;
  85852. }
  85853. this._scene = scene;
  85854. if (this._scene) {
  85855. this._scene.morphTargetManagers.push(this);
  85856. this._uniqueId = this._scene.getUniqueId();
  85857. }
  85858. }
  85859. Object.defineProperty(MorphTargetManager.prototype, "uniqueId", {
  85860. /**
  85861. * Gets the unique ID of this manager
  85862. */
  85863. get: function () {
  85864. return this._uniqueId;
  85865. },
  85866. enumerable: true,
  85867. configurable: true
  85868. });
  85869. Object.defineProperty(MorphTargetManager.prototype, "vertexCount", {
  85870. /**
  85871. * Gets the number of vertices handled by this manager
  85872. */
  85873. get: function () {
  85874. return this._vertexCount;
  85875. },
  85876. enumerable: true,
  85877. configurable: true
  85878. });
  85879. Object.defineProperty(MorphTargetManager.prototype, "supportsNormals", {
  85880. /**
  85881. * Gets a boolean indicating if this manager supports morphing of normals
  85882. */
  85883. get: function () {
  85884. return this._supportsNormals;
  85885. },
  85886. enumerable: true,
  85887. configurable: true
  85888. });
  85889. Object.defineProperty(MorphTargetManager.prototype, "supportsTangents", {
  85890. /**
  85891. * Gets a boolean indicating if this manager supports morphing of tangents
  85892. */
  85893. get: function () {
  85894. return this._supportsTangents;
  85895. },
  85896. enumerable: true,
  85897. configurable: true
  85898. });
  85899. Object.defineProperty(MorphTargetManager.prototype, "numTargets", {
  85900. /**
  85901. * Gets the number of targets stored in this manager
  85902. */
  85903. get: function () {
  85904. return this._targets.length;
  85905. },
  85906. enumerable: true,
  85907. configurable: true
  85908. });
  85909. Object.defineProperty(MorphTargetManager.prototype, "numInfluencers", {
  85910. /**
  85911. * Gets the number of influencers (ie. the number of targets with influences > 0)
  85912. */
  85913. get: function () {
  85914. return this._activeTargets.length;
  85915. },
  85916. enumerable: true,
  85917. configurable: true
  85918. });
  85919. Object.defineProperty(MorphTargetManager.prototype, "influences", {
  85920. /**
  85921. * Gets the list of influences (one per target)
  85922. */
  85923. get: function () {
  85924. return this._influences;
  85925. },
  85926. enumerable: true,
  85927. configurable: true
  85928. });
  85929. /**
  85930. * Gets the active target at specified index. An active target is a target with an influence > 0
  85931. * @param index defines the index to check
  85932. * @returns the requested target
  85933. */
  85934. MorphTargetManager.prototype.getActiveTarget = function (index) {
  85935. return this._activeTargets.data[index];
  85936. };
  85937. /**
  85938. * Gets the target at specified index
  85939. * @param index defines the index to check
  85940. * @returns the requested target
  85941. */
  85942. MorphTargetManager.prototype.getTarget = function (index) {
  85943. return this._targets[index];
  85944. };
  85945. /**
  85946. * Add a new target to this manager
  85947. * @param target defines the target to add
  85948. */
  85949. MorphTargetManager.prototype.addTarget = function (target) {
  85950. var _this = this;
  85951. this._targets.push(target);
  85952. this._targetObservable.push(target.onInfluenceChanged.add(function (needUpdate) {
  85953. _this._syncActiveTargets(needUpdate);
  85954. }));
  85955. this._syncActiveTargets(true);
  85956. };
  85957. /**
  85958. * Removes a target from the manager
  85959. * @param target defines the target to remove
  85960. */
  85961. MorphTargetManager.prototype.removeTarget = function (target) {
  85962. var index = this._targets.indexOf(target);
  85963. if (index >= 0) {
  85964. this._targets.splice(index, 1);
  85965. target.onInfluenceChanged.remove(this._targetObservable.splice(index, 1)[0]);
  85966. this._syncActiveTargets(true);
  85967. }
  85968. };
  85969. /**
  85970. * Serializes the current manager into a Serialization object
  85971. * @returns the serialized object
  85972. */
  85973. MorphTargetManager.prototype.serialize = function () {
  85974. var serializationObject = {};
  85975. serializationObject.id = this.uniqueId;
  85976. serializationObject.targets = [];
  85977. for (var _i = 0, _a = this._targets; _i < _a.length; _i++) {
  85978. var target = _a[_i];
  85979. serializationObject.targets.push(target.serialize());
  85980. }
  85981. return serializationObject;
  85982. };
  85983. MorphTargetManager.prototype._syncActiveTargets = function (needUpdate) {
  85984. var influenceCount = 0;
  85985. this._activeTargets.reset();
  85986. this._supportsNormals = true;
  85987. this._supportsTangents = true;
  85988. this._vertexCount = 0;
  85989. for (var _i = 0, _a = this._targets; _i < _a.length; _i++) {
  85990. var target = _a[_i];
  85991. this._activeTargets.push(target);
  85992. this._tempInfluences[influenceCount++] = target.influence;
  85993. var positions = target.getPositions();
  85994. if (positions) {
  85995. this._supportsNormals = this._supportsNormals && target.hasNormals;
  85996. this._supportsTangents = this._supportsTangents && target.hasTangents;
  85997. var vertexCount = positions.length / 3;
  85998. if (this._vertexCount === 0) {
  85999. this._vertexCount = vertexCount;
  86000. }
  86001. else if (this._vertexCount !== vertexCount) {
  86002. BABYLON.Tools.Error("Incompatible target. Targets must all have the same vertices count.");
  86003. return;
  86004. }
  86005. }
  86006. }
  86007. if (!this._influences || this._influences.length !== influenceCount) {
  86008. this._influences = new Float32Array(influenceCount);
  86009. }
  86010. for (var index = 0; index < influenceCount; index++) {
  86011. this._influences[index] = this._tempInfluences[index];
  86012. }
  86013. if (needUpdate) {
  86014. this.synchronize();
  86015. }
  86016. };
  86017. /**
  86018. * Syncrhonize the targets with all the meshes using this morph target manager
  86019. */
  86020. MorphTargetManager.prototype.synchronize = function () {
  86021. if (!this._scene) {
  86022. return;
  86023. }
  86024. // Flag meshes as dirty to resync with the active targets
  86025. for (var _i = 0, _a = this._scene.meshes; _i < _a.length; _i++) {
  86026. var mesh = _a[_i];
  86027. if (mesh.morphTargetManager === this) {
  86028. mesh._syncGeometryWithMorphTargetManager();
  86029. }
  86030. }
  86031. };
  86032. // Statics
  86033. /**
  86034. * Creates a new MorphTargetManager from serialized data
  86035. * @param serializationObject defines the serialized data
  86036. * @param scene defines the hosting scene
  86037. * @returns the new MorphTargetManager
  86038. */
  86039. MorphTargetManager.Parse = function (serializationObject, scene) {
  86040. var result = new MorphTargetManager(scene);
  86041. result._uniqueId = serializationObject.id;
  86042. for (var _i = 0, _a = serializationObject.targets; _i < _a.length; _i++) {
  86043. var targetData = _a[_i];
  86044. result.addTarget(BABYLON.MorphTarget.Parse(targetData));
  86045. }
  86046. return result;
  86047. };
  86048. return MorphTargetManager;
  86049. }());
  86050. BABYLON.MorphTargetManager = MorphTargetManager;
  86051. })(BABYLON || (BABYLON = {}));
  86052. //# sourceMappingURL=babylon.morphTargetManager.js.map
  86053. var BABYLON;
  86054. (function (BABYLON) {
  86055. var Octree = /** @class */ (function () {
  86056. function Octree(creationFunc, maxBlockCapacity, maxDepth) {
  86057. if (maxDepth === void 0) { maxDepth = 2; }
  86058. this.maxDepth = maxDepth;
  86059. this.dynamicContent = new Array();
  86060. this._maxBlockCapacity = maxBlockCapacity || 64;
  86061. this._selectionContent = new BABYLON.SmartArrayNoDuplicate(1024);
  86062. this._creationFunc = creationFunc;
  86063. }
  86064. // Methods
  86065. Octree.prototype.update = function (worldMin, worldMax, entries) {
  86066. Octree._CreateBlocks(worldMin, worldMax, entries, this._maxBlockCapacity, 0, this.maxDepth, this, this._creationFunc);
  86067. };
  86068. Octree.prototype.addMesh = function (entry) {
  86069. for (var index = 0; index < this.blocks.length; index++) {
  86070. var block = this.blocks[index];
  86071. block.addEntry(entry);
  86072. }
  86073. };
  86074. Octree.prototype.select = function (frustumPlanes, allowDuplicate) {
  86075. this._selectionContent.reset();
  86076. for (var index = 0; index < this.blocks.length; index++) {
  86077. var block = this.blocks[index];
  86078. block.select(frustumPlanes, this._selectionContent, allowDuplicate);
  86079. }
  86080. if (allowDuplicate) {
  86081. this._selectionContent.concat(this.dynamicContent);
  86082. }
  86083. else {
  86084. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  86085. }
  86086. return this._selectionContent;
  86087. };
  86088. Octree.prototype.intersects = function (sphereCenter, sphereRadius, allowDuplicate) {
  86089. this._selectionContent.reset();
  86090. for (var index = 0; index < this.blocks.length; index++) {
  86091. var block = this.blocks[index];
  86092. block.intersects(sphereCenter, sphereRadius, this._selectionContent, allowDuplicate);
  86093. }
  86094. if (allowDuplicate) {
  86095. this._selectionContent.concat(this.dynamicContent);
  86096. }
  86097. else {
  86098. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  86099. }
  86100. return this._selectionContent;
  86101. };
  86102. Octree.prototype.intersectsRay = function (ray) {
  86103. this._selectionContent.reset();
  86104. for (var index = 0; index < this.blocks.length; index++) {
  86105. var block = this.blocks[index];
  86106. block.intersectsRay(ray, this._selectionContent);
  86107. }
  86108. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  86109. return this._selectionContent;
  86110. };
  86111. Octree._CreateBlocks = function (worldMin, worldMax, entries, maxBlockCapacity, currentDepth, maxDepth, target, creationFunc) {
  86112. target.blocks = new Array();
  86113. var blockSize = new BABYLON.Vector3((worldMax.x - worldMin.x) / 2, (worldMax.y - worldMin.y) / 2, (worldMax.z - worldMin.z) / 2);
  86114. // Segmenting space
  86115. for (var x = 0; x < 2; x++) {
  86116. for (var y = 0; y < 2; y++) {
  86117. for (var z = 0; z < 2; z++) {
  86118. var localMin = worldMin.add(blockSize.multiplyByFloats(x, y, z));
  86119. var localMax = worldMin.add(blockSize.multiplyByFloats(x + 1, y + 1, z + 1));
  86120. var block = new BABYLON.OctreeBlock(localMin, localMax, maxBlockCapacity, currentDepth + 1, maxDepth, creationFunc);
  86121. block.addEntries(entries);
  86122. target.blocks.push(block);
  86123. }
  86124. }
  86125. }
  86126. };
  86127. Octree.CreationFuncForMeshes = function (entry, block) {
  86128. var boundingInfo = entry.getBoundingInfo();
  86129. if (!entry.isBlocked && boundingInfo.boundingBox.intersectsMinMax(block.minPoint, block.maxPoint)) {
  86130. block.entries.push(entry);
  86131. }
  86132. };
  86133. Octree.CreationFuncForSubMeshes = function (entry, block) {
  86134. var boundingInfo = entry.getBoundingInfo();
  86135. if (boundingInfo.boundingBox.intersectsMinMax(block.minPoint, block.maxPoint)) {
  86136. block.entries.push(entry);
  86137. }
  86138. };
  86139. return Octree;
  86140. }());
  86141. BABYLON.Octree = Octree;
  86142. })(BABYLON || (BABYLON = {}));
  86143. //# sourceMappingURL=babylon.octree.js.map
  86144. var BABYLON;
  86145. (function (BABYLON) {
  86146. var OctreeBlock = /** @class */ (function () {
  86147. function OctreeBlock(minPoint, maxPoint, capacity, depth, maxDepth, creationFunc) {
  86148. this.entries = new Array();
  86149. this._boundingVectors = new Array();
  86150. this._capacity = capacity;
  86151. this._depth = depth;
  86152. this._maxDepth = maxDepth;
  86153. this._creationFunc = creationFunc;
  86154. this._minPoint = minPoint;
  86155. this._maxPoint = maxPoint;
  86156. this._boundingVectors.push(minPoint.clone());
  86157. this._boundingVectors.push(maxPoint.clone());
  86158. this._boundingVectors.push(minPoint.clone());
  86159. this._boundingVectors[2].x = maxPoint.x;
  86160. this._boundingVectors.push(minPoint.clone());
  86161. this._boundingVectors[3].y = maxPoint.y;
  86162. this._boundingVectors.push(minPoint.clone());
  86163. this._boundingVectors[4].z = maxPoint.z;
  86164. this._boundingVectors.push(maxPoint.clone());
  86165. this._boundingVectors[5].z = minPoint.z;
  86166. this._boundingVectors.push(maxPoint.clone());
  86167. this._boundingVectors[6].x = minPoint.x;
  86168. this._boundingVectors.push(maxPoint.clone());
  86169. this._boundingVectors[7].y = minPoint.y;
  86170. }
  86171. Object.defineProperty(OctreeBlock.prototype, "capacity", {
  86172. // Property
  86173. get: function () {
  86174. return this._capacity;
  86175. },
  86176. enumerable: true,
  86177. configurable: true
  86178. });
  86179. Object.defineProperty(OctreeBlock.prototype, "minPoint", {
  86180. get: function () {
  86181. return this._minPoint;
  86182. },
  86183. enumerable: true,
  86184. configurable: true
  86185. });
  86186. Object.defineProperty(OctreeBlock.prototype, "maxPoint", {
  86187. get: function () {
  86188. return this._maxPoint;
  86189. },
  86190. enumerable: true,
  86191. configurable: true
  86192. });
  86193. // Methods
  86194. OctreeBlock.prototype.addEntry = function (entry) {
  86195. if (this.blocks) {
  86196. for (var index = 0; index < this.blocks.length; index++) {
  86197. var block = this.blocks[index];
  86198. block.addEntry(entry);
  86199. }
  86200. return;
  86201. }
  86202. this._creationFunc(entry, this);
  86203. if (this.entries.length > this.capacity && this._depth < this._maxDepth) {
  86204. this.createInnerBlocks();
  86205. }
  86206. };
  86207. OctreeBlock.prototype.addEntries = function (entries) {
  86208. for (var index = 0; index < entries.length; index++) {
  86209. var mesh = entries[index];
  86210. this.addEntry(mesh);
  86211. }
  86212. };
  86213. OctreeBlock.prototype.select = function (frustumPlanes, selection, allowDuplicate) {
  86214. if (BABYLON.BoundingBox.IsInFrustum(this._boundingVectors, frustumPlanes)) {
  86215. if (this.blocks) {
  86216. for (var index = 0; index < this.blocks.length; index++) {
  86217. var block = this.blocks[index];
  86218. block.select(frustumPlanes, selection, allowDuplicate);
  86219. }
  86220. return;
  86221. }
  86222. if (allowDuplicate) {
  86223. selection.concat(this.entries);
  86224. }
  86225. else {
  86226. selection.concatWithNoDuplicate(this.entries);
  86227. }
  86228. }
  86229. };
  86230. OctreeBlock.prototype.intersects = function (sphereCenter, sphereRadius, selection, allowDuplicate) {
  86231. if (BABYLON.BoundingBox.IntersectsSphere(this._minPoint, this._maxPoint, sphereCenter, sphereRadius)) {
  86232. if (this.blocks) {
  86233. for (var index = 0; index < this.blocks.length; index++) {
  86234. var block = this.blocks[index];
  86235. block.intersects(sphereCenter, sphereRadius, selection, allowDuplicate);
  86236. }
  86237. return;
  86238. }
  86239. if (allowDuplicate) {
  86240. selection.concat(this.entries);
  86241. }
  86242. else {
  86243. selection.concatWithNoDuplicate(this.entries);
  86244. }
  86245. }
  86246. };
  86247. OctreeBlock.prototype.intersectsRay = function (ray, selection) {
  86248. if (ray.intersectsBoxMinMax(this._minPoint, this._maxPoint)) {
  86249. if (this.blocks) {
  86250. for (var index = 0; index < this.blocks.length; index++) {
  86251. var block = this.blocks[index];
  86252. block.intersectsRay(ray, selection);
  86253. }
  86254. return;
  86255. }
  86256. selection.concatWithNoDuplicate(this.entries);
  86257. }
  86258. };
  86259. OctreeBlock.prototype.createInnerBlocks = function () {
  86260. BABYLON.Octree._CreateBlocks(this._minPoint, this._maxPoint, this.entries, this._capacity, this._depth, this._maxDepth, this, this._creationFunc);
  86261. };
  86262. return OctreeBlock;
  86263. }());
  86264. BABYLON.OctreeBlock = OctreeBlock;
  86265. })(BABYLON || (BABYLON = {}));
  86266. //# sourceMappingURL=babylon.octreeBlock.js.map
  86267. var BABYLON;
  86268. (function (BABYLON) {
  86269. var VRDistortionCorrectionPostProcess = /** @class */ (function (_super) {
  86270. __extends(VRDistortionCorrectionPostProcess, _super);
  86271. function VRDistortionCorrectionPostProcess(name, camera, isRightEye, vrMetrics) {
  86272. var _this = _super.call(this, name, "vrDistortionCorrection", [
  86273. 'LensCenter',
  86274. 'Scale',
  86275. 'ScaleIn',
  86276. 'HmdWarpParam'
  86277. ], null, vrMetrics.postProcessScaleFactor, camera, BABYLON.Texture.BILINEAR_SAMPLINGMODE) || this;
  86278. _this._isRightEye = isRightEye;
  86279. _this._distortionFactors = vrMetrics.distortionK;
  86280. _this._postProcessScaleFactor = vrMetrics.postProcessScaleFactor;
  86281. _this._lensCenterOffset = vrMetrics.lensCenterOffset;
  86282. _this.adaptScaleToCurrentViewport = true;
  86283. _this.onSizeChangedObservable.add(function () {
  86284. _this._scaleIn = new BABYLON.Vector2(2, 2 / _this.aspectRatio);
  86285. _this._scaleFactor = new BABYLON.Vector2(.5 * (1 / _this._postProcessScaleFactor), .5 * (1 / _this._postProcessScaleFactor) * _this.aspectRatio);
  86286. _this._lensCenter = new BABYLON.Vector2(_this._isRightEye ? 0.5 - _this._lensCenterOffset * 0.5 : 0.5 + _this._lensCenterOffset * 0.5, 0.5);
  86287. });
  86288. _this.onApplyObservable.add(function (effect) {
  86289. effect.setFloat2("LensCenter", _this._lensCenter.x, _this._lensCenter.y);
  86290. effect.setFloat2("Scale", _this._scaleFactor.x, _this._scaleFactor.y);
  86291. effect.setFloat2("ScaleIn", _this._scaleIn.x, _this._scaleIn.y);
  86292. effect.setFloat4("HmdWarpParam", _this._distortionFactors[0], _this._distortionFactors[1], _this._distortionFactors[2], _this._distortionFactors[3]);
  86293. });
  86294. return _this;
  86295. }
  86296. return VRDistortionCorrectionPostProcess;
  86297. }(BABYLON.PostProcess));
  86298. BABYLON.VRDistortionCorrectionPostProcess = VRDistortionCorrectionPostProcess;
  86299. })(BABYLON || (BABYLON = {}));
  86300. //# sourceMappingURL=babylon.vrDistortionCorrectionPostProcess.js.map
  86301. var BABYLON;
  86302. (function (BABYLON) {
  86303. /**
  86304. * Postprocess used to generate anaglyphic rendering
  86305. */
  86306. var AnaglyphPostProcess = /** @class */ (function (_super) {
  86307. __extends(AnaglyphPostProcess, _super);
  86308. /**
  86309. * Creates a new AnaglyphPostProcess
  86310. * @param name defines postprocess name
  86311. * @param options defines creation options or target ratio scale
  86312. * @param rigCameras defines cameras using this postprocess
  86313. * @param samplingMode defines required sampling mode (BABYLON.Texture.NEAREST_SAMPLINGMODE by default)
  86314. * @param engine defines hosting engine
  86315. * @param reusable defines if the postprocess will be reused multiple times per frame
  86316. */
  86317. function AnaglyphPostProcess(name, options, rigCameras, samplingMode, engine, reusable) {
  86318. var _this = _super.call(this, name, "anaglyph", null, ["leftSampler"], options, rigCameras[1], samplingMode, engine, reusable) || this;
  86319. _this._passedProcess = rigCameras[0]._rigPostProcess;
  86320. _this.onApplyObservable.add(function (effect) {
  86321. effect.setTextureFromPostProcess("leftSampler", _this._passedProcess);
  86322. });
  86323. return _this;
  86324. }
  86325. return AnaglyphPostProcess;
  86326. }(BABYLON.PostProcess));
  86327. BABYLON.AnaglyphPostProcess = AnaglyphPostProcess;
  86328. })(BABYLON || (BABYLON = {}));
  86329. //# sourceMappingURL=babylon.anaglyphPostProcess.js.map
  86330. var BABYLON;
  86331. (function (BABYLON) {
  86332. var StereoscopicInterlacePostProcess = /** @class */ (function (_super) {
  86333. __extends(StereoscopicInterlacePostProcess, _super);
  86334. function StereoscopicInterlacePostProcess(name, rigCameras, isStereoscopicHoriz, samplingMode, engine, reusable) {
  86335. var _this = _super.call(this, name, "stereoscopicInterlace", ['stepSize'], ['camASampler'], 1, rigCameras[1], samplingMode, engine, reusable, isStereoscopicHoriz ? "#define IS_STEREOSCOPIC_HORIZ 1" : undefined) || this;
  86336. _this._passedProcess = rigCameras[0]._rigPostProcess;
  86337. _this._stepSize = new BABYLON.Vector2(1 / _this.width, 1 / _this.height);
  86338. _this.onSizeChangedObservable.add(function () {
  86339. _this._stepSize = new BABYLON.Vector2(1 / _this.width, 1 / _this.height);
  86340. });
  86341. _this.onApplyObservable.add(function (effect) {
  86342. effect.setTextureFromPostProcess("camASampler", _this._passedProcess);
  86343. effect.setFloat2("stepSize", _this._stepSize.x, _this._stepSize.y);
  86344. });
  86345. return _this;
  86346. }
  86347. return StereoscopicInterlacePostProcess;
  86348. }(BABYLON.PostProcess));
  86349. BABYLON.StereoscopicInterlacePostProcess = StereoscopicInterlacePostProcess;
  86350. })(BABYLON || (BABYLON = {}));
  86351. //# sourceMappingURL=babylon.stereoscopicInterlacePostProcess.js.map
  86352. var BABYLON;
  86353. (function (BABYLON) {
  86354. /**
  86355. * Takes information about the orientation of the device as reported by the deviceorientation event to orient the camera.
  86356. * Screen rotation is taken into account.
  86357. */
  86358. var FreeCameraDeviceOrientationInput = /** @class */ (function () {
  86359. function FreeCameraDeviceOrientationInput() {
  86360. var _this = this;
  86361. this._screenOrientationAngle = 0;
  86362. this._screenQuaternion = new BABYLON.Quaternion();
  86363. this._alpha = 0;
  86364. this._beta = 0;
  86365. this._gamma = 0;
  86366. this._orientationChanged = function () {
  86367. _this._screenOrientationAngle = (window.orientation !== undefined ? +window.orientation : (window.screen.orientation && window.screen.orientation['angle'] ? window.screen.orientation.angle : 0));
  86368. _this._screenOrientationAngle = -BABYLON.Tools.ToRadians(_this._screenOrientationAngle / 2);
  86369. _this._screenQuaternion.copyFromFloats(0, Math.sin(_this._screenOrientationAngle), 0, Math.cos(_this._screenOrientationAngle));
  86370. };
  86371. this._deviceOrientation = function (evt) {
  86372. _this._alpha = evt.alpha !== null ? evt.alpha : 0;
  86373. _this._beta = evt.beta !== null ? evt.beta : 0;
  86374. _this._gamma = evt.gamma !== null ? evt.gamma : 0;
  86375. };
  86376. this._constantTranform = new BABYLON.Quaternion(-Math.sqrt(0.5), 0, 0, Math.sqrt(0.5));
  86377. this._orientationChanged();
  86378. }
  86379. Object.defineProperty(FreeCameraDeviceOrientationInput.prototype, "camera", {
  86380. get: function () {
  86381. return this._camera;
  86382. },
  86383. set: function (camera) {
  86384. this._camera = camera;
  86385. if (this._camera != null && !this._camera.rotationQuaternion) {
  86386. this._camera.rotationQuaternion = new BABYLON.Quaternion();
  86387. }
  86388. },
  86389. enumerable: true,
  86390. configurable: true
  86391. });
  86392. FreeCameraDeviceOrientationInput.prototype.attachControl = function (element, noPreventDefault) {
  86393. window.addEventListener("orientationchange", this._orientationChanged);
  86394. window.addEventListener("deviceorientation", this._deviceOrientation);
  86395. //In certain cases, the attach control is called AFTER orientation was changed,
  86396. //So this is needed.
  86397. this._orientationChanged();
  86398. };
  86399. FreeCameraDeviceOrientationInput.prototype.detachControl = function (element) {
  86400. window.removeEventListener("orientationchange", this._orientationChanged);
  86401. window.removeEventListener("deviceorientation", this._deviceOrientation);
  86402. };
  86403. FreeCameraDeviceOrientationInput.prototype.checkInputs = function () {
  86404. //if no device orientation provided, don't update the rotation.
  86405. //Only testing against alpha under the assumption thatnorientation will never be so exact when set.
  86406. if (!this._alpha)
  86407. return;
  86408. BABYLON.Quaternion.RotationYawPitchRollToRef(BABYLON.Tools.ToRadians(this._alpha), BABYLON.Tools.ToRadians(this._beta), -BABYLON.Tools.ToRadians(this._gamma), this.camera.rotationQuaternion);
  86409. this._camera.rotationQuaternion.multiplyInPlace(this._screenQuaternion);
  86410. this._camera.rotationQuaternion.multiplyInPlace(this._constantTranform);
  86411. //Mirror on XY Plane
  86412. this._camera.rotationQuaternion.z *= -1;
  86413. this._camera.rotationQuaternion.w *= -1;
  86414. };
  86415. FreeCameraDeviceOrientationInput.prototype.getClassName = function () {
  86416. return "FreeCameraDeviceOrientationInput";
  86417. };
  86418. FreeCameraDeviceOrientationInput.prototype.getSimpleName = function () {
  86419. return "deviceOrientation";
  86420. };
  86421. return FreeCameraDeviceOrientationInput;
  86422. }());
  86423. BABYLON.FreeCameraDeviceOrientationInput = FreeCameraDeviceOrientationInput;
  86424. BABYLON.CameraInputTypes["FreeCameraDeviceOrientationInput"] = FreeCameraDeviceOrientationInput;
  86425. })(BABYLON || (BABYLON = {}));
  86426. //# sourceMappingURL=babylon.freeCameraDeviceOrientationInput.js.map
  86427. var BABYLON;
  86428. (function (BABYLON) {
  86429. var ArcRotateCameraVRDeviceOrientationInput = /** @class */ (function () {
  86430. function ArcRotateCameraVRDeviceOrientationInput() {
  86431. this.alphaCorrection = 1;
  86432. this.betaCorrection = 1;
  86433. this.gammaCorrection = 1;
  86434. this._alpha = 0;
  86435. this._gamma = 0;
  86436. this._dirty = false;
  86437. this._deviceOrientationHandler = this._onOrientationEvent.bind(this);
  86438. }
  86439. ArcRotateCameraVRDeviceOrientationInput.prototype.attachControl = function (element, noPreventDefault) {
  86440. this.camera.attachControl(element, noPreventDefault);
  86441. window.addEventListener("deviceorientation", this._deviceOrientationHandler);
  86442. };
  86443. ArcRotateCameraVRDeviceOrientationInput.prototype._onOrientationEvent = function (evt) {
  86444. if (evt.alpha !== null) {
  86445. this._alpha = +evt.alpha | 0;
  86446. }
  86447. if (evt.gamma !== null) {
  86448. this._gamma = +evt.gamma | 0;
  86449. }
  86450. this._dirty = true;
  86451. };
  86452. ArcRotateCameraVRDeviceOrientationInput.prototype.checkInputs = function () {
  86453. if (this._dirty) {
  86454. this._dirty = false;
  86455. if (this._gamma < 0) {
  86456. this._gamma = 180 + this._gamma;
  86457. }
  86458. this.camera.alpha = (-this._alpha / 180.0 * Math.PI) % Math.PI * 2;
  86459. this.camera.beta = (this._gamma / 180.0 * Math.PI);
  86460. }
  86461. };
  86462. ArcRotateCameraVRDeviceOrientationInput.prototype.detachControl = function (element) {
  86463. window.removeEventListener("deviceorientation", this._deviceOrientationHandler);
  86464. };
  86465. ArcRotateCameraVRDeviceOrientationInput.prototype.getClassName = function () {
  86466. return "ArcRotateCameraVRDeviceOrientationInput";
  86467. };
  86468. ArcRotateCameraVRDeviceOrientationInput.prototype.getSimpleName = function () {
  86469. return "VRDeviceOrientation";
  86470. };
  86471. return ArcRotateCameraVRDeviceOrientationInput;
  86472. }());
  86473. BABYLON.ArcRotateCameraVRDeviceOrientationInput = ArcRotateCameraVRDeviceOrientationInput;
  86474. BABYLON.CameraInputTypes["ArcRotateCameraVRDeviceOrientationInput"] = ArcRotateCameraVRDeviceOrientationInput;
  86475. })(BABYLON || (BABYLON = {}));
  86476. //# sourceMappingURL=babylon.arcRotateCameraVRDeviceOrientationInput.js.map
  86477. var BABYLON;
  86478. (function (BABYLON) {
  86479. var VRCameraMetrics = /** @class */ (function () {
  86480. function VRCameraMetrics() {
  86481. this.compensateDistortion = true;
  86482. }
  86483. Object.defineProperty(VRCameraMetrics.prototype, "aspectRatio", {
  86484. get: function () {
  86485. return this.hResolution / (2 * this.vResolution);
  86486. },
  86487. enumerable: true,
  86488. configurable: true
  86489. });
  86490. Object.defineProperty(VRCameraMetrics.prototype, "aspectRatioFov", {
  86491. get: function () {
  86492. return (2 * Math.atan((this.postProcessScaleFactor * this.vScreenSize) / (2 * this.eyeToScreenDistance)));
  86493. },
  86494. enumerable: true,
  86495. configurable: true
  86496. });
  86497. Object.defineProperty(VRCameraMetrics.prototype, "leftHMatrix", {
  86498. get: function () {
  86499. var meters = (this.hScreenSize / 4) - (this.lensSeparationDistance / 2);
  86500. var h = (4 * meters) / this.hScreenSize;
  86501. return BABYLON.Matrix.Translation(h, 0, 0);
  86502. },
  86503. enumerable: true,
  86504. configurable: true
  86505. });
  86506. Object.defineProperty(VRCameraMetrics.prototype, "rightHMatrix", {
  86507. get: function () {
  86508. var meters = (this.hScreenSize / 4) - (this.lensSeparationDistance / 2);
  86509. var h = (4 * meters) / this.hScreenSize;
  86510. return BABYLON.Matrix.Translation(-h, 0, 0);
  86511. },
  86512. enumerable: true,
  86513. configurable: true
  86514. });
  86515. Object.defineProperty(VRCameraMetrics.prototype, "leftPreViewMatrix", {
  86516. get: function () {
  86517. return BABYLON.Matrix.Translation(0.5 * this.interpupillaryDistance, 0, 0);
  86518. },
  86519. enumerable: true,
  86520. configurable: true
  86521. });
  86522. Object.defineProperty(VRCameraMetrics.prototype, "rightPreViewMatrix", {
  86523. get: function () {
  86524. return BABYLON.Matrix.Translation(-0.5 * this.interpupillaryDistance, 0, 0);
  86525. },
  86526. enumerable: true,
  86527. configurable: true
  86528. });
  86529. VRCameraMetrics.GetDefault = function () {
  86530. var result = new VRCameraMetrics();
  86531. result.hResolution = 1280;
  86532. result.vResolution = 800;
  86533. result.hScreenSize = 0.149759993;
  86534. result.vScreenSize = 0.0935999975;
  86535. result.vScreenCenter = 0.0467999987;
  86536. result.eyeToScreenDistance = 0.0410000011;
  86537. result.lensSeparationDistance = 0.0635000020;
  86538. result.interpupillaryDistance = 0.0640000030;
  86539. result.distortionK = [1.0, 0.219999999, 0.239999995, 0.0];
  86540. result.chromaAbCorrection = [0.995999992, -0.00400000019, 1.01400006, 0.0];
  86541. result.postProcessScaleFactor = 1.714605507808412;
  86542. result.lensCenterOffset = 0.151976421;
  86543. return result;
  86544. };
  86545. return VRCameraMetrics;
  86546. }());
  86547. BABYLON.VRCameraMetrics = VRCameraMetrics;
  86548. })(BABYLON || (BABYLON = {}));
  86549. //# sourceMappingURL=babylon.vrCameraMetrics.js.map
  86550. var BABYLON;
  86551. (function (BABYLON) {
  86552. /**
  86553. * This represents a WebVR camera.
  86554. * The WebVR camera is Babylon's simple interface to interaction with Windows Mixed Reality, HTC Vive and Oculus Rift.
  86555. * @example http://doc.babylonjs.com/how_to/webvr_camera
  86556. */
  86557. var WebVRFreeCamera = /** @class */ (function (_super) {
  86558. __extends(WebVRFreeCamera, _super);
  86559. /**
  86560. * Instantiates a WebVRFreeCamera.
  86561. * @param name The name of the WebVRFreeCamera
  86562. * @param position The starting anchor position for the camera
  86563. * @param scene The scene the camera belongs to
  86564. * @param webVROptions a set of customizable options for the webVRCamera
  86565. */
  86566. function WebVRFreeCamera(name, position, scene, webVROptions) {
  86567. if (webVROptions === void 0) { webVROptions = {}; }
  86568. var _this = _super.call(this, name, position, scene) || this;
  86569. _this.webVROptions = webVROptions;
  86570. /**
  86571. * The vrDisplay tied to the camera. See https://developer.mozilla.org/en-US/docs/Web/API/VRDisplay
  86572. */
  86573. _this._vrDevice = null;
  86574. /**
  86575. * The rawPose of the vrDevice.
  86576. */
  86577. _this.rawPose = null;
  86578. _this._specsVersion = "1.1";
  86579. _this._attached = false;
  86580. _this._descendants = [];
  86581. // Represents device position and rotation in room space. Should only be used to help calculate babylon space values
  86582. _this._deviceRoomPosition = BABYLON.Vector3.Zero();
  86583. _this._deviceRoomRotationQuaternion = BABYLON.Quaternion.Identity();
  86584. _this._standingMatrix = null;
  86585. /**
  86586. * Represents device position in babylon space.
  86587. */
  86588. _this.devicePosition = BABYLON.Vector3.Zero();
  86589. /**
  86590. * Represents device rotation in babylon space.
  86591. */
  86592. _this.deviceRotationQuaternion = BABYLON.Quaternion.Identity();
  86593. /**
  86594. * The scale of the device to be used when translating from device space to babylon space.
  86595. */
  86596. _this.deviceScaleFactor = 1;
  86597. _this._deviceToWorld = BABYLON.Matrix.Identity();
  86598. _this._worldToDevice = BABYLON.Matrix.Identity();
  86599. /**
  86600. * References to the webVR controllers for the vrDevice.
  86601. */
  86602. _this.controllers = [];
  86603. /**
  86604. * Emits an event when a controller is attached.
  86605. */
  86606. _this.onControllersAttachedObservable = new BABYLON.Observable();
  86607. /**
  86608. * Emits an event when a controller's mesh has been loaded;
  86609. */
  86610. _this.onControllerMeshLoadedObservable = new BABYLON.Observable();
  86611. /**
  86612. * If the rig cameras be used as parent instead of this camera.
  86613. */
  86614. _this.rigParenting = true;
  86615. _this._defaultHeight = undefined;
  86616. _this._workingVector = BABYLON.Vector3.Zero();
  86617. _this._oneVector = BABYLON.Vector3.One();
  86618. _this._workingMatrix = BABYLON.Matrix.Identity();
  86619. _this._cache.position = BABYLON.Vector3.Zero();
  86620. if (webVROptions.defaultHeight) {
  86621. _this._defaultHeight = webVROptions.defaultHeight;
  86622. _this.position.y = _this._defaultHeight;
  86623. }
  86624. _this.minZ = 0.1;
  86625. //legacy support - the compensation boolean was removed.
  86626. if (arguments.length === 5) {
  86627. _this.webVROptions = arguments[4];
  86628. }
  86629. // default webVR options
  86630. if (_this.webVROptions.trackPosition == undefined) {
  86631. _this.webVROptions.trackPosition = true;
  86632. }
  86633. if (_this.webVROptions.controllerMeshes == undefined) {
  86634. _this.webVROptions.controllerMeshes = true;
  86635. }
  86636. if (_this.webVROptions.defaultLightingOnControllers == undefined) {
  86637. _this.webVROptions.defaultLightingOnControllers = true;
  86638. }
  86639. _this.rotationQuaternion = new BABYLON.Quaternion();
  86640. if (_this.webVROptions && _this.webVROptions.positionScale) {
  86641. _this.deviceScaleFactor = _this.webVROptions.positionScale;
  86642. }
  86643. //enable VR
  86644. var engine = _this.getEngine();
  86645. _this._onVREnabled = function (success) { if (success) {
  86646. _this.initControllers();
  86647. } };
  86648. engine.onVRRequestPresentComplete.add(_this._onVREnabled);
  86649. engine.initWebVR().add(function (event) {
  86650. if (!event.vrDisplay || _this._vrDevice === event.vrDisplay) {
  86651. return;
  86652. }
  86653. _this._vrDevice = event.vrDisplay;
  86654. //reset the rig parameters.
  86655. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_WEBVR, { parentCamera: _this, vrDisplay: _this._vrDevice, frameData: _this._frameData, specs: _this._specsVersion });
  86656. if (_this._attached) {
  86657. _this.getEngine().enableVR();
  86658. }
  86659. });
  86660. if (typeof (VRFrameData) !== "undefined")
  86661. _this._frameData = new VRFrameData();
  86662. /**
  86663. * The idea behind the following lines:
  86664. * objects that have the camera as parent should actually have the rig cameras as a parent.
  86665. * BUT, each of those cameras has a different view matrix, which means that if we set the parent to the first rig camera,
  86666. * the second will not show it correctly.
  86667. *
  86668. * To solve this - each object that has the camera as parent will be added to a protected array.
  86669. * When the rig camera renders, it will take this array and set all of those to be its children.
  86670. * This way, the right camera will be used as a parent, and the mesh will be rendered correctly.
  86671. * Amazing!
  86672. */
  86673. scene.onBeforeCameraRenderObservable.add(function (camera) {
  86674. if (camera.parent === _this && _this.rigParenting) {
  86675. _this._descendants = _this.getDescendants(true, function (n) {
  86676. // don't take the cameras or the controllers!
  86677. var isController = _this.controllers.some(function (controller) { return controller._mesh === n; });
  86678. var isRigCamera = _this._rigCameras.indexOf(n) !== -1;
  86679. return !isController && !isRigCamera;
  86680. });
  86681. _this._descendants.forEach(function (node) {
  86682. node.parent = camera;
  86683. });
  86684. }
  86685. });
  86686. scene.onAfterCameraRenderObservable.add(function (camera) {
  86687. if (camera.parent === _this && _this.rigParenting) {
  86688. _this._descendants.forEach(function (node) {
  86689. node.parent = _this;
  86690. });
  86691. }
  86692. });
  86693. return _this;
  86694. }
  86695. /**
  86696. * Gets the device distance from the ground in meters.
  86697. * @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.
  86698. */
  86699. WebVRFreeCamera.prototype.deviceDistanceToRoomGround = function () {
  86700. if (this._standingMatrix) {
  86701. // Add standing matrix offset to get real offset from ground in room
  86702. this._standingMatrix.getTranslationToRef(this._workingVector);
  86703. return this._deviceRoomPosition.y + this._workingVector.y;
  86704. }
  86705. //If VRDisplay does not inform stage parameters and no default height is set we fallback to zero.
  86706. return this._defaultHeight || 0;
  86707. };
  86708. /**
  86709. * Enables the standing matrix when supported. This can be used to position the user's view the correct height from the ground.
  86710. * @param callback will be called when the standing matrix is set. Callback parameter is if the standing matrix is supported.
  86711. */
  86712. WebVRFreeCamera.prototype.useStandingMatrix = function (callback) {
  86713. var _this = this;
  86714. if (callback === void 0) { callback = function (bool) { }; }
  86715. // Use standing matrix if available
  86716. this.getEngine().initWebVRAsync().then(function (result) {
  86717. if (!result.vrDisplay || !result.vrDisplay.stageParameters || !result.vrDisplay.stageParameters.sittingToStandingTransform) {
  86718. callback(false);
  86719. }
  86720. else {
  86721. _this._standingMatrix = new BABYLON.Matrix();
  86722. BABYLON.Matrix.FromFloat32ArrayToRefScaled(result.vrDisplay.stageParameters.sittingToStandingTransform, 0, 1, _this._standingMatrix);
  86723. if (!_this.getScene().useRightHandedSystem) {
  86724. [2, 6, 8, 9, 14].forEach(function (num) {
  86725. if (_this._standingMatrix) {
  86726. _this._standingMatrix.m[num] *= -1;
  86727. }
  86728. });
  86729. }
  86730. callback(true);
  86731. }
  86732. });
  86733. };
  86734. /**
  86735. * Enables the standing matrix when supported. This can be used to position the user's view the correct height from the ground.
  86736. * @returns A promise with a boolean set to if the standing matrix is supported.
  86737. */
  86738. WebVRFreeCamera.prototype.useStandingMatrixAsync = function () {
  86739. var _this = this;
  86740. return new Promise(function (res, rej) {
  86741. _this.useStandingMatrix(function (supported) {
  86742. res(supported);
  86743. });
  86744. });
  86745. };
  86746. /**
  86747. * Disposes the camera
  86748. */
  86749. WebVRFreeCamera.prototype.dispose = function () {
  86750. this.getEngine().onVRRequestPresentComplete.removeCallback(this._onVREnabled);
  86751. _super.prototype.dispose.call(this);
  86752. };
  86753. /**
  86754. * Gets a vrController by name.
  86755. * @param name The name of the controller to retreive
  86756. * @returns the controller matching the name specified or null if not found
  86757. */
  86758. WebVRFreeCamera.prototype.getControllerByName = function (name) {
  86759. for (var _i = 0, _a = this.controllers; _i < _a.length; _i++) {
  86760. var gp = _a[_i];
  86761. if (gp.hand === name) {
  86762. return gp;
  86763. }
  86764. }
  86765. return null;
  86766. };
  86767. Object.defineProperty(WebVRFreeCamera.prototype, "leftController", {
  86768. /**
  86769. * The controller corrisponding to the users left hand.
  86770. */
  86771. get: function () {
  86772. if (!this._leftController) {
  86773. this._leftController = this.getControllerByName("left");
  86774. }
  86775. return this._leftController;
  86776. },
  86777. enumerable: true,
  86778. configurable: true
  86779. });
  86780. ;
  86781. Object.defineProperty(WebVRFreeCamera.prototype, "rightController", {
  86782. /**
  86783. * The controller corrisponding to the users right hand.
  86784. */
  86785. get: function () {
  86786. if (!this._rightController) {
  86787. this._rightController = this.getControllerByName("right");
  86788. }
  86789. return this._rightController;
  86790. },
  86791. enumerable: true,
  86792. configurable: true
  86793. });
  86794. ;
  86795. /**
  86796. * Casts a ray forward from the vrCamera's gaze.
  86797. * @param length Length of the ray (default: 100)
  86798. * @returns the ray corrisponding to the gaze
  86799. */
  86800. WebVRFreeCamera.prototype.getForwardRay = function (length) {
  86801. if (length === void 0) { length = 100; }
  86802. if (this.leftCamera) {
  86803. // Use left eye to avoid computation to compute center on every call
  86804. return _super.prototype.getForwardRay.call(this, length, this.leftCamera.getWorldMatrix(), this.leftCamera.globalPosition); // Need the actual rendered camera
  86805. }
  86806. else {
  86807. return _super.prototype.getForwardRay.call(this, length);
  86808. }
  86809. };
  86810. /**
  86811. * Updates the camera based on device's frame data
  86812. */
  86813. WebVRFreeCamera.prototype._checkInputs = function () {
  86814. if (this._vrDevice && this._vrDevice.isPresenting) {
  86815. this._vrDevice.getFrameData(this._frameData);
  86816. this.updateFromDevice(this._frameData.pose);
  86817. }
  86818. _super.prototype._checkInputs.call(this);
  86819. };
  86820. /**
  86821. * Updates the poseControlled values based on the input device pose.
  86822. * @param poseData Pose coming from the device
  86823. */
  86824. WebVRFreeCamera.prototype.updateFromDevice = function (poseData) {
  86825. if (poseData && poseData.orientation) {
  86826. this.rawPose = poseData;
  86827. this._deviceRoomRotationQuaternion.copyFromFloats(poseData.orientation[0], poseData.orientation[1], -poseData.orientation[2], -poseData.orientation[3]);
  86828. if (this.getScene().useRightHandedSystem) {
  86829. this._deviceRoomRotationQuaternion.z *= -1;
  86830. this._deviceRoomRotationQuaternion.w *= -1;
  86831. }
  86832. if (this.webVROptions.trackPosition && this.rawPose.position) {
  86833. this._deviceRoomPosition.copyFromFloats(this.rawPose.position[0], this.rawPose.position[1], -this.rawPose.position[2]);
  86834. if (this.getScene().useRightHandedSystem) {
  86835. this._deviceRoomPosition.z *= -1;
  86836. }
  86837. }
  86838. }
  86839. };
  86840. /**
  86841. * WebVR's attach control will start broadcasting frames to the device.
  86842. * Note that in certain browsers (chrome for example) this function must be called
  86843. * within a user-interaction callback. Example:
  86844. * <pre> scene.onPointerDown = function() { camera.attachControl(canvas); }</pre>
  86845. *
  86846. * @param element html element to attach the vrDevice to
  86847. * @param noPreventDefault prevent the default html element operation when attaching the vrDevice
  86848. */
  86849. WebVRFreeCamera.prototype.attachControl = function (element, noPreventDefault) {
  86850. _super.prototype.attachControl.call(this, element, noPreventDefault);
  86851. this._attached = true;
  86852. noPreventDefault = BABYLON.Camera.ForceAttachControlToAlwaysPreventDefault ? false : noPreventDefault;
  86853. if (this._vrDevice) {
  86854. this.getEngine().enableVR();
  86855. }
  86856. };
  86857. /**
  86858. * Detaches the camera from the html element and disables VR
  86859. *
  86860. * @param element html element to detach from
  86861. */
  86862. WebVRFreeCamera.prototype.detachControl = function (element) {
  86863. this.getScene().gamepadManager.onGamepadConnectedObservable.remove(this._onGamepadConnectedObserver);
  86864. this.getScene().gamepadManager.onGamepadDisconnectedObservable.remove(this._onGamepadDisconnectedObserver);
  86865. _super.prototype.detachControl.call(this, element);
  86866. this._attached = false;
  86867. this.getEngine().disableVR();
  86868. };
  86869. /**
  86870. * @returns the name of this class
  86871. */
  86872. WebVRFreeCamera.prototype.getClassName = function () {
  86873. return "WebVRFreeCamera";
  86874. };
  86875. /**
  86876. * Calls resetPose on the vrDisplay
  86877. * See: https://developer.mozilla.org/en-US/docs/Web/API/VRDisplay/resetPose
  86878. */
  86879. WebVRFreeCamera.prototype.resetToCurrentRotation = function () {
  86880. //uses the vrDisplay's "resetPose()".
  86881. //pitch and roll won't be affected.
  86882. this._vrDevice.resetPose();
  86883. };
  86884. /**
  86885. * Updates the rig cameras (left and right eye)
  86886. */
  86887. WebVRFreeCamera.prototype._updateRigCameras = function () {
  86888. var camLeft = this._rigCameras[0];
  86889. var camRight = this._rigCameras[1];
  86890. camLeft.rotationQuaternion.copyFrom(this._deviceRoomRotationQuaternion);
  86891. camRight.rotationQuaternion.copyFrom(this._deviceRoomRotationQuaternion);
  86892. camLeft.position.copyFrom(this._deviceRoomPosition);
  86893. camRight.position.copyFrom(this._deviceRoomPosition);
  86894. };
  86895. /**
  86896. * Updates the cached values of the camera
  86897. * @param ignoreParentClass ignores updating the parent class's cache (default: false)
  86898. */
  86899. WebVRFreeCamera.prototype._updateCache = function (ignoreParentClass) {
  86900. var _this = this;
  86901. if (!this.rotationQuaternion.equals(this._cache.rotationQuaternion) || !this.position.equals(this._cache.position)) {
  86902. // Update to ensure devicePosition is up to date with most recent _deviceRoomPosition
  86903. if (!this.updateCacheCalled) {
  86904. // make sure it is only called once per loop. this.update() might cause an infinite loop.
  86905. this.updateCacheCalled = true;
  86906. this.update();
  86907. }
  86908. // Set working vector to the device position in room space rotated by the new rotation
  86909. this.rotationQuaternion.toRotationMatrix(this._workingMatrix);
  86910. BABYLON.Vector3.TransformCoordinatesToRef(this._deviceRoomPosition, this._workingMatrix, this._workingVector);
  86911. // Subtract this vector from the current device position in world to get the translation for the device world matrix
  86912. this.devicePosition.subtractToRef(this._workingVector, this._workingVector);
  86913. BABYLON.Matrix.ComposeToRef(this._oneVector, this.rotationQuaternion, this._workingVector, this._deviceToWorld);
  86914. // Add translation from anchor position
  86915. this._deviceToWorld.getTranslationToRef(this._workingVector);
  86916. this._workingVector.addInPlace(this.position);
  86917. this._workingVector.subtractInPlace(this._cache.position);
  86918. this._deviceToWorld.setTranslation(this._workingVector);
  86919. // Set an inverted matrix to be used when updating the camera
  86920. this._deviceToWorld.invertToRef(this._worldToDevice);
  86921. // Update the gamepad to ensure the mesh is updated on the same frame as camera
  86922. this.controllers.forEach(function (controller) {
  86923. controller._deviceToWorld.copyFrom(_this._deviceToWorld);
  86924. controller.update();
  86925. });
  86926. }
  86927. if (!ignoreParentClass) {
  86928. _super.prototype._updateCache.call(this);
  86929. }
  86930. this.updateCacheCalled = false;
  86931. };
  86932. /**
  86933. * Updates the current device position and rotation in the babylon world
  86934. */
  86935. WebVRFreeCamera.prototype.update = function () {
  86936. // Get current device position in babylon world
  86937. BABYLON.Vector3.TransformCoordinatesToRef(this._deviceRoomPosition, this._deviceToWorld, this.devicePosition);
  86938. // Get current device rotation in babylon world
  86939. BABYLON.Matrix.FromQuaternionToRef(this._deviceRoomRotationQuaternion, this._workingMatrix);
  86940. this._workingMatrix.multiplyToRef(this._deviceToWorld, this._workingMatrix);
  86941. BABYLON.Quaternion.FromRotationMatrixToRef(this._workingMatrix, this.deviceRotationQuaternion);
  86942. _super.prototype.update.call(this);
  86943. };
  86944. /**
  86945. * Gets the view matrix of this camera (Always set to identity as left and right eye cameras contain the actual view matrix)
  86946. * @returns an identity matrix
  86947. */
  86948. WebVRFreeCamera.prototype._getViewMatrix = function () {
  86949. return BABYLON.Matrix.Identity();
  86950. };
  86951. /**
  86952. * This function is called by the two RIG cameras.
  86953. * 'this' is the left or right camera (and NOT (!!!) the WebVRFreeCamera instance)
  86954. */
  86955. WebVRFreeCamera.prototype._getWebVRViewMatrix = function () {
  86956. var _this = this;
  86957. // Update the parent camera prior to using a child camera to avoid desynchronization
  86958. var parentCamera = this._cameraRigParams["parentCamera"];
  86959. parentCamera._updateCache();
  86960. //WebVR 1.1
  86961. var viewArray = this._cameraRigParams["left"] ? this._cameraRigParams["frameData"].leftViewMatrix : this._cameraRigParams["frameData"].rightViewMatrix;
  86962. BABYLON.Matrix.FromArrayToRef(viewArray, 0, this._webvrViewMatrix);
  86963. if (!this.getScene().useRightHandedSystem) {
  86964. [2, 6, 8, 9, 14].forEach(function (num) {
  86965. _this._webvrViewMatrix.m[num] *= -1;
  86966. });
  86967. }
  86968. // update the camera rotation matrix
  86969. this._webvrViewMatrix.getRotationMatrixToRef(this._cameraRotationMatrix);
  86970. BABYLON.Vector3.TransformCoordinatesToRef(this._referencePoint, this._cameraRotationMatrix, this._transformedReferencePoint);
  86971. // Computing target and final matrix
  86972. this.position.addToRef(this._transformedReferencePoint, this._currentTarget);
  86973. // should the view matrix be updated with scale and position offset?
  86974. if (parentCamera.deviceScaleFactor !== 1) {
  86975. this._webvrViewMatrix.invert();
  86976. // scale the position, if set
  86977. if (parentCamera.deviceScaleFactor) {
  86978. this._webvrViewMatrix.m[12] *= parentCamera.deviceScaleFactor;
  86979. this._webvrViewMatrix.m[13] *= parentCamera.deviceScaleFactor;
  86980. this._webvrViewMatrix.m[14] *= parentCamera.deviceScaleFactor;
  86981. }
  86982. this._webvrViewMatrix.invert();
  86983. }
  86984. parentCamera._worldToDevice.multiplyToRef(this._webvrViewMatrix, this._webvrViewMatrix);
  86985. return this._webvrViewMatrix;
  86986. };
  86987. WebVRFreeCamera.prototype._getWebVRProjectionMatrix = function () {
  86988. var _this = this;
  86989. var parentCamera = this.parent;
  86990. parentCamera._vrDevice.depthNear = parentCamera.minZ;
  86991. parentCamera._vrDevice.depthFar = parentCamera.maxZ;
  86992. var projectionArray = this._cameraRigParams["left"] ? this._cameraRigParams["frameData"].leftProjectionMatrix : this._cameraRigParams["frameData"].rightProjectionMatrix;
  86993. BABYLON.Matrix.FromArrayToRef(projectionArray, 0, this._projectionMatrix);
  86994. //babylon compatible matrix
  86995. if (!this.getScene().useRightHandedSystem) {
  86996. [8, 9, 10, 11].forEach(function (num) {
  86997. _this._projectionMatrix.m[num] *= -1;
  86998. });
  86999. }
  87000. return this._projectionMatrix;
  87001. };
  87002. /**
  87003. * Initializes the controllers and their meshes
  87004. */
  87005. WebVRFreeCamera.prototype.initControllers = function () {
  87006. var _this = this;
  87007. this.controllers = [];
  87008. var manager = this.getScene().gamepadManager;
  87009. this._onGamepadDisconnectedObserver = manager.onGamepadDisconnectedObservable.add(function (gamepad) {
  87010. if (gamepad.type === BABYLON.Gamepad.POSE_ENABLED) {
  87011. var webVrController = gamepad;
  87012. if (webVrController.defaultModel) {
  87013. webVrController.defaultModel.setEnabled(false);
  87014. }
  87015. if (webVrController.hand === "right") {
  87016. _this._rightController = null;
  87017. }
  87018. if (webVrController.hand === "left") {
  87019. _this._leftController = null;
  87020. }
  87021. var controllerIndex = _this.controllers.indexOf(webVrController);
  87022. if (controllerIndex !== -1) {
  87023. _this.controllers.splice(controllerIndex, 1);
  87024. }
  87025. }
  87026. });
  87027. this._onGamepadConnectedObserver = manager.onGamepadConnectedObservable.add(function (gamepad) {
  87028. if (gamepad.type === BABYLON.Gamepad.POSE_ENABLED) {
  87029. var webVrController_1 = gamepad;
  87030. webVrController_1.deviceScaleFactor = _this.deviceScaleFactor;
  87031. webVrController_1._deviceToWorld.copyFrom(_this._deviceToWorld);
  87032. if (_this.webVROptions.controllerMeshes) {
  87033. if (webVrController_1.defaultModel) {
  87034. webVrController_1.defaultModel.setEnabled(true);
  87035. }
  87036. else {
  87037. // Load the meshes
  87038. webVrController_1.initControllerMesh(_this.getScene(), function (loadedMesh) {
  87039. loadedMesh.scaling.scaleInPlace(_this.deviceScaleFactor);
  87040. _this.onControllerMeshLoadedObservable.notifyObservers(webVrController_1);
  87041. if (_this.webVROptions.defaultLightingOnControllers) {
  87042. if (!_this._lightOnControllers) {
  87043. _this._lightOnControllers = new BABYLON.HemisphericLight("vrControllersLight", new BABYLON.Vector3(0, 1, 0), _this.getScene());
  87044. }
  87045. var activateLightOnSubMeshes_1 = function (mesh, light) {
  87046. var children = mesh.getChildren();
  87047. if (children.length !== 0) {
  87048. children.forEach(function (mesh) {
  87049. light.includedOnlyMeshes.push(mesh);
  87050. activateLightOnSubMeshes_1(mesh, light);
  87051. });
  87052. }
  87053. };
  87054. _this._lightOnControllers.includedOnlyMeshes.push(loadedMesh);
  87055. activateLightOnSubMeshes_1(loadedMesh, _this._lightOnControllers);
  87056. }
  87057. });
  87058. }
  87059. }
  87060. webVrController_1.attachToPoseControlledCamera(_this);
  87061. // since this is async - sanity check. Is the controller already stored?
  87062. if (_this.controllers.indexOf(webVrController_1) === -1) {
  87063. //add to the controllers array
  87064. _this.controllers.push(webVrController_1);
  87065. // Forced to add some control code for Vive as it doesn't always fill properly the "hand" property
  87066. // Sometimes, both controllers are set correctly (left and right), sometimes none, sometimes only one of them...
  87067. // So we're overriding setting left & right manually to be sure
  87068. var firstViveWandDetected = false;
  87069. for (var i = 0; i < _this.controllers.length; i++) {
  87070. if (_this.controllers[i].controllerType === BABYLON.PoseEnabledControllerType.VIVE) {
  87071. if (!firstViveWandDetected) {
  87072. firstViveWandDetected = true;
  87073. _this.controllers[i].hand = "left";
  87074. }
  87075. else {
  87076. _this.controllers[i].hand = "right";
  87077. }
  87078. }
  87079. }
  87080. //did we find enough controllers? Great! let the developer know.
  87081. if (_this.controllers.length >= 2) {
  87082. _this.onControllersAttachedObservable.notifyObservers(_this.controllers);
  87083. }
  87084. }
  87085. }
  87086. });
  87087. };
  87088. return WebVRFreeCamera;
  87089. }(BABYLON.FreeCamera));
  87090. BABYLON.WebVRFreeCamera = WebVRFreeCamera;
  87091. })(BABYLON || (BABYLON = {}));
  87092. //# sourceMappingURL=babylon.webVRCamera.js.map
  87093. var BABYLON;
  87094. (function (BABYLON) {
  87095. // We're mainly based on the logic defined into the FreeCamera code
  87096. /**
  87097. * This is a camera specifically designed to react to device orientation events such as a modern mobile device
  87098. * being tilted forward or back and left or right.
  87099. */
  87100. var DeviceOrientationCamera = /** @class */ (function (_super) {
  87101. __extends(DeviceOrientationCamera, _super);
  87102. /**
  87103. * Creates a new device orientation camera
  87104. * @param name The name of the camera
  87105. * @param position The start position camera
  87106. * @param scene The scene the camera belongs to
  87107. */
  87108. function DeviceOrientationCamera(name, position, scene) {
  87109. var _this = _super.call(this, name, position, scene) || this;
  87110. _this._quaternionCache = new BABYLON.Quaternion();
  87111. _this.inputs.addDeviceOrientation();
  87112. return _this;
  87113. }
  87114. /**
  87115. * Gets the current instance class name ("DeviceOrientationCamera").
  87116. * This helps avoiding instanceof at run time.
  87117. * @returns the class name
  87118. */
  87119. DeviceOrientationCamera.prototype.getClassName = function () {
  87120. return "DeviceOrientationCamera";
  87121. };
  87122. /**
  87123. * Checks and applies the current values of the inputs to the camera. (Internal use only)
  87124. */
  87125. DeviceOrientationCamera.prototype._checkInputs = function () {
  87126. _super.prototype._checkInputs.call(this);
  87127. this._quaternionCache.copyFrom(this.rotationQuaternion);
  87128. if (this._initialQuaternion) {
  87129. this._initialQuaternion.multiplyToRef(this.rotationQuaternion, this.rotationQuaternion);
  87130. }
  87131. };
  87132. /**
  87133. * Reset the camera to its default orientation on the specified axis only.
  87134. * @param axis The axis to reset
  87135. */
  87136. DeviceOrientationCamera.prototype.resetToCurrentRotation = function (axis) {
  87137. var _this = this;
  87138. if (axis === void 0) { axis = BABYLON.Axis.Y; }
  87139. //can only work if this camera has a rotation quaternion already.
  87140. if (!this.rotationQuaternion)
  87141. return;
  87142. if (!this._initialQuaternion) {
  87143. this._initialQuaternion = new BABYLON.Quaternion();
  87144. }
  87145. this._initialQuaternion.copyFrom(this._quaternionCache || this.rotationQuaternion);
  87146. ['x', 'y', 'z'].forEach(function (axisName) {
  87147. if (!axis[axisName]) {
  87148. _this._initialQuaternion[axisName] = 0;
  87149. }
  87150. else {
  87151. _this._initialQuaternion[axisName] *= -1;
  87152. }
  87153. });
  87154. this._initialQuaternion.normalize();
  87155. //force rotation update
  87156. this._initialQuaternion.multiplyToRef(this.rotationQuaternion, this.rotationQuaternion);
  87157. };
  87158. return DeviceOrientationCamera;
  87159. }(BABYLON.FreeCamera));
  87160. BABYLON.DeviceOrientationCamera = DeviceOrientationCamera;
  87161. })(BABYLON || (BABYLON = {}));
  87162. //# sourceMappingURL=babylon.deviceOrientationCamera.js.map
  87163. var BABYLON;
  87164. (function (BABYLON) {
  87165. var VRDeviceOrientationFreeCamera = /** @class */ (function (_super) {
  87166. __extends(VRDeviceOrientationFreeCamera, _super);
  87167. function VRDeviceOrientationFreeCamera(name, position, scene, compensateDistortion, vrCameraMetrics) {
  87168. if (compensateDistortion === void 0) { compensateDistortion = true; }
  87169. if (vrCameraMetrics === void 0) { vrCameraMetrics = BABYLON.VRCameraMetrics.GetDefault(); }
  87170. var _this = _super.call(this, name, position, scene) || this;
  87171. vrCameraMetrics.compensateDistortion = compensateDistortion;
  87172. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_VR, { vrCameraMetrics: vrCameraMetrics });
  87173. return _this;
  87174. }
  87175. VRDeviceOrientationFreeCamera.prototype.getClassName = function () {
  87176. return "VRDeviceOrientationFreeCamera";
  87177. };
  87178. return VRDeviceOrientationFreeCamera;
  87179. }(BABYLON.DeviceOrientationCamera));
  87180. BABYLON.VRDeviceOrientationFreeCamera = VRDeviceOrientationFreeCamera;
  87181. var VRDeviceOrientationGamepadCamera = /** @class */ (function (_super) {
  87182. __extends(VRDeviceOrientationGamepadCamera, _super);
  87183. function VRDeviceOrientationGamepadCamera(name, position, scene, compensateDistortion, vrCameraMetrics) {
  87184. if (compensateDistortion === void 0) { compensateDistortion = true; }
  87185. if (vrCameraMetrics === void 0) { vrCameraMetrics = BABYLON.VRCameraMetrics.GetDefault(); }
  87186. var _this = _super.call(this, name, position, scene, compensateDistortion, vrCameraMetrics) || this;
  87187. _this.inputs.addGamepad();
  87188. return _this;
  87189. }
  87190. VRDeviceOrientationGamepadCamera.prototype.getClassName = function () {
  87191. return "VRDeviceOrientationGamepadCamera";
  87192. };
  87193. return VRDeviceOrientationGamepadCamera;
  87194. }(VRDeviceOrientationFreeCamera));
  87195. BABYLON.VRDeviceOrientationGamepadCamera = VRDeviceOrientationGamepadCamera;
  87196. var VRDeviceOrientationArcRotateCamera = /** @class */ (function (_super) {
  87197. __extends(VRDeviceOrientationArcRotateCamera, _super);
  87198. function VRDeviceOrientationArcRotateCamera(name, alpha, beta, radius, target, scene, compensateDistortion, vrCameraMetrics) {
  87199. if (compensateDistortion === void 0) { compensateDistortion = true; }
  87200. if (vrCameraMetrics === void 0) { vrCameraMetrics = BABYLON.VRCameraMetrics.GetDefault(); }
  87201. var _this = _super.call(this, name, alpha, beta, radius, target, scene) || this;
  87202. vrCameraMetrics.compensateDistortion = compensateDistortion;
  87203. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_VR, { vrCameraMetrics: vrCameraMetrics });
  87204. _this.inputs.addVRDeviceOrientation();
  87205. return _this;
  87206. }
  87207. VRDeviceOrientationArcRotateCamera.prototype.getClassName = function () {
  87208. return "VRDeviceOrientationArcRotateCamera";
  87209. };
  87210. return VRDeviceOrientationArcRotateCamera;
  87211. }(BABYLON.ArcRotateCamera));
  87212. BABYLON.VRDeviceOrientationArcRotateCamera = VRDeviceOrientationArcRotateCamera;
  87213. })(BABYLON || (BABYLON = {}));
  87214. //# sourceMappingURL=babylon.vrDeviceOrientationCamera.js.map
  87215. var BABYLON;
  87216. (function (BABYLON) {
  87217. /**
  87218. * Camera used to simulate anaglyphic rendering (based on FreeCamera)
  87219. */
  87220. var AnaglyphFreeCamera = /** @class */ (function (_super) {
  87221. __extends(AnaglyphFreeCamera, _super);
  87222. /**
  87223. * Creates a new AnaglyphFreeCamera
  87224. * @param name defines camera name
  87225. * @param position defines initial position
  87226. * @param interaxialDistance defines distance between each color axis
  87227. * @param scene defines the hosting scene
  87228. */
  87229. function AnaglyphFreeCamera(name, position, interaxialDistance, scene) {
  87230. var _this = _super.call(this, name, position, scene) || this;
  87231. _this.interaxialDistance = interaxialDistance;
  87232. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  87233. return _this;
  87234. }
  87235. /**
  87236. * Gets camera class name
  87237. * @returns AnaglyphFreeCamera
  87238. */
  87239. AnaglyphFreeCamera.prototype.getClassName = function () {
  87240. return "AnaglyphFreeCamera";
  87241. };
  87242. return AnaglyphFreeCamera;
  87243. }(BABYLON.FreeCamera));
  87244. BABYLON.AnaglyphFreeCamera = AnaglyphFreeCamera;
  87245. /**
  87246. * Camera used to simulate anaglyphic rendering (based on ArcRotateCamera)
  87247. */
  87248. var AnaglyphArcRotateCamera = /** @class */ (function (_super) {
  87249. __extends(AnaglyphArcRotateCamera, _super);
  87250. /**
  87251. * Creates a new AnaglyphArcRotateCamera
  87252. * @param name defines camera name
  87253. * @param alpha defines alpha angle (in radians)
  87254. * @param beta defines beta angle (in radians)
  87255. * @param radius defines radius
  87256. * @param target defines camera target
  87257. * @param interaxialDistance defines distance between each color axis
  87258. * @param scene defines the hosting scene
  87259. */
  87260. function AnaglyphArcRotateCamera(name, alpha, beta, radius, target, interaxialDistance, scene) {
  87261. var _this = _super.call(this, name, alpha, beta, radius, target, scene) || this;
  87262. _this.interaxialDistance = interaxialDistance;
  87263. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  87264. return _this;
  87265. }
  87266. /**
  87267. * Gets camera class name
  87268. * @returns AnaglyphArcRotateCamera
  87269. */
  87270. AnaglyphArcRotateCamera.prototype.getClassName = function () {
  87271. return "AnaglyphArcRotateCamera";
  87272. };
  87273. return AnaglyphArcRotateCamera;
  87274. }(BABYLON.ArcRotateCamera));
  87275. BABYLON.AnaglyphArcRotateCamera = AnaglyphArcRotateCamera;
  87276. /**
  87277. * Camera used to simulate anaglyphic rendering (based on GamepadCamera)
  87278. */
  87279. var AnaglyphGamepadCamera = /** @class */ (function (_super) {
  87280. __extends(AnaglyphGamepadCamera, _super);
  87281. /**
  87282. * Creates a new AnaglyphGamepadCamera
  87283. * @param name defines camera name
  87284. * @param position defines initial position
  87285. * @param interaxialDistance defines distance between each color axis
  87286. * @param scene defines the hosting scene
  87287. */
  87288. function AnaglyphGamepadCamera(name, position, interaxialDistance, scene) {
  87289. var _this = _super.call(this, name, position, scene) || this;
  87290. _this.interaxialDistance = interaxialDistance;
  87291. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  87292. return _this;
  87293. }
  87294. /**
  87295. * Gets camera class name
  87296. * @returns AnaglyphGamepadCamera
  87297. */
  87298. AnaglyphGamepadCamera.prototype.getClassName = function () {
  87299. return "AnaglyphGamepadCamera";
  87300. };
  87301. return AnaglyphGamepadCamera;
  87302. }(BABYLON.GamepadCamera));
  87303. BABYLON.AnaglyphGamepadCamera = AnaglyphGamepadCamera;
  87304. /**
  87305. * Camera used to simulate anaglyphic rendering (based on UniversalCamera)
  87306. */
  87307. var AnaglyphUniversalCamera = /** @class */ (function (_super) {
  87308. __extends(AnaglyphUniversalCamera, _super);
  87309. /**
  87310. * Creates a new AnaglyphUniversalCamera
  87311. * @param name defines camera name
  87312. * @param position defines initial position
  87313. * @param interaxialDistance defines distance between each color axis
  87314. * @param scene defines the hosting scene
  87315. */
  87316. function AnaglyphUniversalCamera(name, position, interaxialDistance, scene) {
  87317. var _this = _super.call(this, name, position, scene) || this;
  87318. _this.interaxialDistance = interaxialDistance;
  87319. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  87320. return _this;
  87321. }
  87322. /**
  87323. * Gets camera class name
  87324. * @returns AnaglyphUniversalCamera
  87325. */
  87326. AnaglyphUniversalCamera.prototype.getClassName = function () {
  87327. return "AnaglyphUniversalCamera";
  87328. };
  87329. return AnaglyphUniversalCamera;
  87330. }(BABYLON.UniversalCamera));
  87331. BABYLON.AnaglyphUniversalCamera = AnaglyphUniversalCamera;
  87332. /**
  87333. * Camera used to simulate stereoscopic rendering (based on FreeCamera)
  87334. */
  87335. var StereoscopicFreeCamera = /** @class */ (function (_super) {
  87336. __extends(StereoscopicFreeCamera, _super);
  87337. /**
  87338. * Creates a new StereoscopicFreeCamera
  87339. * @param name defines camera name
  87340. * @param position defines initial position
  87341. * @param interaxialDistance defines distance between each color axis
  87342. * @param isStereoscopicSideBySide defines is stereoscopic is done side by side or over under
  87343. * @param scene defines the hosting scene
  87344. */
  87345. function StereoscopicFreeCamera(name, position, interaxialDistance, isStereoscopicSideBySide, scene) {
  87346. var _this = _super.call(this, name, position, scene) || this;
  87347. _this.interaxialDistance = interaxialDistance;
  87348. _this.isStereoscopicSideBySide = isStereoscopicSideBySide;
  87349. _this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  87350. return _this;
  87351. }
  87352. /**
  87353. * Gets camera class name
  87354. * @returns StereoscopicFreeCamera
  87355. */
  87356. StereoscopicFreeCamera.prototype.getClassName = function () {
  87357. return "StereoscopicFreeCamera";
  87358. };
  87359. return StereoscopicFreeCamera;
  87360. }(BABYLON.FreeCamera));
  87361. BABYLON.StereoscopicFreeCamera = StereoscopicFreeCamera;
  87362. /**
  87363. * Camera used to simulate stereoscopic rendering (based on ArcRotateCamera)
  87364. */
  87365. var StereoscopicArcRotateCamera = /** @class */ (function (_super) {
  87366. __extends(StereoscopicArcRotateCamera, _super);
  87367. /**
  87368. * Creates a new StereoscopicArcRotateCamera
  87369. * @param name defines camera name
  87370. * @param alpha defines alpha angle (in radians)
  87371. * @param beta defines beta angle (in radians)
  87372. * @param radius defines radius
  87373. * @param target defines camera target
  87374. * @param interaxialDistance defines distance between each color axis
  87375. * @param isStereoscopicSideBySide defines is stereoscopic is done side by side or over under
  87376. * @param scene defines the hosting scene
  87377. */
  87378. function StereoscopicArcRotateCamera(name, alpha, beta, radius, target, interaxialDistance, isStereoscopicSideBySide, scene) {
  87379. var _this = _super.call(this, name, alpha, beta, radius, target, scene) || this;
  87380. _this.interaxialDistance = interaxialDistance;
  87381. _this.isStereoscopicSideBySide = isStereoscopicSideBySide;
  87382. _this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  87383. return _this;
  87384. }
  87385. /**
  87386. * Gets camera class name
  87387. * @returns StereoscopicArcRotateCamera
  87388. */
  87389. StereoscopicArcRotateCamera.prototype.getClassName = function () {
  87390. return "StereoscopicArcRotateCamera";
  87391. };
  87392. return StereoscopicArcRotateCamera;
  87393. }(BABYLON.ArcRotateCamera));
  87394. BABYLON.StereoscopicArcRotateCamera = StereoscopicArcRotateCamera;
  87395. /**
  87396. * Camera used to simulate stereoscopic rendering (based on GamepadCamera)
  87397. */
  87398. var StereoscopicGamepadCamera = /** @class */ (function (_super) {
  87399. __extends(StereoscopicGamepadCamera, _super);
  87400. /**
  87401. * Creates a new StereoscopicGamepadCamera
  87402. * @param name defines camera name
  87403. * @param position defines initial position
  87404. * @param interaxialDistance defines distance between each color axis
  87405. * @param isStereoscopicSideBySide defines is stereoscopic is done side by side or over under
  87406. * @param scene defines the hosting scene
  87407. */
  87408. function StereoscopicGamepadCamera(name, position, interaxialDistance, isStereoscopicSideBySide, scene) {
  87409. var _this = _super.call(this, name, position, scene) || this;
  87410. _this.interaxialDistance = interaxialDistance;
  87411. _this.isStereoscopicSideBySide = isStereoscopicSideBySide;
  87412. _this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  87413. return _this;
  87414. }
  87415. /**
  87416. * Gets camera class name
  87417. * @returns StereoscopicGamepadCamera
  87418. */
  87419. StereoscopicGamepadCamera.prototype.getClassName = function () {
  87420. return "StereoscopicGamepadCamera";
  87421. };
  87422. return StereoscopicGamepadCamera;
  87423. }(BABYLON.GamepadCamera));
  87424. BABYLON.StereoscopicGamepadCamera = StereoscopicGamepadCamera;
  87425. /**
  87426. * Camera used to simulate stereoscopic rendering (based on UniversalCamera)
  87427. */
  87428. var StereoscopicUniversalCamera = /** @class */ (function (_super) {
  87429. __extends(StereoscopicUniversalCamera, _super);
  87430. /**
  87431. * Creates a new StereoscopicUniversalCamera
  87432. * @param name defines camera name
  87433. * @param position defines initial position
  87434. * @param interaxialDistance defines distance between each color axis
  87435. * @param isStereoscopicSideBySide defines is stereoscopic is done side by side or over under
  87436. * @param scene defines the hosting scene
  87437. */
  87438. function StereoscopicUniversalCamera(name, position, interaxialDistance, isStereoscopicSideBySide, scene) {
  87439. var _this = _super.call(this, name, position, scene) || this;
  87440. _this.interaxialDistance = interaxialDistance;
  87441. _this.isStereoscopicSideBySide = isStereoscopicSideBySide;
  87442. _this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  87443. return _this;
  87444. }
  87445. /**
  87446. * Gets camera class name
  87447. * @returns StereoscopicUniversalCamera
  87448. */
  87449. StereoscopicUniversalCamera.prototype.getClassName = function () {
  87450. return "StereoscopicUniversalCamera";
  87451. };
  87452. return StereoscopicUniversalCamera;
  87453. }(BABYLON.UniversalCamera));
  87454. BABYLON.StereoscopicUniversalCamera = StereoscopicUniversalCamera;
  87455. })(BABYLON || (BABYLON = {}));
  87456. //# sourceMappingURL=babylon.stereoscopicCameras.js.map
  87457. var BABYLON;
  87458. (function (BABYLON) {
  87459. var VRExperienceHelperGazer = /** @class */ (function () {
  87460. function VRExperienceHelperGazer(scene, gazeTrackerToClone) {
  87461. if (gazeTrackerToClone === void 0) { gazeTrackerToClone = null; }
  87462. this.scene = scene;
  87463. this._pointerDownOnMeshAsked = false;
  87464. this._isActionableMesh = false;
  87465. this._teleportationRequestInitiated = false;
  87466. this._teleportationBackRequestInitiated = false;
  87467. this._dpadPressed = true;
  87468. this._activePointer = false;
  87469. this._id = VRExperienceHelperGazer._idCounter++;
  87470. // Gaze tracker
  87471. if (!gazeTrackerToClone) {
  87472. this._gazeTracker = BABYLON.Mesh.CreateTorus("gazeTracker", 0.0035, 0.0025, 20, scene, false);
  87473. this._gazeTracker.bakeCurrentTransformIntoVertices();
  87474. this._gazeTracker.isPickable = false;
  87475. this._gazeTracker.isVisible = false;
  87476. var targetMat = new BABYLON.StandardMaterial("targetMat", scene);
  87477. targetMat.specularColor = BABYLON.Color3.Black();
  87478. targetMat.emissiveColor = new BABYLON.Color3(0.7, 0.7, 0.7);
  87479. targetMat.backFaceCulling = false;
  87480. this._gazeTracker.material = targetMat;
  87481. }
  87482. else {
  87483. this._gazeTracker = gazeTrackerToClone.clone("gazeTracker");
  87484. }
  87485. }
  87486. VRExperienceHelperGazer.prototype._getForwardRay = function (length) {
  87487. return new BABYLON.Ray(BABYLON.Vector3.Zero(), new BABYLON.Vector3(0, 0, length));
  87488. };
  87489. VRExperienceHelperGazer.prototype._selectionPointerDown = function () {
  87490. this._pointerDownOnMeshAsked = true;
  87491. if (this._currentMeshSelected && this._currentHit) {
  87492. this.scene.simulatePointerDown(this._currentHit, { pointerId: this._id });
  87493. }
  87494. };
  87495. VRExperienceHelperGazer.prototype._selectionPointerUp = function () {
  87496. if (this._currentMeshSelected && this._currentHit) {
  87497. this.scene.simulatePointerUp(this._currentHit, { pointerId: this._id });
  87498. }
  87499. this._pointerDownOnMeshAsked = false;
  87500. };
  87501. VRExperienceHelperGazer.prototype._activatePointer = function () {
  87502. this._activePointer = true;
  87503. };
  87504. VRExperienceHelperGazer.prototype._deactivatePointer = function () {
  87505. this._activePointer = false;
  87506. };
  87507. VRExperienceHelperGazer.prototype._updatePointerDistance = function (distance) {
  87508. };
  87509. VRExperienceHelperGazer.prototype.dispose = function () {
  87510. this._interactionsEnabled = false;
  87511. this._teleportationEnabled = false;
  87512. };
  87513. VRExperienceHelperGazer._idCounter = 0;
  87514. return VRExperienceHelperGazer;
  87515. }());
  87516. var VRExperienceHelperControllerGazer = /** @class */ (function (_super) {
  87517. __extends(VRExperienceHelperControllerGazer, _super);
  87518. function VRExperienceHelperControllerGazer(webVRController, scene, gazeTrackerToClone) {
  87519. var _this = _super.call(this, scene, gazeTrackerToClone) || this;
  87520. _this.webVRController = webVRController;
  87521. // Laser pointer
  87522. _this._laserPointer = BABYLON.Mesh.CreateCylinder("laserPointer", 1, 0.004, 0.0002, 20, 1, scene, false);
  87523. var laserPointerMaterial = new BABYLON.StandardMaterial("laserPointerMat", scene);
  87524. laserPointerMaterial.emissiveColor = new BABYLON.Color3(0.7, 0.7, 0.7);
  87525. laserPointerMaterial.alpha = 0.6;
  87526. _this._laserPointer.material = laserPointerMaterial;
  87527. _this._laserPointer.rotation.x = Math.PI / 2;
  87528. _this._laserPointer.position.z = -0.5;
  87529. _this._laserPointer.isVisible = false;
  87530. if (!webVRController.mesh) {
  87531. // Create an empty mesh that is used prior to loading the high quality model
  87532. var preloadMesh = new BABYLON.Mesh("preloadControllerMesh", scene);
  87533. var preloadPointerPose = new BABYLON.Mesh(BABYLON.PoseEnabledController.POINTING_POSE, scene);
  87534. preloadPointerPose.rotation.x = -0.7;
  87535. preloadMesh.addChild(preloadPointerPose);
  87536. webVRController.attachToMesh(preloadMesh);
  87537. }
  87538. _this._setLaserPointerParent(webVRController.mesh);
  87539. return _this;
  87540. }
  87541. VRExperienceHelperControllerGazer.prototype._getForwardRay = function (length) {
  87542. return this.webVRController.getForwardRay(length);
  87543. };
  87544. VRExperienceHelperControllerGazer.prototype._activatePointer = function () {
  87545. _super.prototype._activatePointer.call(this);
  87546. this._laserPointer.isVisible = true;
  87547. };
  87548. VRExperienceHelperControllerGazer.prototype._deactivatePointer = function () {
  87549. _super.prototype._deactivatePointer.call(this);
  87550. this._laserPointer.isVisible = false;
  87551. };
  87552. VRExperienceHelperControllerGazer.prototype._setLaserPointerColor = function (color) {
  87553. this._laserPointer.material.emissiveColor = color;
  87554. };
  87555. VRExperienceHelperControllerGazer.prototype._setLaserPointerParent = function (mesh) {
  87556. var makeNotPick = function (root) {
  87557. root.name += " laserPointer";
  87558. root.getChildMeshes().forEach(function (c) {
  87559. makeNotPick(c);
  87560. });
  87561. };
  87562. makeNotPick(mesh);
  87563. var childMeshes = mesh.getChildMeshes();
  87564. this.webVRController._pointingPoseNode = null;
  87565. for (var i = 0; i < childMeshes.length; i++) {
  87566. if (childMeshes[i].name && childMeshes[i].name.indexOf(BABYLON.PoseEnabledController.POINTING_POSE) >= 0) {
  87567. mesh = childMeshes[i];
  87568. this.webVRController._pointingPoseNode = mesh;
  87569. break;
  87570. }
  87571. }
  87572. this._laserPointer.parent = mesh;
  87573. };
  87574. VRExperienceHelperControllerGazer.prototype._updatePointerDistance = function (distance) {
  87575. this._laserPointer.scaling.y = distance;
  87576. this._laserPointer.position.z = -distance / 2;
  87577. };
  87578. VRExperienceHelperControllerGazer.prototype.dispose = function () {
  87579. _super.prototype.dispose.call(this);
  87580. this._laserPointer.dispose();
  87581. };
  87582. return VRExperienceHelperControllerGazer;
  87583. }(VRExperienceHelperGazer));
  87584. var VRExperienceHelperCameraGazer = /** @class */ (function (_super) {
  87585. __extends(VRExperienceHelperCameraGazer, _super);
  87586. function VRExperienceHelperCameraGazer(getCamera, scene) {
  87587. var _this = _super.call(this, scene) || this;
  87588. _this.getCamera = getCamera;
  87589. return _this;
  87590. }
  87591. VRExperienceHelperCameraGazer.prototype._getForwardRay = function (length) {
  87592. var camera = this.getCamera();
  87593. if (camera) {
  87594. return camera.getForwardRay(length);
  87595. }
  87596. else {
  87597. return new BABYLON.Ray(BABYLON.Vector3.Zero(), BABYLON.Vector3.Forward());
  87598. }
  87599. };
  87600. return VRExperienceHelperCameraGazer;
  87601. }(VRExperienceHelperGazer));
  87602. /**
  87603. * Helps to quickly add VR support to an existing scene.
  87604. * See http://doc.babylonjs.com/how_to/webvr_helper
  87605. */
  87606. var VRExperienceHelper = /** @class */ (function () {
  87607. /**
  87608. * Instantiates a VRExperienceHelper.
  87609. * Helps to quickly add VR support to an existing scene.
  87610. * @param scene The scene the VRExperienceHelper belongs to.
  87611. * @param webVROptions Options to modify the vr experience helper's behavior.
  87612. */
  87613. function VRExperienceHelper(scene, /** Options to modify the vr experience helper's behavior. */ webVROptions) {
  87614. if (webVROptions === void 0) { webVROptions = {}; }
  87615. var _this = this;
  87616. this.webVROptions = webVROptions;
  87617. // Can the system support WebVR, even if a headset isn't plugged in?
  87618. this._webVRsupported = false;
  87619. // If WebVR is supported, is a headset plugged in and are we ready to present?
  87620. this._webVRready = false;
  87621. // Are we waiting for the requestPresent callback to complete?
  87622. this._webVRrequesting = false;
  87623. // Are we presenting to the headset right now?
  87624. this._webVRpresenting = false;
  87625. // Are we presenting in the fullscreen fallback?
  87626. this._fullscreenVRpresenting = false;
  87627. /**
  87628. * Observable raised when entering VR.
  87629. */
  87630. this.onEnteringVRObservable = new BABYLON.Observable();
  87631. /**
  87632. * Observable raised when exiting VR.
  87633. */
  87634. this.onExitingVRObservable = new BABYLON.Observable();
  87635. /**
  87636. * Observable raised when controller mesh is loaded.
  87637. */
  87638. this.onControllerMeshLoadedObservable = new BABYLON.Observable();
  87639. this._useCustomVRButton = false;
  87640. this._teleportationRequested = false;
  87641. this._teleportActive = false;
  87642. this._floorMeshesCollection = [];
  87643. this._rotationAllowed = true;
  87644. this._teleportBackwardsVector = new BABYLON.Vector3(0, -1, -1);
  87645. this._rotationRightAsked = false;
  87646. this._rotationLeftAsked = false;
  87647. this._isDefaultTeleportationTarget = true;
  87648. this._teleportationFillColor = "#444444";
  87649. this._teleportationBorderColor = "#FFFFFF";
  87650. this._rotationAngle = 0;
  87651. this._haloCenter = new BABYLON.Vector3(0, 0, 0);
  87652. this._padSensibilityUp = 0.65;
  87653. this._padSensibilityDown = 0.35;
  87654. this.leftController = null;
  87655. this.rightController = null;
  87656. /**
  87657. * Observable raised when a new mesh is selected based on meshSelectionPredicate
  87658. */
  87659. this.onNewMeshSelected = new BABYLON.Observable();
  87660. /**
  87661. * Observable raised when a new mesh is picked based on meshSelectionPredicate
  87662. */
  87663. this.onNewMeshPicked = new BABYLON.Observable();
  87664. /**
  87665. * Observable raised before camera teleportation
  87666. */
  87667. this.onBeforeCameraTeleport = new BABYLON.Observable();
  87668. /**
  87669. * Observable raised after camera teleportation
  87670. */
  87671. this.onAfterCameraTeleport = new BABYLON.Observable();
  87672. /**
  87673. * Observable raised when current selected mesh gets unselected
  87674. */
  87675. this.onSelectedMeshUnselected = new BABYLON.Observable();
  87676. /**
  87677. * Set teleportation enabled. If set to false camera teleportation will be disabled but camera rotation will be kept.
  87678. */
  87679. this.teleportationEnabled = true;
  87680. this._teleportationInitialized = false;
  87681. this._interactionsEnabled = false;
  87682. this._interactionsRequested = false;
  87683. this._displayGaze = true;
  87684. this._displayLaserPointer = true;
  87685. this._onResize = function () {
  87686. _this.moveButtonToBottomRight();
  87687. if (_this._fullscreenVRpresenting && _this._webVRready) {
  87688. _this.exitVR();
  87689. }
  87690. };
  87691. this._onFullscreenChange = function () {
  87692. if (document.fullscreen !== undefined) {
  87693. _this._fullscreenVRpresenting = document.fullscreen;
  87694. }
  87695. else if (document.mozFullScreen !== undefined) {
  87696. _this._fullscreenVRpresenting = document.mozFullScreen;
  87697. }
  87698. else if (document.webkitIsFullScreen !== undefined) {
  87699. _this._fullscreenVRpresenting = document.webkitIsFullScreen;
  87700. }
  87701. else if (document.msIsFullScreen !== undefined) {
  87702. _this._fullscreenVRpresenting = document.msIsFullScreen;
  87703. }
  87704. if (!_this._fullscreenVRpresenting && _this._canvas) {
  87705. _this.exitVR();
  87706. if (!_this._useCustomVRButton) {
  87707. _this._btnVR.style.top = _this._canvas.offsetTop + _this._canvas.offsetHeight - 70 + "px";
  87708. _this._btnVR.style.left = _this._canvas.offsetLeft + _this._canvas.offsetWidth - 100 + "px";
  87709. }
  87710. }
  87711. };
  87712. this.beforeRender = function () {
  87713. if (_this.leftController && _this.leftController._activePointer) {
  87714. _this._castRayAndSelectObject(_this.leftController);
  87715. }
  87716. if (_this.rightController && _this.rightController._activePointer) {
  87717. _this._castRayAndSelectObject(_this.rightController);
  87718. }
  87719. if (!(_this.leftController && _this.leftController._activePointer) && !(_this.rightController && _this.rightController._activePointer)) {
  87720. _this._castRayAndSelectObject(_this._cameraGazer);
  87721. }
  87722. else {
  87723. _this._cameraGazer._gazeTracker.isVisible = false;
  87724. }
  87725. };
  87726. this._onNewGamepadConnected = function (gamepad) {
  87727. if (gamepad.type !== BABYLON.Gamepad.POSE_ENABLED) {
  87728. if (gamepad.leftStick) {
  87729. gamepad.onleftstickchanged(function (stickValues) {
  87730. if (_this._teleportationInitialized && _this.teleportationEnabled) {
  87731. // Listening to classic/xbox gamepad only if no VR controller is active
  87732. if ((!_this.leftController && !_this.rightController) ||
  87733. ((_this.leftController && !_this.leftController._activePointer) &&
  87734. (_this.rightController && !_this.rightController._activePointer))) {
  87735. _this._checkTeleportWithRay(stickValues, _this._cameraGazer);
  87736. _this._checkTeleportBackwards(stickValues, _this._cameraGazer);
  87737. }
  87738. }
  87739. });
  87740. }
  87741. if (gamepad.rightStick) {
  87742. gamepad.onrightstickchanged(function (stickValues) {
  87743. if (_this._teleportationInitialized) {
  87744. _this._checkRotate(stickValues, _this._cameraGazer);
  87745. }
  87746. });
  87747. }
  87748. if (gamepad.type === BABYLON.Gamepad.XBOX) {
  87749. gamepad.onbuttondown(function (buttonPressed) {
  87750. if (_this._interactionsEnabled && buttonPressed === BABYLON.Xbox360Button.A) {
  87751. _this._cameraGazer._selectionPointerDown();
  87752. }
  87753. });
  87754. gamepad.onbuttonup(function (buttonPressed) {
  87755. if (_this._interactionsEnabled && buttonPressed === BABYLON.Xbox360Button.A) {
  87756. _this._cameraGazer._selectionPointerUp();
  87757. }
  87758. });
  87759. }
  87760. }
  87761. else {
  87762. var webVRController = gamepad;
  87763. var controller = new VRExperienceHelperControllerGazer(webVRController, _this._scene, _this._cameraGazer._gazeTracker);
  87764. if (webVRController.hand === "right" || (_this.leftController && _this.leftController.webVRController != webVRController)) {
  87765. _this.rightController = controller;
  87766. }
  87767. else {
  87768. _this.leftController = controller;
  87769. }
  87770. _this._tryEnableInteractionOnController(controller);
  87771. }
  87772. };
  87773. // 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
  87774. this._tryEnableInteractionOnController = function (controller) {
  87775. if (_this._interactionsRequested && !controller._interactionsEnabled) {
  87776. _this._enableInteractionOnController(controller);
  87777. }
  87778. if (_this._teleportationRequested && !controller._teleportationEnabled) {
  87779. _this._enableTeleportationOnController(controller);
  87780. }
  87781. };
  87782. this._onNewGamepadDisconnected = function (gamepad) {
  87783. if (gamepad instanceof BABYLON.WebVRController) {
  87784. if (gamepad.hand === "left" && _this.leftController != null) {
  87785. _this.leftController.dispose();
  87786. _this.leftController = null;
  87787. }
  87788. if (gamepad.hand === "right" && _this.rightController != null) {
  87789. _this.rightController.dispose();
  87790. _this.rightController = null;
  87791. }
  87792. }
  87793. };
  87794. this._workingVector = BABYLON.Vector3.Zero();
  87795. this._workingQuaternion = BABYLON.Quaternion.Identity();
  87796. this._workingMatrix = BABYLON.Matrix.Identity();
  87797. this._scene = scene;
  87798. this._canvas = scene.getEngine().getRenderingCanvas();
  87799. // Parse options
  87800. if (webVROptions.createFallbackVRDeviceOrientationFreeCamera === undefined) {
  87801. webVROptions.createFallbackVRDeviceOrientationFreeCamera = true;
  87802. }
  87803. if (webVROptions.createDeviceOrientationCamera === undefined) {
  87804. webVROptions.createDeviceOrientationCamera = true;
  87805. }
  87806. if (webVROptions.defaultHeight === undefined) {
  87807. webVROptions.defaultHeight = 1.7;
  87808. }
  87809. if (webVROptions.useCustomVRButton) {
  87810. this._useCustomVRButton = true;
  87811. if (webVROptions.customVRButton) {
  87812. this._btnVR = webVROptions.customVRButton;
  87813. }
  87814. }
  87815. if (webVROptions.rayLength) {
  87816. this._rayLength = webVROptions.rayLength;
  87817. }
  87818. this._defaultHeight = webVROptions.defaultHeight;
  87819. if (webVROptions.positionScale) {
  87820. this._rayLength *= webVROptions.positionScale;
  87821. this._defaultHeight *= webVROptions.positionScale;
  87822. }
  87823. // Set position
  87824. if (this._scene.activeCamera) {
  87825. this._position = this._scene.activeCamera.position.clone();
  87826. }
  87827. else {
  87828. this._position = new BABYLON.Vector3(0, this._defaultHeight, 0);
  87829. }
  87830. // Set non-vr camera
  87831. if (webVROptions.createDeviceOrientationCamera || !this._scene.activeCamera) {
  87832. this._deviceOrientationCamera = new BABYLON.DeviceOrientationCamera("deviceOrientationVRHelper", this._position.clone(), scene);
  87833. // Copy data from existing camera
  87834. if (this._scene.activeCamera) {
  87835. this._deviceOrientationCamera.minZ = this._scene.activeCamera.minZ;
  87836. this._deviceOrientationCamera.maxZ = this._scene.activeCamera.maxZ;
  87837. // Set rotation from previous camera
  87838. if (this._scene.activeCamera instanceof BABYLON.TargetCamera && this._scene.activeCamera.rotation) {
  87839. var targetCamera = this._scene.activeCamera;
  87840. if (targetCamera.rotationQuaternion) {
  87841. this._deviceOrientationCamera.rotationQuaternion.copyFrom(targetCamera.rotationQuaternion);
  87842. }
  87843. else {
  87844. this._deviceOrientationCamera.rotationQuaternion.copyFrom(BABYLON.Quaternion.RotationYawPitchRoll(targetCamera.rotation.y, targetCamera.rotation.x, targetCamera.rotation.z));
  87845. }
  87846. this._deviceOrientationCamera.rotation = targetCamera.rotation.clone();
  87847. }
  87848. }
  87849. this._scene.activeCamera = this._deviceOrientationCamera;
  87850. if (this._canvas) {
  87851. this._scene.activeCamera.attachControl(this._canvas);
  87852. }
  87853. }
  87854. else {
  87855. this._existingCamera = this._scene.activeCamera;
  87856. }
  87857. // Create VR cameras
  87858. if (webVROptions.createFallbackVRDeviceOrientationFreeCamera) {
  87859. this._vrDeviceOrientationCamera = new BABYLON.VRDeviceOrientationFreeCamera("VRDeviceOrientationVRHelper", this._position, this._scene);
  87860. }
  87861. this._webVRCamera = new BABYLON.WebVRFreeCamera("WebVRHelper", this._position, this._scene, webVROptions);
  87862. this._webVRCamera.useStandingMatrix();
  87863. this._cameraGazer = new VRExperienceHelperCameraGazer(function () { return _this.currentVRCamera; }, scene);
  87864. // Create default button
  87865. if (!this._useCustomVRButton) {
  87866. this._btnVR = document.createElement("BUTTON");
  87867. this._btnVR.className = "babylonVRicon";
  87868. this._btnVR.id = "babylonVRiconbtn";
  87869. this._btnVR.title = "Click to switch to VR";
  87870. 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) }";
  87871. css += ".babylonVRicon.vrdisplaypresenting { display: none; }";
  87872. // TODO: Add user feedback so that they know what state the VRDisplay is in (disconnected, connected, entering-VR)
  87873. // css += ".babylonVRicon.vrdisplaysupported { }";
  87874. // css += ".babylonVRicon.vrdisplayready { }";
  87875. // css += ".babylonVRicon.vrdisplayrequesting { }";
  87876. var style = document.createElement('style');
  87877. style.appendChild(document.createTextNode(css));
  87878. document.getElementsByTagName('head')[0].appendChild(style);
  87879. this.moveButtonToBottomRight();
  87880. }
  87881. // VR button click event
  87882. if (this._btnVR) {
  87883. this._btnVR.addEventListener("click", function () {
  87884. if (!_this.isInVRMode) {
  87885. _this.enterVR();
  87886. }
  87887. else {
  87888. _this.exitVR();
  87889. }
  87890. });
  87891. }
  87892. // Window events
  87893. window.addEventListener("resize", this._onResize);
  87894. document.addEventListener("fullscreenchange", this._onFullscreenChange, false);
  87895. document.addEventListener("mozfullscreenchange", this._onFullscreenChange, false);
  87896. document.addEventListener("webkitfullscreenchange", this._onFullscreenChange, false);
  87897. document.addEventListener("msfullscreenchange", this._onFullscreenChange, false);
  87898. // Display vr button when headset is connected
  87899. if (webVROptions.createFallbackVRDeviceOrientationFreeCamera) {
  87900. this.displayVRButton();
  87901. }
  87902. else {
  87903. this._scene.getEngine().onVRDisplayChangedObservable.add(function (e) {
  87904. if (e.vrDisplay) {
  87905. _this.displayVRButton();
  87906. }
  87907. });
  87908. }
  87909. // Exiting VR mode using 'ESC' key on desktop
  87910. this._onKeyDown = function (event) {
  87911. if (event.keyCode === 27 && _this.isInVRMode) {
  87912. _this.exitVR();
  87913. }
  87914. };
  87915. document.addEventListener("keydown", this._onKeyDown);
  87916. // Exiting VR mode double tapping the touch screen
  87917. this._scene.onPrePointerObservable.add(function (pointerInfo, eventState) {
  87918. if (_this.isInVRMode) {
  87919. _this.exitVR();
  87920. if (_this._fullscreenVRpresenting) {
  87921. _this._scene.getEngine().switchFullscreen(true);
  87922. }
  87923. }
  87924. }, BABYLON.PointerEventTypes.POINTERDOUBLETAP, false);
  87925. // Listen for WebVR display changes
  87926. this._onVRDisplayChanged = function (eventArgs) { return _this.onVRDisplayChanged(eventArgs); };
  87927. this._onVrDisplayPresentChange = function () { return _this.onVrDisplayPresentChange(); };
  87928. this._onVRRequestPresentStart = function () {
  87929. _this._webVRrequesting = true;
  87930. _this.updateButtonVisibility();
  87931. };
  87932. this._onVRRequestPresentComplete = function (success) {
  87933. _this._webVRrequesting = false;
  87934. _this.updateButtonVisibility();
  87935. };
  87936. scene.getEngine().onVRDisplayChangedObservable.add(this._onVRDisplayChanged);
  87937. scene.getEngine().onVRRequestPresentStart.add(this._onVRRequestPresentStart);
  87938. scene.getEngine().onVRRequestPresentComplete.add(this._onVRRequestPresentComplete);
  87939. window.addEventListener('vrdisplaypresentchange', this._onVrDisplayPresentChange);
  87940. scene.onDisposeObservable.add(function () {
  87941. _this.dispose();
  87942. });
  87943. // Gamepad connection events
  87944. this._webVRCamera.onControllerMeshLoadedObservable.add(function (webVRController) { return _this._onDefaultMeshLoaded(webVRController); });
  87945. this._scene.gamepadManager.onGamepadConnectedObservable.add(this._onNewGamepadConnected);
  87946. this._scene.gamepadManager.onGamepadDisconnectedObservable.add(this._onNewGamepadDisconnected);
  87947. this.updateButtonVisibility();
  87948. //create easing functions
  87949. this._circleEase = new BABYLON.CircleEase();
  87950. this._circleEase.setEasingMode(BABYLON.EasingFunction.EASINGMODE_EASEINOUT);
  87951. }
  87952. Object.defineProperty(VRExperienceHelper.prototype, "onEnteringVR", {
  87953. /** Return this.onEnteringVRObservable
  87954. * Note: This one is for backward compatibility. Please use onEnteringVRObservable directly
  87955. */
  87956. get: function () {
  87957. return this.onEnteringVRObservable;
  87958. },
  87959. enumerable: true,
  87960. configurable: true
  87961. });
  87962. Object.defineProperty(VRExperienceHelper.prototype, "onExitingVR", {
  87963. /** Return this.onExitingVRObservable
  87964. * Note: This one is for backward compatibility. Please use onExitingVRObservable directly
  87965. */
  87966. get: function () {
  87967. return this.onExitingVRObservable;
  87968. },
  87969. enumerable: true,
  87970. configurable: true
  87971. });
  87972. Object.defineProperty(VRExperienceHelper.prototype, "onControllerMeshLoaded", {
  87973. /** Return this.onControllerMeshLoadedObservable
  87974. * Note: This one is for backward compatibility. Please use onControllerMeshLoadedObservable directly
  87975. */
  87976. get: function () {
  87977. return this.onControllerMeshLoadedObservable;
  87978. },
  87979. enumerable: true,
  87980. configurable: true
  87981. });
  87982. Object.defineProperty(VRExperienceHelper.prototype, "teleportationTarget", {
  87983. /**
  87984. * The mesh used to display where the user is going to teleport.
  87985. */
  87986. get: function () {
  87987. return this._teleportationTarget;
  87988. },
  87989. /**
  87990. * Sets the mesh to be used to display where the user is going to teleport.
  87991. */
  87992. set: function (value) {
  87993. if (value) {
  87994. value.name = "teleportationTarget";
  87995. this._isDefaultTeleportationTarget = false;
  87996. this._teleportationTarget = value;
  87997. }
  87998. },
  87999. enumerable: true,
  88000. configurable: true
  88001. });
  88002. Object.defineProperty(VRExperienceHelper.prototype, "gazeTrackerMesh", {
  88003. /**
  88004. * The mesh used to display where the user is selecting,
  88005. * when set bakeCurrentTransformIntoVertices will be called on the mesh.
  88006. * See http://doc.babylonjs.com/resources/baking_transformations
  88007. */
  88008. get: function () {
  88009. return this._cameraGazer._gazeTracker;
  88010. },
  88011. set: function (value) {
  88012. if (value) {
  88013. this._cameraGazer._gazeTracker = value;
  88014. this._cameraGazer._gazeTracker.bakeCurrentTransformIntoVertices();
  88015. this._cameraGazer._gazeTracker.isPickable = false;
  88016. this._cameraGazer._gazeTracker.isVisible = false;
  88017. this._cameraGazer._gazeTracker.name = "gazeTracker";
  88018. if (this.leftController) {
  88019. this.leftController._gazeTracker = this._cameraGazer._gazeTracker.clone("gazeTracker");
  88020. }
  88021. if (this.rightController) {
  88022. this.rightController._gazeTracker = this._cameraGazer._gazeTracker.clone("gazeTracker");
  88023. }
  88024. }
  88025. },
  88026. enumerable: true,
  88027. configurable: true
  88028. });
  88029. Object.defineProperty(VRExperienceHelper.prototype, "displayGaze", {
  88030. /**
  88031. * If the ray of the gaze should be displayed.
  88032. */
  88033. get: function () {
  88034. return this._displayGaze;
  88035. },
  88036. /**
  88037. * Sets if the ray of the gaze should be displayed.
  88038. */
  88039. set: function (value) {
  88040. this._displayGaze = value;
  88041. if (!value) {
  88042. this._cameraGazer._gazeTracker.isVisible = false;
  88043. if (this.leftController) {
  88044. this.leftController._gazeTracker.isVisible = false;
  88045. }
  88046. if (this.rightController) {
  88047. this.rightController._gazeTracker.isVisible = false;
  88048. }
  88049. }
  88050. },
  88051. enumerable: true,
  88052. configurable: true
  88053. });
  88054. Object.defineProperty(VRExperienceHelper.prototype, "displayLaserPointer", {
  88055. /**
  88056. * If the ray of the LaserPointer should be displayed.
  88057. */
  88058. get: function () {
  88059. return this._displayLaserPointer;
  88060. },
  88061. /**
  88062. * Sets if the ray of the LaserPointer should be displayed.
  88063. */
  88064. set: function (value) {
  88065. this._displayLaserPointer = value;
  88066. if (!value) {
  88067. if (this.rightController) {
  88068. this.rightController._deactivatePointer();
  88069. this.rightController._gazeTracker.isVisible = false;
  88070. }
  88071. if (this.leftController) {
  88072. this.leftController._deactivatePointer();
  88073. this.leftController._gazeTracker.isVisible = false;
  88074. }
  88075. }
  88076. else {
  88077. if (this.rightController) {
  88078. this.rightController._activatePointer();
  88079. }
  88080. else if (this.leftController) {
  88081. this.leftController._activatePointer();
  88082. }
  88083. }
  88084. },
  88085. enumerable: true,
  88086. configurable: true
  88087. });
  88088. Object.defineProperty(VRExperienceHelper.prototype, "deviceOrientationCamera", {
  88089. /**
  88090. * The deviceOrientationCamera used as the camera when not in VR.
  88091. */
  88092. get: function () {
  88093. return this._deviceOrientationCamera;
  88094. },
  88095. enumerable: true,
  88096. configurable: true
  88097. });
  88098. Object.defineProperty(VRExperienceHelper.prototype, "currentVRCamera", {
  88099. /**
  88100. * Based on the current WebVR support, returns the current VR camera used.
  88101. */
  88102. get: function () {
  88103. if (this._webVRready) {
  88104. return this._webVRCamera;
  88105. }
  88106. else {
  88107. return this._scene.activeCamera;
  88108. }
  88109. },
  88110. enumerable: true,
  88111. configurable: true
  88112. });
  88113. Object.defineProperty(VRExperienceHelper.prototype, "webVRCamera", {
  88114. /**
  88115. * The webVRCamera which is used when in VR.
  88116. */
  88117. get: function () {
  88118. return this._webVRCamera;
  88119. },
  88120. enumerable: true,
  88121. configurable: true
  88122. });
  88123. Object.defineProperty(VRExperienceHelper.prototype, "vrDeviceOrientationCamera", {
  88124. /**
  88125. * The deviceOrientationCamera that is used as a fallback when vr device is not connected.
  88126. */
  88127. get: function () {
  88128. return this._vrDeviceOrientationCamera;
  88129. },
  88130. enumerable: true,
  88131. configurable: true
  88132. });
  88133. Object.defineProperty(VRExperienceHelper.prototype, "_teleportationRequestInitiated", {
  88134. get: function () {
  88135. var result = this._cameraGazer._teleportationRequestInitiated
  88136. || (this.leftController !== null && this.leftController._teleportationRequestInitiated)
  88137. || (this.rightController !== null && this.rightController._teleportationRequestInitiated);
  88138. return result;
  88139. },
  88140. enumerable: true,
  88141. configurable: true
  88142. });
  88143. // Raised when one of the controller has loaded successfully its associated default mesh
  88144. VRExperienceHelper.prototype._onDefaultMeshLoaded = function (webVRController) {
  88145. if (this.leftController && this.leftController.webVRController == webVRController) {
  88146. if (webVRController.mesh) {
  88147. this.leftController._setLaserPointerParent(webVRController.mesh);
  88148. }
  88149. }
  88150. if (this.rightController && this.rightController.webVRController == webVRController) {
  88151. if (webVRController.mesh) {
  88152. this.rightController._setLaserPointerParent(webVRController.mesh);
  88153. }
  88154. }
  88155. try {
  88156. this.onControllerMeshLoadedObservable.notifyObservers(webVRController);
  88157. }
  88158. catch (err) {
  88159. BABYLON.Tools.Warn("Error in your custom logic onControllerMeshLoaded: " + err);
  88160. }
  88161. };
  88162. Object.defineProperty(VRExperienceHelper.prototype, "isInVRMode", {
  88163. /**
  88164. * Gets a value indicating if we are currently in VR mode.
  88165. */
  88166. get: function () {
  88167. return this._webVRpresenting || this._fullscreenVRpresenting;
  88168. },
  88169. enumerable: true,
  88170. configurable: true
  88171. });
  88172. VRExperienceHelper.prototype.onVrDisplayPresentChange = function () {
  88173. var vrDisplay = this._scene.getEngine().getVRDevice();
  88174. if (vrDisplay) {
  88175. var wasPresenting = this._webVRpresenting;
  88176. // A VR display is connected
  88177. this._webVRpresenting = vrDisplay.isPresenting;
  88178. if (wasPresenting && !this._webVRpresenting)
  88179. this.exitVR();
  88180. }
  88181. else {
  88182. BABYLON.Tools.Warn('Detected VRDisplayPresentChange on an unknown VRDisplay. Did you can enterVR on the vrExperienceHelper?');
  88183. }
  88184. this.updateButtonVisibility();
  88185. };
  88186. VRExperienceHelper.prototype.onVRDisplayChanged = function (eventArgs) {
  88187. this._webVRsupported = eventArgs.vrSupported;
  88188. this._webVRready = !!eventArgs.vrDisplay;
  88189. this._webVRpresenting = eventArgs.vrDisplay && eventArgs.vrDisplay.isPresenting;
  88190. this.updateButtonVisibility();
  88191. };
  88192. VRExperienceHelper.prototype.moveButtonToBottomRight = function () {
  88193. if (this._canvas && !this._useCustomVRButton) {
  88194. this._btnVR.style.top = this._canvas.offsetTop + this._canvas.offsetHeight - 70 + "px";
  88195. this._btnVR.style.left = this._canvas.offsetLeft + this._canvas.offsetWidth - 100 + "px";
  88196. }
  88197. };
  88198. VRExperienceHelper.prototype.displayVRButton = function () {
  88199. if (!this._useCustomVRButton && !this._btnVRDisplayed) {
  88200. document.body.appendChild(this._btnVR);
  88201. this._btnVRDisplayed = true;
  88202. }
  88203. };
  88204. VRExperienceHelper.prototype.updateButtonVisibility = function () {
  88205. if (!this._btnVR || this._useCustomVRButton) {
  88206. return;
  88207. }
  88208. this._btnVR.className = "babylonVRicon";
  88209. if (this.isInVRMode) {
  88210. this._btnVR.className += " vrdisplaypresenting";
  88211. }
  88212. else {
  88213. if (this._webVRready)
  88214. this._btnVR.className += " vrdisplayready";
  88215. if (this._webVRsupported)
  88216. this._btnVR.className += " vrdisplaysupported";
  88217. if (this._webVRrequesting)
  88218. this._btnVR.className += " vrdisplayrequesting";
  88219. }
  88220. };
  88221. /**
  88222. * Attempt to enter VR. If a headset is connected and ready, will request present on that.
  88223. * Otherwise, will use the fullscreen API.
  88224. */
  88225. VRExperienceHelper.prototype.enterVR = function () {
  88226. if (this.onEnteringVRObservable) {
  88227. try {
  88228. this.onEnteringVRObservable.notifyObservers(this);
  88229. }
  88230. catch (err) {
  88231. BABYLON.Tools.Warn("Error in your custom logic onEnteringVR: " + err);
  88232. }
  88233. }
  88234. if (this._scene.activeCamera) {
  88235. this._position = this._scene.activeCamera.position.clone();
  88236. // make sure that we return to the last active camera
  88237. this._existingCamera = this._scene.activeCamera;
  88238. }
  88239. if (this._webVRrequesting)
  88240. return;
  88241. // If WebVR is supported and a headset is connected
  88242. if (this._webVRready) {
  88243. if (!this._webVRpresenting) {
  88244. this._webVRCamera.position = this._position;
  88245. this._scene.activeCamera = this._webVRCamera;
  88246. }
  88247. }
  88248. else if (this._vrDeviceOrientationCamera) {
  88249. this._vrDeviceOrientationCamera.position = this._position;
  88250. if (this._scene.activeCamera) {
  88251. this._vrDeviceOrientationCamera.minZ = this._scene.activeCamera.minZ;
  88252. }
  88253. this._scene.activeCamera = this._vrDeviceOrientationCamera;
  88254. this._scene.getEngine().switchFullscreen(true);
  88255. this.updateButtonVisibility();
  88256. }
  88257. if (this._scene.activeCamera && this._canvas) {
  88258. this._scene.activeCamera.attachControl(this._canvas);
  88259. }
  88260. if (this._interactionsEnabled) {
  88261. this._scene.registerBeforeRender(this.beforeRender);
  88262. }
  88263. };
  88264. /**
  88265. * Attempt to exit VR, or fullscreen.
  88266. */
  88267. VRExperienceHelper.prototype.exitVR = function () {
  88268. if (this.onExitingVRObservable) {
  88269. try {
  88270. this.onExitingVRObservable.notifyObservers(this);
  88271. }
  88272. catch (err) {
  88273. BABYLON.Tools.Warn("Error in your custom logic onExitingVR: " + err);
  88274. }
  88275. }
  88276. if (this._webVRpresenting) {
  88277. this._scene.getEngine().disableVR();
  88278. }
  88279. if (this._scene.activeCamera) {
  88280. this._position = this._scene.activeCamera.position.clone();
  88281. }
  88282. if (this._deviceOrientationCamera) {
  88283. this._deviceOrientationCamera.position = this._position;
  88284. this._scene.activeCamera = this._deviceOrientationCamera;
  88285. if (this._canvas) {
  88286. this._scene.activeCamera.attachControl(this._canvas);
  88287. }
  88288. }
  88289. else if (this._existingCamera) {
  88290. this._existingCamera.position = this._position;
  88291. this._scene.activeCamera = this._existingCamera;
  88292. }
  88293. this.updateButtonVisibility();
  88294. if (this._interactionsEnabled) {
  88295. this._scene.unregisterBeforeRender(this.beforeRender);
  88296. }
  88297. // resize to update width and height when exiting vr exits fullscreen
  88298. this._scene.getEngine().resize();
  88299. };
  88300. Object.defineProperty(VRExperienceHelper.prototype, "position", {
  88301. /**
  88302. * The position of the vr experience helper.
  88303. */
  88304. get: function () {
  88305. return this._position;
  88306. },
  88307. /**
  88308. * Sets the position of the vr experience helper.
  88309. */
  88310. set: function (value) {
  88311. this._position = value;
  88312. if (this._scene.activeCamera) {
  88313. this._scene.activeCamera.position = value;
  88314. }
  88315. },
  88316. enumerable: true,
  88317. configurable: true
  88318. });
  88319. /**
  88320. * Enables controllers and user interactions suck as selecting and object or clicking on an object.
  88321. */
  88322. VRExperienceHelper.prototype.enableInteractions = function () {
  88323. var _this = this;
  88324. if (!this._interactionsEnabled) {
  88325. this._interactionsRequested = true;
  88326. if (this.leftController) {
  88327. this._enableInteractionOnController(this.leftController);
  88328. }
  88329. if (this.rightController) {
  88330. this._enableInteractionOnController(this.rightController);
  88331. }
  88332. this.raySelectionPredicate = function (mesh) {
  88333. return mesh.isVisible;
  88334. };
  88335. this.meshSelectionPredicate = function (mesh) {
  88336. return true;
  88337. };
  88338. this._raySelectionPredicate = function (mesh) {
  88339. if (_this._isTeleportationFloor(mesh) || (mesh.name.indexOf("gazeTracker") === -1
  88340. && mesh.name.indexOf("teleportationTarget") === -1
  88341. && mesh.name.indexOf("torusTeleportation") === -1
  88342. && mesh.name.indexOf("laserPointer") === -1)) {
  88343. return _this.raySelectionPredicate(mesh);
  88344. }
  88345. return false;
  88346. };
  88347. this._interactionsEnabled = true;
  88348. }
  88349. };
  88350. VRExperienceHelper.prototype._isTeleportationFloor = function (mesh) {
  88351. for (var i = 0; i < this._floorMeshesCollection.length; i++) {
  88352. if (this._floorMeshesCollection[i].id === mesh.id) {
  88353. return true;
  88354. }
  88355. }
  88356. if (this._floorMeshName && mesh.name === this._floorMeshName) {
  88357. return true;
  88358. }
  88359. return false;
  88360. };
  88361. /**
  88362. * Adds a floor mesh to be used for teleportation.
  88363. * @param floorMesh the mesh to be used for teleportation.
  88364. */
  88365. VRExperienceHelper.prototype.addFloorMesh = function (floorMesh) {
  88366. if (!this._floorMeshesCollection) {
  88367. return;
  88368. }
  88369. if (this._floorMeshesCollection.indexOf(floorMesh) > -1) {
  88370. return;
  88371. }
  88372. this._floorMeshesCollection.push(floorMesh);
  88373. };
  88374. /**
  88375. * Removes a floor mesh from being used for teleportation.
  88376. * @param floorMesh the mesh to be removed.
  88377. */
  88378. VRExperienceHelper.prototype.removeFloorMesh = function (floorMesh) {
  88379. if (!this._floorMeshesCollection) {
  88380. return;
  88381. }
  88382. var meshIndex = this._floorMeshesCollection.indexOf(floorMesh);
  88383. if (meshIndex !== -1) {
  88384. this._floorMeshesCollection.splice(meshIndex, 1);
  88385. }
  88386. };
  88387. /**
  88388. * Enables interactions and teleportation using the VR controllers and gaze.
  88389. * @param vrTeleportationOptions options to modify teleportation behavior.
  88390. */
  88391. VRExperienceHelper.prototype.enableTeleportation = function (vrTeleportationOptions) {
  88392. if (vrTeleportationOptions === void 0) { vrTeleportationOptions = {}; }
  88393. if (!this._teleportationInitialized) {
  88394. this._teleportationRequested = true;
  88395. this.enableInteractions();
  88396. if (vrTeleportationOptions.floorMeshName) {
  88397. this._floorMeshName = vrTeleportationOptions.floorMeshName;
  88398. }
  88399. if (vrTeleportationOptions.floorMeshes) {
  88400. this._floorMeshesCollection = vrTeleportationOptions.floorMeshes;
  88401. }
  88402. if (this.leftController != null) {
  88403. this._enableTeleportationOnController(this.leftController);
  88404. }
  88405. if (this.rightController != null) {
  88406. this._enableTeleportationOnController(this.rightController);
  88407. }
  88408. // Creates an image processing post process for the vignette not relying
  88409. // on the main scene configuration for image processing to reduce setup and spaces
  88410. // (gamma/linear) conflicts.
  88411. var imageProcessingConfiguration = new BABYLON.ImageProcessingConfiguration();
  88412. imageProcessingConfiguration.vignetteColor = new BABYLON.Color4(0, 0, 0, 0);
  88413. imageProcessingConfiguration.vignetteEnabled = true;
  88414. this._postProcessMove = new BABYLON.ImageProcessingPostProcess("postProcessMove", 1.0, this._webVRCamera, undefined, undefined, undefined, undefined, imageProcessingConfiguration);
  88415. this._webVRCamera.detachPostProcess(this._postProcessMove);
  88416. this._teleportationInitialized = true;
  88417. if (this._isDefaultTeleportationTarget) {
  88418. this._createTeleportationCircles();
  88419. this._teleportationTarget.scaling.scaleInPlace(this._webVRCamera.deviceScaleFactor);
  88420. }
  88421. }
  88422. };
  88423. VRExperienceHelper.prototype._enableInteractionOnController = function (controller) {
  88424. var _this = this;
  88425. var controllerMesh = controller.webVRController.mesh;
  88426. if (controllerMesh) {
  88427. controller._interactionsEnabled = true;
  88428. controller._activatePointer();
  88429. controller.webVRController.onMainButtonStateChangedObservable.add(function (stateObject) {
  88430. // Enabling / disabling laserPointer
  88431. if (_this._displayLaserPointer && stateObject.value === 1) {
  88432. if (controller._activePointer) {
  88433. controller._deactivatePointer();
  88434. }
  88435. else {
  88436. controller._activatePointer();
  88437. }
  88438. if (_this.displayGaze) {
  88439. controller._gazeTracker.isVisible = controller._activePointer;
  88440. }
  88441. }
  88442. });
  88443. controller.webVRController.onTriggerStateChangedObservable.add(function (stateObject) {
  88444. if (!controller._pointerDownOnMeshAsked) {
  88445. if (stateObject.value > _this._padSensibilityUp) {
  88446. controller._selectionPointerDown();
  88447. }
  88448. }
  88449. else if (stateObject.value < _this._padSensibilityDown) {
  88450. controller._selectionPointerUp();
  88451. }
  88452. });
  88453. }
  88454. };
  88455. VRExperienceHelper.prototype._checkTeleportWithRay = function (stateObject, gazer) {
  88456. // Dont teleport if another gaze already requested teleportation
  88457. if (this._teleportationRequestInitiated && !gazer._teleportationRequestInitiated) {
  88458. return;
  88459. }
  88460. if (!gazer._teleportationRequestInitiated) {
  88461. if (stateObject.y < -this._padSensibilityUp && gazer._dpadPressed) {
  88462. gazer._activatePointer();
  88463. gazer._teleportationRequestInitiated = true;
  88464. }
  88465. }
  88466. else {
  88467. // Listening to the proper controller values changes to confirm teleportation
  88468. if (Math.sqrt(stateObject.y * stateObject.y + stateObject.x * stateObject.x) < this._padSensibilityDown) {
  88469. if (this._teleportActive) {
  88470. this._teleportCamera(this._haloCenter);
  88471. }
  88472. gazer._teleportationRequestInitiated = false;
  88473. }
  88474. }
  88475. };
  88476. VRExperienceHelper.prototype._checkRotate = function (stateObject, gazer) {
  88477. // Only rotate when user is not currently selecting a teleportation location
  88478. if (gazer._teleportationRequestInitiated) {
  88479. return;
  88480. }
  88481. if (!this._rotationLeftAsked) {
  88482. if (stateObject.x < -this._padSensibilityUp && gazer._dpadPressed) {
  88483. this._rotationLeftAsked = true;
  88484. if (this._rotationAllowed) {
  88485. this._rotateCamera(false);
  88486. }
  88487. }
  88488. }
  88489. else {
  88490. if (stateObject.x > -this._padSensibilityDown) {
  88491. this._rotationLeftAsked = false;
  88492. }
  88493. }
  88494. if (!this._rotationRightAsked) {
  88495. if (stateObject.x > this._padSensibilityUp && gazer._dpadPressed) {
  88496. this._rotationRightAsked = true;
  88497. if (this._rotationAllowed) {
  88498. this._rotateCamera(true);
  88499. }
  88500. }
  88501. }
  88502. else {
  88503. if (stateObject.x < this._padSensibilityDown) {
  88504. this._rotationRightAsked = false;
  88505. }
  88506. }
  88507. };
  88508. VRExperienceHelper.prototype._checkTeleportBackwards = function (stateObject, gazer) {
  88509. // Only teleport backwards when user is not currently selecting a teleportation location
  88510. if (gazer._teleportationRequestInitiated) {
  88511. return;
  88512. }
  88513. // Teleport backwards
  88514. if (stateObject.y > this._padSensibilityUp && gazer._dpadPressed) {
  88515. if (!gazer._teleportationBackRequestInitiated) {
  88516. if (!this.currentVRCamera) {
  88517. return;
  88518. }
  88519. // Get rotation and position of the current camera
  88520. var rotation = BABYLON.Quaternion.FromRotationMatrix(this.currentVRCamera.getWorldMatrix().getRotationMatrix());
  88521. var position = this.currentVRCamera.position;
  88522. // If the camera has device position, use that instead
  88523. if (this.currentVRCamera.devicePosition && this.currentVRCamera.deviceRotationQuaternion) {
  88524. rotation = this.currentVRCamera.deviceRotationQuaternion;
  88525. position = this.currentVRCamera.devicePosition;
  88526. }
  88527. // Get matrix with only the y rotation of the device rotation
  88528. rotation.toEulerAnglesToRef(this._workingVector);
  88529. this._workingVector.z = 0;
  88530. this._workingVector.x = 0;
  88531. BABYLON.Quaternion.RotationYawPitchRollToRef(this._workingVector.y, this._workingVector.x, this._workingVector.z, this._workingQuaternion);
  88532. this._workingQuaternion.toRotationMatrix(this._workingMatrix);
  88533. // Rotate backwards ray by device rotation to cast at the ground behind the user
  88534. BABYLON.Vector3.TransformCoordinatesToRef(this._teleportBackwardsVector, this._workingMatrix, this._workingVector);
  88535. // Teleport if ray hit the ground and is not to far away eg. backwards off a cliff
  88536. var ray = new BABYLON.Ray(position, this._workingVector);
  88537. var hit = this._scene.pickWithRay(ray, this._raySelectionPredicate);
  88538. if (hit && hit.pickedPoint && hit.pickedMesh && this._isTeleportationFloor(hit.pickedMesh) && hit.distance < 5) {
  88539. this._teleportCamera(hit.pickedPoint);
  88540. }
  88541. gazer._teleportationBackRequestInitiated = true;
  88542. }
  88543. }
  88544. else {
  88545. gazer._teleportationBackRequestInitiated = false;
  88546. }
  88547. };
  88548. VRExperienceHelper.prototype._enableTeleportationOnController = function (controller) {
  88549. var _this = this;
  88550. var controllerMesh = controller.webVRController.mesh;
  88551. if (controllerMesh) {
  88552. if (!controller._interactionsEnabled) {
  88553. this._enableInteractionOnController(controller);
  88554. }
  88555. controller._interactionsEnabled = true;
  88556. controller._teleportationEnabled = true;
  88557. if (controller.webVRController.controllerType === BABYLON.PoseEnabledControllerType.VIVE) {
  88558. controller._dpadPressed = false;
  88559. controller.webVRController.onPadStateChangedObservable.add(function (stateObject) {
  88560. controller._dpadPressed = stateObject.pressed;
  88561. if (!controller._dpadPressed) {
  88562. _this._rotationLeftAsked = false;
  88563. _this._rotationRightAsked = false;
  88564. controller._teleportationBackRequestInitiated = false;
  88565. }
  88566. });
  88567. }
  88568. controller.webVRController.onPadValuesChangedObservable.add(function (stateObject) {
  88569. if (_this.teleportationEnabled) {
  88570. _this._checkTeleportBackwards(stateObject, controller);
  88571. _this._checkTeleportWithRay(stateObject, controller);
  88572. }
  88573. _this._checkRotate(stateObject, controller);
  88574. });
  88575. }
  88576. };
  88577. VRExperienceHelper.prototype._createTeleportationCircles = function () {
  88578. this._teleportationTarget = BABYLON.Mesh.CreateGround("teleportationTarget", 2, 2, 2, this._scene);
  88579. this._teleportationTarget.isPickable = false;
  88580. var length = 512;
  88581. var dynamicTexture = new BABYLON.DynamicTexture("DynamicTexture", length, this._scene, true);
  88582. dynamicTexture.hasAlpha = true;
  88583. var context = dynamicTexture.getContext();
  88584. var centerX = length / 2;
  88585. var centerY = length / 2;
  88586. var radius = 200;
  88587. context.beginPath();
  88588. context.arc(centerX, centerY, radius, 0, 2 * Math.PI, false);
  88589. context.fillStyle = this._teleportationFillColor;
  88590. context.fill();
  88591. context.lineWidth = 10;
  88592. context.strokeStyle = this._teleportationBorderColor;
  88593. context.stroke();
  88594. context.closePath();
  88595. dynamicTexture.update();
  88596. var teleportationCircleMaterial = new BABYLON.StandardMaterial("TextPlaneMaterial", this._scene);
  88597. teleportationCircleMaterial.diffuseTexture = dynamicTexture;
  88598. this._teleportationTarget.material = teleportationCircleMaterial;
  88599. var torus = BABYLON.Mesh.CreateTorus("torusTeleportation", 0.75, 0.1, 25, this._scene, false);
  88600. torus.isPickable = false;
  88601. torus.parent = this._teleportationTarget;
  88602. var animationInnerCircle = new BABYLON.Animation("animationInnerCircle", "position.y", 30, BABYLON.Animation.ANIMATIONTYPE_FLOAT, BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE);
  88603. var keys = [];
  88604. keys.push({
  88605. frame: 0,
  88606. value: 0
  88607. });
  88608. keys.push({
  88609. frame: 30,
  88610. value: 0.4
  88611. });
  88612. keys.push({
  88613. frame: 60,
  88614. value: 0
  88615. });
  88616. animationInnerCircle.setKeys(keys);
  88617. var easingFunction = new BABYLON.SineEase();
  88618. easingFunction.setEasingMode(BABYLON.EasingFunction.EASINGMODE_EASEINOUT);
  88619. animationInnerCircle.setEasingFunction(easingFunction);
  88620. torus.animations = [];
  88621. torus.animations.push(animationInnerCircle);
  88622. this._scene.beginAnimation(torus, 0, 60, true);
  88623. this._hideTeleportationTarget();
  88624. };
  88625. VRExperienceHelper.prototype._displayTeleportationTarget = function () {
  88626. this._teleportActive = true;
  88627. if (this._teleportationInitialized) {
  88628. this._teleportationTarget.isVisible = true;
  88629. if (this._isDefaultTeleportationTarget) {
  88630. this._teleportationTarget.getChildren()[0].isVisible = true;
  88631. }
  88632. }
  88633. };
  88634. VRExperienceHelper.prototype._hideTeleportationTarget = function () {
  88635. this._teleportActive = false;
  88636. if (this._teleportationInitialized) {
  88637. this._teleportationTarget.isVisible = false;
  88638. if (this._isDefaultTeleportationTarget) {
  88639. this._teleportationTarget.getChildren()[0].isVisible = false;
  88640. }
  88641. }
  88642. };
  88643. VRExperienceHelper.prototype._rotateCamera = function (right) {
  88644. var _this = this;
  88645. if (!(this.currentVRCamera instanceof BABYLON.FreeCamera)) {
  88646. return;
  88647. }
  88648. if (right) {
  88649. this._rotationAngle++;
  88650. }
  88651. else {
  88652. this._rotationAngle--;
  88653. }
  88654. this.currentVRCamera.animations = [];
  88655. var target = BABYLON.Quaternion.FromRotationMatrix(BABYLON.Matrix.RotationY(Math.PI / 4 * this._rotationAngle));
  88656. var animationRotation = new BABYLON.Animation("animationRotation", "rotationQuaternion", 90, BABYLON.Animation.ANIMATIONTYPE_QUATERNION, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  88657. var animationRotationKeys = [];
  88658. animationRotationKeys.push({
  88659. frame: 0,
  88660. value: this.currentVRCamera.rotationQuaternion
  88661. });
  88662. animationRotationKeys.push({
  88663. frame: 6,
  88664. value: target
  88665. });
  88666. animationRotation.setKeys(animationRotationKeys);
  88667. animationRotation.setEasingFunction(this._circleEase);
  88668. this.currentVRCamera.animations.push(animationRotation);
  88669. this._postProcessMove.animations = [];
  88670. var animationPP = new BABYLON.Animation("animationPP", "vignetteWeight", 90, BABYLON.Animation.ANIMATIONTYPE_FLOAT, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  88671. var vignetteWeightKeys = [];
  88672. vignetteWeightKeys.push({
  88673. frame: 0,
  88674. value: 0
  88675. });
  88676. vignetteWeightKeys.push({
  88677. frame: 3,
  88678. value: 4
  88679. });
  88680. vignetteWeightKeys.push({
  88681. frame: 6,
  88682. value: 0
  88683. });
  88684. animationPP.setKeys(vignetteWeightKeys);
  88685. animationPP.setEasingFunction(this._circleEase);
  88686. this._postProcessMove.animations.push(animationPP);
  88687. var animationPP2 = new BABYLON.Animation("animationPP2", "vignetteStretch", 90, BABYLON.Animation.ANIMATIONTYPE_FLOAT, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  88688. var vignetteStretchKeys = [];
  88689. vignetteStretchKeys.push({
  88690. frame: 0,
  88691. value: 0
  88692. });
  88693. vignetteStretchKeys.push({
  88694. frame: 3,
  88695. value: 10
  88696. });
  88697. vignetteStretchKeys.push({
  88698. frame: 6,
  88699. value: 0
  88700. });
  88701. animationPP2.setKeys(vignetteStretchKeys);
  88702. animationPP2.setEasingFunction(this._circleEase);
  88703. this._postProcessMove.animations.push(animationPP2);
  88704. this._postProcessMove.imageProcessingConfiguration.vignetteWeight = 0;
  88705. this._postProcessMove.imageProcessingConfiguration.vignetteStretch = 0;
  88706. this._postProcessMove.samples = 4;
  88707. this._webVRCamera.attachPostProcess(this._postProcessMove);
  88708. this._scene.beginAnimation(this._postProcessMove, 0, 6, false, 1, function () {
  88709. _this._webVRCamera.detachPostProcess(_this._postProcessMove);
  88710. });
  88711. this._scene.beginAnimation(this.currentVRCamera, 0, 6, false, 1);
  88712. };
  88713. VRExperienceHelper.prototype._moveTeleportationSelectorTo = function (hit, gazer) {
  88714. if (hit.pickedPoint) {
  88715. if (gazer._teleportationRequestInitiated) {
  88716. this._displayTeleportationTarget();
  88717. this._haloCenter.copyFrom(hit.pickedPoint);
  88718. this._teleportationTarget.position.copyFrom(hit.pickedPoint);
  88719. }
  88720. var pickNormal = hit.getNormal(true, false);
  88721. if (pickNormal) {
  88722. var axis1 = BABYLON.Vector3.Cross(BABYLON.Axis.Y, pickNormal);
  88723. var axis2 = BABYLON.Vector3.Cross(pickNormal, axis1);
  88724. BABYLON.Vector3.RotationFromAxisToRef(axis2, pickNormal, axis1, this._teleportationTarget.rotation);
  88725. }
  88726. this._teleportationTarget.position.y += 0.1;
  88727. }
  88728. };
  88729. VRExperienceHelper.prototype._teleportCamera = function (location) {
  88730. var _this = this;
  88731. if (!(this.currentVRCamera instanceof BABYLON.FreeCamera)) {
  88732. return;
  88733. }
  88734. // Teleport the hmd to where the user is looking by moving the anchor to where they are looking minus the
  88735. // offset of the headset from the anchor.
  88736. if (this.webVRCamera.leftCamera) {
  88737. this._workingVector.copyFrom(this.webVRCamera.leftCamera.globalPosition);
  88738. this._workingVector.subtractInPlace(this.webVRCamera.position);
  88739. location.subtractToRef(this._workingVector, this._workingVector);
  88740. }
  88741. else {
  88742. this._workingVector.copyFrom(location);
  88743. }
  88744. // Add height to account for user's height offset
  88745. if (this.isInVRMode) {
  88746. this._workingVector.y += this.webVRCamera.deviceDistanceToRoomGround() * this._webVRCamera.deviceScaleFactor;
  88747. }
  88748. else {
  88749. this._workingVector.y += this._defaultHeight;
  88750. }
  88751. this.onBeforeCameraTeleport.notifyObservers(this._workingVector);
  88752. // Create animation from the camera's position to the new location
  88753. this.currentVRCamera.animations = [];
  88754. var animationCameraTeleportation = new BABYLON.Animation("animationCameraTeleportation", "position", 90, BABYLON.Animation.ANIMATIONTYPE_VECTOR3, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  88755. var animationCameraTeleportationKeys = [{
  88756. frame: 0,
  88757. value: this.currentVRCamera.position
  88758. },
  88759. {
  88760. frame: 11,
  88761. value: this._workingVector
  88762. }
  88763. ];
  88764. animationCameraTeleportation.setKeys(animationCameraTeleportationKeys);
  88765. animationCameraTeleportation.setEasingFunction(this._circleEase);
  88766. this.currentVRCamera.animations.push(animationCameraTeleportation);
  88767. this._postProcessMove.animations = [];
  88768. var animationPP = new BABYLON.Animation("animationPP", "vignetteWeight", 90, BABYLON.Animation.ANIMATIONTYPE_FLOAT, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  88769. var vignetteWeightKeys = [];
  88770. vignetteWeightKeys.push({
  88771. frame: 0,
  88772. value: 0
  88773. });
  88774. vignetteWeightKeys.push({
  88775. frame: 5,
  88776. value: 8
  88777. });
  88778. vignetteWeightKeys.push({
  88779. frame: 11,
  88780. value: 0
  88781. });
  88782. animationPP.setKeys(vignetteWeightKeys);
  88783. this._postProcessMove.animations.push(animationPP);
  88784. var animationPP2 = new BABYLON.Animation("animationPP2", "vignetteStretch", 90, BABYLON.Animation.ANIMATIONTYPE_FLOAT, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  88785. var vignetteStretchKeys = [];
  88786. vignetteStretchKeys.push({
  88787. frame: 0,
  88788. value: 0
  88789. });
  88790. vignetteStretchKeys.push({
  88791. frame: 5,
  88792. value: 10
  88793. });
  88794. vignetteStretchKeys.push({
  88795. frame: 11,
  88796. value: 0
  88797. });
  88798. animationPP2.setKeys(vignetteStretchKeys);
  88799. this._postProcessMove.animations.push(animationPP2);
  88800. this._postProcessMove.imageProcessingConfiguration.vignetteWeight = 0;
  88801. this._postProcessMove.imageProcessingConfiguration.vignetteStretch = 0;
  88802. this._webVRCamera.attachPostProcess(this._postProcessMove);
  88803. this._scene.beginAnimation(this._postProcessMove, 0, 11, false, 1, function () {
  88804. _this._webVRCamera.detachPostProcess(_this._postProcessMove);
  88805. });
  88806. this._scene.beginAnimation(this.currentVRCamera, 0, 11, false, 1, function () {
  88807. _this.onAfterCameraTeleport.notifyObservers(_this._workingVector);
  88808. });
  88809. this._hideTeleportationTarget();
  88810. };
  88811. VRExperienceHelper.prototype._castRayAndSelectObject = function (gazer) {
  88812. if (!(this.currentVRCamera instanceof BABYLON.FreeCamera)) {
  88813. return;
  88814. }
  88815. var hit = this._scene.pickWithRay(gazer._getForwardRay(this._rayLength), this._raySelectionPredicate);
  88816. // Moving the gazeTracker on the mesh face targetted
  88817. if (hit && hit.pickedPoint) {
  88818. if (this._displayGaze) {
  88819. var multiplier = 1;
  88820. gazer._gazeTracker.isVisible = true;
  88821. if (gazer._isActionableMesh) {
  88822. multiplier = 3;
  88823. }
  88824. gazer._gazeTracker.scaling.x = hit.distance * multiplier;
  88825. gazer._gazeTracker.scaling.y = hit.distance * multiplier;
  88826. gazer._gazeTracker.scaling.z = hit.distance * multiplier;
  88827. var pickNormal = hit.getNormal();
  88828. // To avoid z-fighting
  88829. var deltaFighting = 0.002;
  88830. if (pickNormal) {
  88831. var axis1 = BABYLON.Vector3.Cross(BABYLON.Axis.Y, pickNormal);
  88832. var axis2 = BABYLON.Vector3.Cross(pickNormal, axis1);
  88833. BABYLON.Vector3.RotationFromAxisToRef(axis2, pickNormal, axis1, gazer._gazeTracker.rotation);
  88834. }
  88835. gazer._gazeTracker.position.copyFrom(hit.pickedPoint);
  88836. if (gazer._gazeTracker.position.x < 0) {
  88837. gazer._gazeTracker.position.x += deltaFighting;
  88838. }
  88839. else {
  88840. gazer._gazeTracker.position.x -= deltaFighting;
  88841. }
  88842. if (gazer._gazeTracker.position.y < 0) {
  88843. gazer._gazeTracker.position.y += deltaFighting;
  88844. }
  88845. else {
  88846. gazer._gazeTracker.position.y -= deltaFighting;
  88847. }
  88848. if (gazer._gazeTracker.position.z < 0) {
  88849. gazer._gazeTracker.position.z += deltaFighting;
  88850. }
  88851. else {
  88852. gazer._gazeTracker.position.z -= deltaFighting;
  88853. }
  88854. }
  88855. // Changing the size of the laser pointer based on the distance from the targetted point
  88856. gazer._updatePointerDistance(hit.distance);
  88857. }
  88858. else {
  88859. gazer._gazeTracker.isVisible = false;
  88860. }
  88861. if (hit && hit.pickedMesh) {
  88862. gazer._currentHit = hit;
  88863. if (gazer._pointerDownOnMeshAsked) {
  88864. this._scene.simulatePointerMove(gazer._currentHit, { pointerId: gazer._id });
  88865. }
  88866. // The object selected is the floor, we're in a teleportation scenario
  88867. if (this._teleportationInitialized && this._isTeleportationFloor(hit.pickedMesh) && hit.pickedPoint) {
  88868. // Moving the teleportation area to this targetted point
  88869. //Raise onSelectedMeshUnselected observable if ray collided floor mesh/meshes and a non floor mesh was previously selected
  88870. if (gazer._currentMeshSelected && !this._isTeleportationFloor(gazer._currentMeshSelected)) {
  88871. this._notifySelectedMeshUnselected(gazer._currentMeshSelected);
  88872. }
  88873. gazer._currentMeshSelected = null;
  88874. if (gazer._teleportationRequestInitiated) {
  88875. this._moveTeleportationSelectorTo(hit, gazer);
  88876. }
  88877. return;
  88878. }
  88879. // If not, we're in a selection scenario
  88880. //this._teleportationAllowed = false;
  88881. if (hit.pickedMesh !== gazer._currentMeshSelected) {
  88882. if (this.meshSelectionPredicate(hit.pickedMesh)) {
  88883. this.onNewMeshPicked.notifyObservers(hit);
  88884. gazer._currentMeshSelected = hit.pickedMesh;
  88885. if (hit.pickedMesh.isPickable && hit.pickedMesh.actionManager) {
  88886. this.changeGazeColor(new BABYLON.Color3(0, 0, 1));
  88887. this.changeLaserColor(new BABYLON.Color3(0.2, 0.2, 1));
  88888. gazer._isActionableMesh = true;
  88889. }
  88890. else {
  88891. this.changeGazeColor(new BABYLON.Color3(0.7, 0.7, 0.7));
  88892. this.changeLaserColor(new BABYLON.Color3(0.7, 0.7, 0.7));
  88893. gazer._isActionableMesh = false;
  88894. }
  88895. try {
  88896. this.onNewMeshSelected.notifyObservers(hit.pickedMesh);
  88897. }
  88898. catch (err) {
  88899. BABYLON.Tools.Warn("Error in your custom logic onNewMeshSelected: " + err);
  88900. }
  88901. }
  88902. else {
  88903. this._notifySelectedMeshUnselected(gazer._currentMeshSelected);
  88904. gazer._currentMeshSelected = null;
  88905. this.changeGazeColor(new BABYLON.Color3(0.7, 0.7, 0.7));
  88906. this.changeLaserColor(new BABYLON.Color3(0.7, 0.7, 0.7));
  88907. }
  88908. }
  88909. }
  88910. else {
  88911. gazer._currentHit = null;
  88912. this._notifySelectedMeshUnselected(gazer._currentMeshSelected);
  88913. gazer._currentMeshSelected = null;
  88914. //this._teleportationAllowed = false;
  88915. this.changeGazeColor(new BABYLON.Color3(0.7, 0.7, 0.7));
  88916. this.changeLaserColor(new BABYLON.Color3(0.7, 0.7, 0.7));
  88917. }
  88918. };
  88919. VRExperienceHelper.prototype._notifySelectedMeshUnselected = function (mesh) {
  88920. if (mesh) {
  88921. this.onSelectedMeshUnselected.notifyObservers(mesh);
  88922. }
  88923. };
  88924. /**
  88925. * Sets the color of the laser ray from the vr controllers.
  88926. * @param color new color for the ray.
  88927. */
  88928. VRExperienceHelper.prototype.changeLaserColor = function (color) {
  88929. if (this.leftController) {
  88930. this.leftController._setLaserPointerColor(color);
  88931. }
  88932. if (this.rightController) {
  88933. this.rightController._setLaserPointerColor(color);
  88934. }
  88935. };
  88936. /**
  88937. * Sets the color of the ray from the vr headsets gaze.
  88938. * @param color new color for the ray.
  88939. */
  88940. VRExperienceHelper.prototype.changeGazeColor = function (color) {
  88941. if (!this._cameraGazer._gazeTracker.material) {
  88942. return;
  88943. }
  88944. this._cameraGazer._gazeTracker.material.emissiveColor = color;
  88945. if (this.leftController) {
  88946. this.leftController._gazeTracker.material.emissiveColor = color;
  88947. }
  88948. if (this.rightController) {
  88949. this.rightController._gazeTracker.material.emissiveColor = color;
  88950. }
  88951. };
  88952. /**
  88953. * Exits VR and disposes of the vr experience helper
  88954. */
  88955. VRExperienceHelper.prototype.dispose = function () {
  88956. if (this.isInVRMode) {
  88957. this.exitVR();
  88958. }
  88959. if (this._postProcessMove) {
  88960. this._postProcessMove.dispose();
  88961. }
  88962. if (this._webVRCamera) {
  88963. this._webVRCamera.dispose();
  88964. }
  88965. if (this._vrDeviceOrientationCamera) {
  88966. this._vrDeviceOrientationCamera.dispose();
  88967. }
  88968. if (!this._useCustomVRButton && this._btnVR.parentNode) {
  88969. document.body.removeChild(this._btnVR);
  88970. }
  88971. if (this._deviceOrientationCamera && (this._scene.activeCamera != this._deviceOrientationCamera)) {
  88972. this._deviceOrientationCamera.dispose();
  88973. }
  88974. if (this._cameraGazer) {
  88975. this._cameraGazer.dispose();
  88976. }
  88977. if (this.leftController) {
  88978. this.leftController.dispose();
  88979. }
  88980. if (this.rightController) {
  88981. this.rightController.dispose();
  88982. }
  88983. if (this._teleportationTarget) {
  88984. this._teleportationTarget.dispose();
  88985. }
  88986. this._floorMeshesCollection = [];
  88987. document.removeEventListener("keydown", this._onKeyDown);
  88988. window.removeEventListener('vrdisplaypresentchange', this._onVrDisplayPresentChange);
  88989. window.removeEventListener("resize", this._onResize);
  88990. document.removeEventListener("fullscreenchange", this._onFullscreenChange);
  88991. document.removeEventListener("mozfullscreenchange", this._onFullscreenChange);
  88992. document.removeEventListener("webkitfullscreenchange", this._onFullscreenChange);
  88993. document.removeEventListener("msfullscreenchange", this._onFullscreenChange);
  88994. this._scene.getEngine().onVRDisplayChangedObservable.removeCallback(this._onVRDisplayChanged);
  88995. this._scene.getEngine().onVRRequestPresentStart.removeCallback(this._onVRRequestPresentStart);
  88996. this._scene.getEngine().onVRRequestPresentComplete.removeCallback(this._onVRRequestPresentComplete);
  88997. window.removeEventListener('vrdisplaypresentchange', this._onVrDisplayPresentChange);
  88998. this._scene.gamepadManager.onGamepadConnectedObservable.removeCallback(this._onNewGamepadConnected);
  88999. this._scene.gamepadManager.onGamepadDisconnectedObservable.removeCallback(this._onNewGamepadDisconnected);
  89000. this._scene.unregisterBeforeRender(this.beforeRender);
  89001. };
  89002. /**
  89003. * Gets the name of the VRExperienceHelper class
  89004. * @returns "VRExperienceHelper"
  89005. */
  89006. VRExperienceHelper.prototype.getClassName = function () {
  89007. return "VRExperienceHelper";
  89008. };
  89009. return VRExperienceHelper;
  89010. }());
  89011. BABYLON.VRExperienceHelper = VRExperienceHelper;
  89012. })(BABYLON || (BABYLON = {}));
  89013. //# sourceMappingURL=babylon.vrExperienceHelper.js.map
  89014. // Mainly based on these 2 articles :
  89015. // 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
  89016. // & on Seb Lee-Delisle original work: http://seb.ly/2011/04/multi-touch-game-controller-in-javascripthtml5-for-ipad/
  89017. var BABYLON;
  89018. (function (BABYLON) {
  89019. /**
  89020. * Defines the potential axis of a Joystick
  89021. */
  89022. var JoystickAxis;
  89023. (function (JoystickAxis) {
  89024. /** X axis */
  89025. JoystickAxis[JoystickAxis["X"] = 0] = "X";
  89026. /** Y axis */
  89027. JoystickAxis[JoystickAxis["Y"] = 1] = "Y";
  89028. /** Z axis */
  89029. JoystickAxis[JoystickAxis["Z"] = 2] = "Z";
  89030. })(JoystickAxis = BABYLON.JoystickAxis || (BABYLON.JoystickAxis = {}));
  89031. /**
  89032. * Class used to define virtual joystick (used in touch mode)
  89033. */
  89034. var VirtualJoystick = /** @class */ (function () {
  89035. /**
  89036. * Creates a new virtual joystick
  89037. * @param leftJoystick defines that the joystick is for left hand (false by default)
  89038. */
  89039. function VirtualJoystick(leftJoystick) {
  89040. var _this = this;
  89041. if (leftJoystick) {
  89042. this._leftJoystick = true;
  89043. }
  89044. else {
  89045. this._leftJoystick = false;
  89046. }
  89047. VirtualJoystick._globalJoystickIndex++;
  89048. // By default left & right arrow keys are moving the X
  89049. // and up & down keys are moving the Y
  89050. this._axisTargetedByLeftAndRight = JoystickAxis.X;
  89051. this._axisTargetedByUpAndDown = JoystickAxis.Y;
  89052. this.reverseLeftRight = false;
  89053. this.reverseUpDown = false;
  89054. // collections of pointers
  89055. this._touches = new BABYLON.StringDictionary();
  89056. this.deltaPosition = BABYLON.Vector3.Zero();
  89057. this._joystickSensibility = 25;
  89058. this._inversedSensibility = 1 / (this._joystickSensibility / 1000);
  89059. this._onResize = function (evt) {
  89060. VirtualJoystick.vjCanvasWidth = window.innerWidth;
  89061. VirtualJoystick.vjCanvasHeight = window.innerHeight;
  89062. if (VirtualJoystick.vjCanvas) {
  89063. VirtualJoystick.vjCanvas.width = VirtualJoystick.vjCanvasWidth;
  89064. VirtualJoystick.vjCanvas.height = VirtualJoystick.vjCanvasHeight;
  89065. }
  89066. VirtualJoystick.halfWidth = VirtualJoystick.vjCanvasWidth / 2;
  89067. };
  89068. // injecting a canvas element on top of the canvas 3D game
  89069. if (!VirtualJoystick.vjCanvas) {
  89070. window.addEventListener("resize", this._onResize, false);
  89071. VirtualJoystick.vjCanvas = document.createElement("canvas");
  89072. VirtualJoystick.vjCanvasWidth = window.innerWidth;
  89073. VirtualJoystick.vjCanvasHeight = window.innerHeight;
  89074. VirtualJoystick.vjCanvas.width = window.innerWidth;
  89075. VirtualJoystick.vjCanvas.height = window.innerHeight;
  89076. VirtualJoystick.vjCanvas.style.width = "100%";
  89077. VirtualJoystick.vjCanvas.style.height = "100%";
  89078. VirtualJoystick.vjCanvas.style.position = "absolute";
  89079. VirtualJoystick.vjCanvas.style.backgroundColor = "transparent";
  89080. VirtualJoystick.vjCanvas.style.top = "0px";
  89081. VirtualJoystick.vjCanvas.style.left = "0px";
  89082. VirtualJoystick.vjCanvas.style.zIndex = "5";
  89083. VirtualJoystick.vjCanvas.style.msTouchAction = "none";
  89084. // Support for jQuery PEP polyfill
  89085. VirtualJoystick.vjCanvas.setAttribute("touch-action", "none");
  89086. var context = VirtualJoystick.vjCanvas.getContext('2d');
  89087. if (!context) {
  89088. throw new Error("Unable to create canvas for virtual joystick");
  89089. }
  89090. VirtualJoystick.vjCanvasContext = context;
  89091. VirtualJoystick.vjCanvasContext.strokeStyle = "#ffffff";
  89092. VirtualJoystick.vjCanvasContext.lineWidth = 2;
  89093. document.body.appendChild(VirtualJoystick.vjCanvas);
  89094. }
  89095. VirtualJoystick.halfWidth = VirtualJoystick.vjCanvas.width / 2;
  89096. this.pressed = false;
  89097. // default joystick color
  89098. this._joystickColor = "cyan";
  89099. this._joystickPointerID = -1;
  89100. // current joystick position
  89101. this._joystickPointerPos = new BABYLON.Vector2(0, 0);
  89102. this._joystickPreviousPointerPos = new BABYLON.Vector2(0, 0);
  89103. // origin joystick position
  89104. this._joystickPointerStartPos = new BABYLON.Vector2(0, 0);
  89105. this._deltaJoystickVector = new BABYLON.Vector2(0, 0);
  89106. this._onPointerDownHandlerRef = function (evt) {
  89107. _this._onPointerDown(evt);
  89108. };
  89109. this._onPointerMoveHandlerRef = function (evt) {
  89110. _this._onPointerMove(evt);
  89111. };
  89112. this._onPointerUpHandlerRef = function (evt) {
  89113. _this._onPointerUp(evt);
  89114. };
  89115. VirtualJoystick.vjCanvas.addEventListener('pointerdown', this._onPointerDownHandlerRef, false);
  89116. VirtualJoystick.vjCanvas.addEventListener('pointermove', this._onPointerMoveHandlerRef, false);
  89117. VirtualJoystick.vjCanvas.addEventListener('pointerup', this._onPointerUpHandlerRef, false);
  89118. VirtualJoystick.vjCanvas.addEventListener('pointerout', this._onPointerUpHandlerRef, false);
  89119. VirtualJoystick.vjCanvas.addEventListener("contextmenu", function (evt) {
  89120. evt.preventDefault(); // Disables system menu
  89121. }, false);
  89122. requestAnimationFrame(function () { _this._drawVirtualJoystick(); });
  89123. }
  89124. /**
  89125. * Defines joystick sensibility (ie. the ratio beteen a physical move and virtual joystick position change)
  89126. * @param newJoystickSensibility defines the new sensibility
  89127. */
  89128. VirtualJoystick.prototype.setJoystickSensibility = function (newJoystickSensibility) {
  89129. this._joystickSensibility = newJoystickSensibility;
  89130. this._inversedSensibility = 1 / (this._joystickSensibility / 1000);
  89131. };
  89132. VirtualJoystick.prototype._onPointerDown = function (e) {
  89133. var positionOnScreenCondition;
  89134. e.preventDefault();
  89135. if (this._leftJoystick === true) {
  89136. positionOnScreenCondition = (e.clientX < VirtualJoystick.halfWidth);
  89137. }
  89138. else {
  89139. positionOnScreenCondition = (e.clientX > VirtualJoystick.halfWidth);
  89140. }
  89141. if (positionOnScreenCondition && this._joystickPointerID < 0) {
  89142. // First contact will be dedicated to the virtual joystick
  89143. this._joystickPointerID = e.pointerId;
  89144. this._joystickPointerStartPos.x = e.clientX;
  89145. this._joystickPointerStartPos.y = e.clientY;
  89146. this._joystickPointerPos = this._joystickPointerStartPos.clone();
  89147. this._joystickPreviousPointerPos = this._joystickPointerStartPos.clone();
  89148. this._deltaJoystickVector.x = 0;
  89149. this._deltaJoystickVector.y = 0;
  89150. this.pressed = true;
  89151. this._touches.add(e.pointerId.toString(), e);
  89152. }
  89153. else {
  89154. // You can only trigger the action buttons with a joystick declared
  89155. if (VirtualJoystick._globalJoystickIndex < 2 && this._action) {
  89156. this._action();
  89157. this._touches.add(e.pointerId.toString(), { x: e.clientX, y: e.clientY, prevX: e.clientX, prevY: e.clientY });
  89158. }
  89159. }
  89160. };
  89161. VirtualJoystick.prototype._onPointerMove = function (e) {
  89162. // If the current pointer is the one associated to the joystick (first touch contact)
  89163. if (this._joystickPointerID == e.pointerId) {
  89164. this._joystickPointerPos.x = e.clientX;
  89165. this._joystickPointerPos.y = e.clientY;
  89166. this._deltaJoystickVector = this._joystickPointerPos.clone();
  89167. this._deltaJoystickVector = this._deltaJoystickVector.subtract(this._joystickPointerStartPos);
  89168. var directionLeftRight = this.reverseLeftRight ? -1 : 1;
  89169. var deltaJoystickX = directionLeftRight * this._deltaJoystickVector.x / this._inversedSensibility;
  89170. switch (this._axisTargetedByLeftAndRight) {
  89171. case JoystickAxis.X:
  89172. this.deltaPosition.x = Math.min(1, Math.max(-1, deltaJoystickX));
  89173. break;
  89174. case JoystickAxis.Y:
  89175. this.deltaPosition.y = Math.min(1, Math.max(-1, deltaJoystickX));
  89176. break;
  89177. case JoystickAxis.Z:
  89178. this.deltaPosition.z = Math.min(1, Math.max(-1, deltaJoystickX));
  89179. break;
  89180. }
  89181. var directionUpDown = this.reverseUpDown ? 1 : -1;
  89182. var deltaJoystickY = directionUpDown * this._deltaJoystickVector.y / this._inversedSensibility;
  89183. switch (this._axisTargetedByUpAndDown) {
  89184. case JoystickAxis.X:
  89185. this.deltaPosition.x = Math.min(1, Math.max(-1, deltaJoystickY));
  89186. break;
  89187. case JoystickAxis.Y:
  89188. this.deltaPosition.y = Math.min(1, Math.max(-1, deltaJoystickY));
  89189. break;
  89190. case JoystickAxis.Z:
  89191. this.deltaPosition.z = Math.min(1, Math.max(-1, deltaJoystickY));
  89192. break;
  89193. }
  89194. }
  89195. else {
  89196. var data = this._touches.get(e.pointerId.toString());
  89197. if (data) {
  89198. data.x = e.clientX;
  89199. data.y = e.clientY;
  89200. }
  89201. }
  89202. };
  89203. VirtualJoystick.prototype._onPointerUp = function (e) {
  89204. if (this._joystickPointerID == e.pointerId) {
  89205. VirtualJoystick.vjCanvasContext.clearRect(this._joystickPointerStartPos.x - 64, this._joystickPointerStartPos.y - 64, 128, 128);
  89206. VirtualJoystick.vjCanvasContext.clearRect(this._joystickPreviousPointerPos.x - 42, this._joystickPreviousPointerPos.y - 42, 84, 84);
  89207. this._joystickPointerID = -1;
  89208. this.pressed = false;
  89209. }
  89210. else {
  89211. var touch = this._touches.get(e.pointerId.toString());
  89212. if (touch) {
  89213. VirtualJoystick.vjCanvasContext.clearRect(touch.prevX - 44, touch.prevY - 44, 88, 88);
  89214. }
  89215. }
  89216. this._deltaJoystickVector.x = 0;
  89217. this._deltaJoystickVector.y = 0;
  89218. this._touches.remove(e.pointerId.toString());
  89219. };
  89220. /**
  89221. * Change the color of the virtual joystick
  89222. * @param newColor a string that must be a CSS color value (like "red") or the hexa value (like "#FF0000")
  89223. */
  89224. VirtualJoystick.prototype.setJoystickColor = function (newColor) {
  89225. this._joystickColor = newColor;
  89226. };
  89227. /**
  89228. * Defines a callback to call when the joystick is touched
  89229. * @param action defines the callback
  89230. */
  89231. VirtualJoystick.prototype.setActionOnTouch = function (action) {
  89232. this._action = action;
  89233. };
  89234. /**
  89235. * Defines which axis you'd like to control for left & right
  89236. * @param axis defines the axis to use
  89237. */
  89238. VirtualJoystick.prototype.setAxisForLeftRight = function (axis) {
  89239. switch (axis) {
  89240. case JoystickAxis.X:
  89241. case JoystickAxis.Y:
  89242. case JoystickAxis.Z:
  89243. this._axisTargetedByLeftAndRight = axis;
  89244. break;
  89245. default:
  89246. this._axisTargetedByLeftAndRight = JoystickAxis.X;
  89247. break;
  89248. }
  89249. };
  89250. /**
  89251. * Defines which axis you'd like to control for up & down
  89252. * @param axis defines the axis to use
  89253. */
  89254. VirtualJoystick.prototype.setAxisForUpDown = function (axis) {
  89255. switch (axis) {
  89256. case JoystickAxis.X:
  89257. case JoystickAxis.Y:
  89258. case JoystickAxis.Z:
  89259. this._axisTargetedByUpAndDown = axis;
  89260. break;
  89261. default:
  89262. this._axisTargetedByUpAndDown = JoystickAxis.Y;
  89263. break;
  89264. }
  89265. };
  89266. VirtualJoystick.prototype._drawVirtualJoystick = function () {
  89267. var _this = this;
  89268. if (this.pressed) {
  89269. this._touches.forEach(function (key, touch) {
  89270. if (touch.pointerId === _this._joystickPointerID) {
  89271. VirtualJoystick.vjCanvasContext.clearRect(_this._joystickPointerStartPos.x - 64, _this._joystickPointerStartPos.y - 64, 128, 128);
  89272. VirtualJoystick.vjCanvasContext.clearRect(_this._joystickPreviousPointerPos.x - 42, _this._joystickPreviousPointerPos.y - 42, 84, 84);
  89273. VirtualJoystick.vjCanvasContext.beginPath();
  89274. VirtualJoystick.vjCanvasContext.lineWidth = 6;
  89275. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  89276. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerStartPos.x, _this._joystickPointerStartPos.y, 40, 0, Math.PI * 2, true);
  89277. VirtualJoystick.vjCanvasContext.stroke();
  89278. VirtualJoystick.vjCanvasContext.closePath();
  89279. VirtualJoystick.vjCanvasContext.beginPath();
  89280. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  89281. VirtualJoystick.vjCanvasContext.lineWidth = 2;
  89282. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerStartPos.x, _this._joystickPointerStartPos.y, 60, 0, Math.PI * 2, true);
  89283. VirtualJoystick.vjCanvasContext.stroke();
  89284. VirtualJoystick.vjCanvasContext.closePath();
  89285. VirtualJoystick.vjCanvasContext.beginPath();
  89286. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  89287. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerPos.x, _this._joystickPointerPos.y, 40, 0, Math.PI * 2, true);
  89288. VirtualJoystick.vjCanvasContext.stroke();
  89289. VirtualJoystick.vjCanvasContext.closePath();
  89290. _this._joystickPreviousPointerPos = _this._joystickPointerPos.clone();
  89291. }
  89292. else {
  89293. VirtualJoystick.vjCanvasContext.clearRect(touch.prevX - 44, touch.prevY - 44, 88, 88);
  89294. VirtualJoystick.vjCanvasContext.beginPath();
  89295. VirtualJoystick.vjCanvasContext.fillStyle = "white";
  89296. VirtualJoystick.vjCanvasContext.beginPath();
  89297. VirtualJoystick.vjCanvasContext.strokeStyle = "red";
  89298. VirtualJoystick.vjCanvasContext.lineWidth = 6;
  89299. VirtualJoystick.vjCanvasContext.arc(touch.x, touch.y, 40, 0, Math.PI * 2, true);
  89300. VirtualJoystick.vjCanvasContext.stroke();
  89301. VirtualJoystick.vjCanvasContext.closePath();
  89302. touch.prevX = touch.x;
  89303. touch.prevY = touch.y;
  89304. }
  89305. ;
  89306. });
  89307. }
  89308. requestAnimationFrame(function () { _this._drawVirtualJoystick(); });
  89309. };
  89310. /**
  89311. * Release internal HTML canvas
  89312. */
  89313. VirtualJoystick.prototype.releaseCanvas = function () {
  89314. if (VirtualJoystick.vjCanvas) {
  89315. VirtualJoystick.vjCanvas.removeEventListener('pointerdown', this._onPointerDownHandlerRef);
  89316. VirtualJoystick.vjCanvas.removeEventListener('pointermove', this._onPointerMoveHandlerRef);
  89317. VirtualJoystick.vjCanvas.removeEventListener('pointerup', this._onPointerUpHandlerRef);
  89318. VirtualJoystick.vjCanvas.removeEventListener('pointerout', this._onPointerUpHandlerRef);
  89319. window.removeEventListener("resize", this._onResize);
  89320. document.body.removeChild(VirtualJoystick.vjCanvas);
  89321. VirtualJoystick.vjCanvas = null;
  89322. }
  89323. };
  89324. // Used to draw the virtual joystick inside a 2D canvas on top of the WebGL rendering canvas
  89325. VirtualJoystick._globalJoystickIndex = 0;
  89326. return VirtualJoystick;
  89327. }());
  89328. BABYLON.VirtualJoystick = VirtualJoystick;
  89329. })(BABYLON || (BABYLON = {}));
  89330. //# sourceMappingURL=babylon.virtualJoystick.js.map
  89331. var BABYLON;
  89332. (function (BABYLON) {
  89333. // We're mainly based on the logic defined into the FreeCamera code
  89334. var VirtualJoysticksCamera = /** @class */ (function (_super) {
  89335. __extends(VirtualJoysticksCamera, _super);
  89336. function VirtualJoysticksCamera(name, position, scene) {
  89337. var _this = _super.call(this, name, position, scene) || this;
  89338. _this.inputs.addVirtualJoystick();
  89339. return _this;
  89340. }
  89341. VirtualJoysticksCamera.prototype.getClassName = function () {
  89342. return "VirtualJoysticksCamera";
  89343. };
  89344. return VirtualJoysticksCamera;
  89345. }(BABYLON.FreeCamera));
  89346. BABYLON.VirtualJoysticksCamera = VirtualJoysticksCamera;
  89347. })(BABYLON || (BABYLON = {}));
  89348. //# sourceMappingURL=babylon.virtualJoysticksCamera.js.map
  89349. var BABYLON;
  89350. (function (BABYLON) {
  89351. var FreeCameraVirtualJoystickInput = /** @class */ (function () {
  89352. function FreeCameraVirtualJoystickInput() {
  89353. }
  89354. FreeCameraVirtualJoystickInput.prototype.getLeftJoystick = function () {
  89355. return this._leftjoystick;
  89356. };
  89357. FreeCameraVirtualJoystickInput.prototype.getRightJoystick = function () {
  89358. return this._rightjoystick;
  89359. };
  89360. FreeCameraVirtualJoystickInput.prototype.checkInputs = function () {
  89361. if (this._leftjoystick) {
  89362. var camera = this.camera;
  89363. var speed = camera._computeLocalCameraSpeed() * 50;
  89364. var cameraTransform = BABYLON.Matrix.RotationYawPitchRoll(camera.rotation.y, camera.rotation.x, 0);
  89365. var deltaTransform = BABYLON.Vector3.TransformCoordinates(new BABYLON.Vector3(this._leftjoystick.deltaPosition.x * speed, this._leftjoystick.deltaPosition.y * speed, this._leftjoystick.deltaPosition.z * speed), cameraTransform);
  89366. camera.cameraDirection = camera.cameraDirection.add(deltaTransform);
  89367. camera.cameraRotation = camera.cameraRotation.addVector3(this._rightjoystick.deltaPosition);
  89368. if (!this._leftjoystick.pressed) {
  89369. this._leftjoystick.deltaPosition = this._leftjoystick.deltaPosition.scale(0.9);
  89370. }
  89371. if (!this._rightjoystick.pressed) {
  89372. this._rightjoystick.deltaPosition = this._rightjoystick.deltaPosition.scale(0.9);
  89373. }
  89374. }
  89375. };
  89376. FreeCameraVirtualJoystickInput.prototype.attachControl = function (element, noPreventDefault) {
  89377. this._leftjoystick = new BABYLON.VirtualJoystick(true);
  89378. this._leftjoystick.setAxisForUpDown(BABYLON.JoystickAxis.Z);
  89379. this._leftjoystick.setAxisForLeftRight(BABYLON.JoystickAxis.X);
  89380. this._leftjoystick.setJoystickSensibility(0.15);
  89381. this._rightjoystick = new BABYLON.VirtualJoystick(false);
  89382. this._rightjoystick.setAxisForUpDown(BABYLON.JoystickAxis.X);
  89383. this._rightjoystick.setAxisForLeftRight(BABYLON.JoystickAxis.Y);
  89384. this._rightjoystick.reverseUpDown = true;
  89385. this._rightjoystick.setJoystickSensibility(0.05);
  89386. this._rightjoystick.setJoystickColor("yellow");
  89387. };
  89388. FreeCameraVirtualJoystickInput.prototype.detachControl = function (element) {
  89389. this._leftjoystick.releaseCanvas();
  89390. this._rightjoystick.releaseCanvas();
  89391. };
  89392. FreeCameraVirtualJoystickInput.prototype.getClassName = function () {
  89393. return "FreeCameraVirtualJoystickInput";
  89394. };
  89395. FreeCameraVirtualJoystickInput.prototype.getSimpleName = function () {
  89396. return "virtualJoystick";
  89397. };
  89398. return FreeCameraVirtualJoystickInput;
  89399. }());
  89400. BABYLON.FreeCameraVirtualJoystickInput = FreeCameraVirtualJoystickInput;
  89401. BABYLON.CameraInputTypes["FreeCameraVirtualJoystickInput"] = FreeCameraVirtualJoystickInput;
  89402. })(BABYLON || (BABYLON = {}));
  89403. //# sourceMappingURL=babylon.freeCameraVirtualJoystickInput.js.map
  89404. var BABYLON;
  89405. (function (BABYLON) {
  89406. var SimplificationSettings = /** @class */ (function () {
  89407. function SimplificationSettings(quality, distance, optimizeMesh) {
  89408. this.quality = quality;
  89409. this.distance = distance;
  89410. this.optimizeMesh = optimizeMesh;
  89411. }
  89412. return SimplificationSettings;
  89413. }());
  89414. BABYLON.SimplificationSettings = SimplificationSettings;
  89415. var SimplificationQueue = /** @class */ (function () {
  89416. function SimplificationQueue() {
  89417. this.running = false;
  89418. this._simplificationArray = [];
  89419. }
  89420. SimplificationQueue.prototype.addTask = function (task) {
  89421. this._simplificationArray.push(task);
  89422. };
  89423. SimplificationQueue.prototype.executeNext = function () {
  89424. var task = this._simplificationArray.pop();
  89425. if (task) {
  89426. this.running = true;
  89427. this.runSimplification(task);
  89428. }
  89429. else {
  89430. this.running = false;
  89431. }
  89432. };
  89433. SimplificationQueue.prototype.runSimplification = function (task) {
  89434. var _this = this;
  89435. if (task.parallelProcessing) {
  89436. //parallel simplifier
  89437. task.settings.forEach(function (setting) {
  89438. var simplifier = _this.getSimplifier(task);
  89439. simplifier.simplify(setting, function (newMesh) {
  89440. task.mesh.addLODLevel(setting.distance, newMesh);
  89441. newMesh.isVisible = true;
  89442. //check if it is the last
  89443. if (setting.quality === task.settings[task.settings.length - 1].quality && task.successCallback) {
  89444. //all done, run the success callback.
  89445. task.successCallback();
  89446. }
  89447. _this.executeNext();
  89448. });
  89449. });
  89450. }
  89451. else {
  89452. //single simplifier.
  89453. var simplifier = this.getSimplifier(task);
  89454. var runDecimation = function (setting, callback) {
  89455. simplifier.simplify(setting, function (newMesh) {
  89456. task.mesh.addLODLevel(setting.distance, newMesh);
  89457. newMesh.isVisible = true;
  89458. //run the next quality level
  89459. callback();
  89460. });
  89461. };
  89462. BABYLON.AsyncLoop.Run(task.settings.length, function (loop) {
  89463. runDecimation(task.settings[loop.index], function () {
  89464. loop.executeNext();
  89465. });
  89466. }, function () {
  89467. //execution ended, run the success callback.
  89468. if (task.successCallback) {
  89469. task.successCallback();
  89470. }
  89471. _this.executeNext();
  89472. });
  89473. }
  89474. };
  89475. SimplificationQueue.prototype.getSimplifier = function (task) {
  89476. switch (task.simplificationType) {
  89477. case SimplificationType.QUADRATIC:
  89478. default:
  89479. return new QuadraticErrorSimplification(task.mesh);
  89480. }
  89481. };
  89482. return SimplificationQueue;
  89483. }());
  89484. BABYLON.SimplificationQueue = SimplificationQueue;
  89485. /**
  89486. * The implemented types of simplification
  89487. * At the moment only Quadratic Error Decimation is implemented
  89488. */
  89489. var SimplificationType;
  89490. (function (SimplificationType) {
  89491. /** Quadratic error decimation */
  89492. SimplificationType[SimplificationType["QUADRATIC"] = 0] = "QUADRATIC";
  89493. })(SimplificationType = BABYLON.SimplificationType || (BABYLON.SimplificationType = {}));
  89494. var DecimationTriangle = /** @class */ (function () {
  89495. function DecimationTriangle(vertices) {
  89496. this.vertices = vertices;
  89497. this.error = new Array(4);
  89498. this.deleted = false;
  89499. this.isDirty = false;
  89500. this.deletePending = false;
  89501. this.borderFactor = 0;
  89502. }
  89503. return DecimationTriangle;
  89504. }());
  89505. BABYLON.DecimationTriangle = DecimationTriangle;
  89506. var DecimationVertex = /** @class */ (function () {
  89507. function DecimationVertex(position, id) {
  89508. this.position = position;
  89509. this.id = id;
  89510. this.isBorder = true;
  89511. this.q = new QuadraticMatrix();
  89512. this.triangleCount = 0;
  89513. this.triangleStart = 0;
  89514. this.originalOffsets = [];
  89515. }
  89516. DecimationVertex.prototype.updatePosition = function (newPosition) {
  89517. this.position.copyFrom(newPosition);
  89518. };
  89519. return DecimationVertex;
  89520. }());
  89521. BABYLON.DecimationVertex = DecimationVertex;
  89522. var QuadraticMatrix = /** @class */ (function () {
  89523. function QuadraticMatrix(data) {
  89524. this.data = new Array(10);
  89525. for (var i = 0; i < 10; ++i) {
  89526. if (data && data[i]) {
  89527. this.data[i] = data[i];
  89528. }
  89529. else {
  89530. this.data[i] = 0;
  89531. }
  89532. }
  89533. }
  89534. QuadraticMatrix.prototype.det = function (a11, a12, a13, a21, a22, a23, a31, a32, a33) {
  89535. var det = this.data[a11] * this.data[a22] * this.data[a33] + this.data[a13] * this.data[a21] * this.data[a32] +
  89536. this.data[a12] * this.data[a23] * this.data[a31] - this.data[a13] * this.data[a22] * this.data[a31] -
  89537. this.data[a11] * this.data[a23] * this.data[a32] - this.data[a12] * this.data[a21] * this.data[a33];
  89538. return det;
  89539. };
  89540. QuadraticMatrix.prototype.addInPlace = function (matrix) {
  89541. for (var i = 0; i < 10; ++i) {
  89542. this.data[i] += matrix.data[i];
  89543. }
  89544. };
  89545. QuadraticMatrix.prototype.addArrayInPlace = function (data) {
  89546. for (var i = 0; i < 10; ++i) {
  89547. this.data[i] += data[i];
  89548. }
  89549. };
  89550. QuadraticMatrix.prototype.add = function (matrix) {
  89551. var m = new QuadraticMatrix();
  89552. for (var i = 0; i < 10; ++i) {
  89553. m.data[i] = this.data[i] + matrix.data[i];
  89554. }
  89555. return m;
  89556. };
  89557. QuadraticMatrix.FromData = function (a, b, c, d) {
  89558. return new QuadraticMatrix(QuadraticMatrix.DataFromNumbers(a, b, c, d));
  89559. };
  89560. //returning an array to avoid garbage collection
  89561. QuadraticMatrix.DataFromNumbers = function (a, b, c, d) {
  89562. return [a * a, a * b, a * c, a * d, b * b, b * c, b * d, c * c, c * d, d * d];
  89563. };
  89564. return QuadraticMatrix;
  89565. }());
  89566. BABYLON.QuadraticMatrix = QuadraticMatrix;
  89567. var Reference = /** @class */ (function () {
  89568. function Reference(vertexId, triangleId) {
  89569. this.vertexId = vertexId;
  89570. this.triangleId = triangleId;
  89571. }
  89572. return Reference;
  89573. }());
  89574. BABYLON.Reference = Reference;
  89575. /**
  89576. * An implementation of the Quadratic Error simplification algorithm.
  89577. * Original paper : http://www1.cs.columbia.edu/~cs4162/html05s/garland97.pdf
  89578. * Ported mostly from QSlim and http://voxels.blogspot.de/2014/05/quadric-mesh-simplification-with-source.html to babylon JS
  89579. * @author RaananW
  89580. */
  89581. var QuadraticErrorSimplification = /** @class */ (function () {
  89582. function QuadraticErrorSimplification(_mesh) {
  89583. this._mesh = _mesh;
  89584. this.syncIterations = 5000;
  89585. this.aggressiveness = 7;
  89586. this.decimationIterations = 100;
  89587. this.boundingBoxEpsilon = BABYLON.Epsilon;
  89588. }
  89589. QuadraticErrorSimplification.prototype.simplify = function (settings, successCallback) {
  89590. var _this = this;
  89591. this.initDecimatedMesh();
  89592. //iterating through the submeshes array, one after the other.
  89593. BABYLON.AsyncLoop.Run(this._mesh.subMeshes.length, function (loop) {
  89594. _this.initWithMesh(loop.index, function () {
  89595. _this.runDecimation(settings, loop.index, function () {
  89596. loop.executeNext();
  89597. });
  89598. }, settings.optimizeMesh);
  89599. }, function () {
  89600. setTimeout(function () {
  89601. successCallback(_this._reconstructedMesh);
  89602. }, 0);
  89603. });
  89604. };
  89605. QuadraticErrorSimplification.prototype.runDecimation = function (settings, submeshIndex, successCallback) {
  89606. var _this = this;
  89607. var targetCount = ~~(this.triangles.length * settings.quality);
  89608. var deletedTriangles = 0;
  89609. var triangleCount = this.triangles.length;
  89610. var iterationFunction = function (iteration, callback) {
  89611. setTimeout(function () {
  89612. if (iteration % 5 === 0) {
  89613. _this.updateMesh(iteration === 0);
  89614. }
  89615. for (var i = 0; i < _this.triangles.length; ++i) {
  89616. _this.triangles[i].isDirty = false;
  89617. }
  89618. var threshold = 0.000000001 * Math.pow((iteration + 3), _this.aggressiveness);
  89619. var trianglesIterator = function (i) {
  89620. var tIdx = ~~(((_this.triangles.length / 2) + i) % _this.triangles.length);
  89621. var t = _this.triangles[tIdx];
  89622. if (!t)
  89623. return;
  89624. if (t.error[3] > threshold || t.deleted || t.isDirty) {
  89625. return;
  89626. }
  89627. for (var j = 0; j < 3; ++j) {
  89628. if (t.error[j] < threshold) {
  89629. var deleted0 = [];
  89630. var deleted1 = [];
  89631. var v0 = t.vertices[j];
  89632. var v1 = t.vertices[(j + 1) % 3];
  89633. if (v0.isBorder || v1.isBorder)
  89634. continue;
  89635. var p = BABYLON.Vector3.Zero();
  89636. var n = BABYLON.Vector3.Zero();
  89637. var uv = BABYLON.Vector2.Zero();
  89638. var color = new BABYLON.Color4(0, 0, 0, 1);
  89639. _this.calculateError(v0, v1, p, n, uv, color);
  89640. var delTr = new Array();
  89641. if (_this.isFlipped(v0, v1, p, deleted0, t.borderFactor, delTr))
  89642. continue;
  89643. if (_this.isFlipped(v1, v0, p, deleted1, t.borderFactor, delTr))
  89644. continue;
  89645. if (deleted0.indexOf(true) < 0 || deleted1.indexOf(true) < 0)
  89646. continue;
  89647. var uniqueArray = new Array();
  89648. delTr.forEach(function (deletedT) {
  89649. if (uniqueArray.indexOf(deletedT) === -1) {
  89650. deletedT.deletePending = true;
  89651. uniqueArray.push(deletedT);
  89652. }
  89653. });
  89654. if (uniqueArray.length % 2 !== 0) {
  89655. continue;
  89656. }
  89657. v0.q = v1.q.add(v0.q);
  89658. v0.updatePosition(p);
  89659. var tStart = _this.references.length;
  89660. deletedTriangles = _this.updateTriangles(v0, v0, deleted0, deletedTriangles);
  89661. deletedTriangles = _this.updateTriangles(v0, v1, deleted1, deletedTriangles);
  89662. var tCount = _this.references.length - tStart;
  89663. if (tCount <= v0.triangleCount) {
  89664. if (tCount) {
  89665. for (var c = 0; c < tCount; c++) {
  89666. _this.references[v0.triangleStart + c] = _this.references[tStart + c];
  89667. }
  89668. }
  89669. }
  89670. else {
  89671. v0.triangleStart = tStart;
  89672. }
  89673. v0.triangleCount = tCount;
  89674. break;
  89675. }
  89676. }
  89677. };
  89678. BABYLON.AsyncLoop.SyncAsyncForLoop(_this.triangles.length, _this.syncIterations, trianglesIterator, callback, function () { return (triangleCount - deletedTriangles <= targetCount); });
  89679. }, 0);
  89680. };
  89681. BABYLON.AsyncLoop.Run(this.decimationIterations, function (loop) {
  89682. if (triangleCount - deletedTriangles <= targetCount)
  89683. loop.breakLoop();
  89684. else {
  89685. iterationFunction(loop.index, function () {
  89686. loop.executeNext();
  89687. });
  89688. }
  89689. }, function () {
  89690. setTimeout(function () {
  89691. //reconstruct this part of the mesh
  89692. _this.reconstructMesh(submeshIndex);
  89693. successCallback();
  89694. }, 0);
  89695. });
  89696. };
  89697. QuadraticErrorSimplification.prototype.initWithMesh = function (submeshIndex, callback, optimizeMesh) {
  89698. var _this = this;
  89699. this.vertices = [];
  89700. this.triangles = [];
  89701. var positionData = this._mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  89702. var indices = this._mesh.getIndices();
  89703. var submesh = this._mesh.subMeshes[submeshIndex];
  89704. var findInVertices = function (positionToSearch) {
  89705. if (optimizeMesh) {
  89706. for (var ii = 0; ii < _this.vertices.length; ++ii) {
  89707. if (_this.vertices[ii].position.equals(positionToSearch)) {
  89708. return _this.vertices[ii];
  89709. }
  89710. }
  89711. }
  89712. return null;
  89713. };
  89714. var vertexReferences = [];
  89715. var vertexInit = function (i) {
  89716. if (!positionData) {
  89717. return;
  89718. }
  89719. var offset = i + submesh.verticesStart;
  89720. var position = BABYLON.Vector3.FromArray(positionData, offset * 3);
  89721. var vertex = findInVertices(position) || new DecimationVertex(position, _this.vertices.length);
  89722. vertex.originalOffsets.push(offset);
  89723. if (vertex.id === _this.vertices.length) {
  89724. _this.vertices.push(vertex);
  89725. }
  89726. vertexReferences.push(vertex.id);
  89727. };
  89728. //var totalVertices = mesh.getTotalVertices();
  89729. var totalVertices = submesh.verticesCount;
  89730. BABYLON.AsyncLoop.SyncAsyncForLoop(totalVertices, (this.syncIterations / 4) >> 0, vertexInit, function () {
  89731. var indicesInit = function (i) {
  89732. if (!indices) {
  89733. return;
  89734. }
  89735. var offset = (submesh.indexStart / 3) + i;
  89736. var pos = (offset * 3);
  89737. var i0 = indices[pos + 0];
  89738. var i1 = indices[pos + 1];
  89739. var i2 = indices[pos + 2];
  89740. var v0 = _this.vertices[vertexReferences[i0 - submesh.verticesStart]];
  89741. var v1 = _this.vertices[vertexReferences[i1 - submesh.verticesStart]];
  89742. var v2 = _this.vertices[vertexReferences[i2 - submesh.verticesStart]];
  89743. var triangle = new DecimationTriangle([v0, v1, v2]);
  89744. triangle.originalOffset = pos;
  89745. _this.triangles.push(triangle);
  89746. };
  89747. BABYLON.AsyncLoop.SyncAsyncForLoop(submesh.indexCount / 3, _this.syncIterations, indicesInit, function () {
  89748. _this.init(callback);
  89749. });
  89750. });
  89751. };
  89752. QuadraticErrorSimplification.prototype.init = function (callback) {
  89753. var _this = this;
  89754. var triangleInit1 = function (i) {
  89755. var t = _this.triangles[i];
  89756. t.normal = BABYLON.Vector3.Cross(t.vertices[1].position.subtract(t.vertices[0].position), t.vertices[2].position.subtract(t.vertices[0].position)).normalize();
  89757. for (var j = 0; j < 3; j++) {
  89758. 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))));
  89759. }
  89760. };
  89761. BABYLON.AsyncLoop.SyncAsyncForLoop(this.triangles.length, this.syncIterations, triangleInit1, function () {
  89762. var triangleInit2 = function (i) {
  89763. var t = _this.triangles[i];
  89764. for (var j = 0; j < 3; ++j) {
  89765. t.error[j] = _this.calculateError(t.vertices[j], t.vertices[(j + 1) % 3]);
  89766. }
  89767. t.error[3] = Math.min(t.error[0], t.error[1], t.error[2]);
  89768. };
  89769. BABYLON.AsyncLoop.SyncAsyncForLoop(_this.triangles.length, _this.syncIterations, triangleInit2, function () {
  89770. callback();
  89771. });
  89772. });
  89773. };
  89774. QuadraticErrorSimplification.prototype.reconstructMesh = function (submeshIndex) {
  89775. var newTriangles = [];
  89776. var i;
  89777. for (i = 0; i < this.vertices.length; ++i) {
  89778. this.vertices[i].triangleCount = 0;
  89779. }
  89780. var t;
  89781. var j;
  89782. for (i = 0; i < this.triangles.length; ++i) {
  89783. if (!this.triangles[i].deleted) {
  89784. t = this.triangles[i];
  89785. for (j = 0; j < 3; ++j) {
  89786. t.vertices[j].triangleCount = 1;
  89787. }
  89788. newTriangles.push(t);
  89789. }
  89790. }
  89791. var newPositionData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind) || []);
  89792. var newNormalData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.NormalKind) || []);
  89793. var newUVsData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.UVKind) || []);
  89794. var newColorsData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.ColorKind) || []);
  89795. var normalData = this._mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  89796. var uvs = this._mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  89797. var colorsData = this._mesh.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  89798. var vertexCount = 0;
  89799. for (i = 0; i < this.vertices.length; ++i) {
  89800. var vertex = this.vertices[i];
  89801. vertex.id = vertexCount;
  89802. if (vertex.triangleCount) {
  89803. vertex.originalOffsets.forEach(function (originalOffset) {
  89804. if (!normalData) {
  89805. return;
  89806. }
  89807. newPositionData.push(vertex.position.x);
  89808. newPositionData.push(vertex.position.y);
  89809. newPositionData.push(vertex.position.z);
  89810. newNormalData.push(normalData[originalOffset * 3]);
  89811. newNormalData.push(normalData[(originalOffset * 3) + 1]);
  89812. newNormalData.push(normalData[(originalOffset * 3) + 2]);
  89813. if (uvs && uvs.length) {
  89814. newUVsData.push(uvs[(originalOffset * 2)]);
  89815. newUVsData.push(uvs[(originalOffset * 2) + 1]);
  89816. }
  89817. else if (colorsData && colorsData.length) {
  89818. newColorsData.push(colorsData[(originalOffset * 4)]);
  89819. newColorsData.push(colorsData[(originalOffset * 4) + 1]);
  89820. newColorsData.push(colorsData[(originalOffset * 4) + 2]);
  89821. newColorsData.push(colorsData[(originalOffset * 4) + 3]);
  89822. }
  89823. ++vertexCount;
  89824. });
  89825. }
  89826. }
  89827. var startingIndex = this._reconstructedMesh.getTotalIndices();
  89828. var startingVertex = this._reconstructedMesh.getTotalVertices();
  89829. var submeshesArray = this._reconstructedMesh.subMeshes;
  89830. this._reconstructedMesh.subMeshes = [];
  89831. var newIndicesArray = this._reconstructedMesh.getIndices(); //[];
  89832. var originalIndices = this._mesh.getIndices();
  89833. for (i = 0; i < newTriangles.length; ++i) {
  89834. t = newTriangles[i]; //now get the new referencing point for each vertex
  89835. [0, 1, 2].forEach(function (idx) {
  89836. var id = originalIndices[t.originalOffset + idx];
  89837. var offset = t.vertices[idx].originalOffsets.indexOf(id);
  89838. if (offset < 0)
  89839. offset = 0;
  89840. newIndicesArray.push(t.vertices[idx].id + offset + startingVertex);
  89841. });
  89842. }
  89843. //overwriting the old vertex buffers and indices.
  89844. this._reconstructedMesh.setIndices(newIndicesArray);
  89845. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, newPositionData);
  89846. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, newNormalData);
  89847. if (newUVsData.length > 0)
  89848. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.UVKind, newUVsData);
  89849. if (newColorsData.length > 0)
  89850. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, newColorsData);
  89851. //create submesh
  89852. var originalSubmesh = this._mesh.subMeshes[submeshIndex];
  89853. if (submeshIndex > 0) {
  89854. this._reconstructedMesh.subMeshes = [];
  89855. submeshesArray.forEach(function (submesh) {
  89856. BABYLON.SubMesh.AddToMesh(submesh.materialIndex, submesh.verticesStart, submesh.verticesCount, /* 0, newPositionData.length/3, */ submesh.indexStart, submesh.indexCount, submesh.getMesh());
  89857. });
  89858. BABYLON.SubMesh.AddToMesh(originalSubmesh.materialIndex, startingVertex, vertexCount, /* 0, newPositionData.length / 3, */ startingIndex, newTriangles.length * 3, this._reconstructedMesh);
  89859. }
  89860. };
  89861. QuadraticErrorSimplification.prototype.initDecimatedMesh = function () {
  89862. this._reconstructedMesh = new BABYLON.Mesh(this._mesh.name + "Decimated", this._mesh.getScene());
  89863. this._reconstructedMesh.material = this._mesh.material;
  89864. this._reconstructedMesh.parent = this._mesh.parent;
  89865. this._reconstructedMesh.isVisible = false;
  89866. this._reconstructedMesh.renderingGroupId = this._mesh.renderingGroupId;
  89867. };
  89868. QuadraticErrorSimplification.prototype.isFlipped = function (vertex1, vertex2, point, deletedArray, borderFactor, delTr) {
  89869. for (var i = 0; i < vertex1.triangleCount; ++i) {
  89870. var t = this.triangles[this.references[vertex1.triangleStart + i].triangleId];
  89871. if (t.deleted)
  89872. continue;
  89873. var s = this.references[vertex1.triangleStart + i].vertexId;
  89874. var v1 = t.vertices[(s + 1) % 3];
  89875. var v2 = t.vertices[(s + 2) % 3];
  89876. if ((v1 === vertex2 || v2 === vertex2)) {
  89877. deletedArray[i] = true;
  89878. delTr.push(t);
  89879. continue;
  89880. }
  89881. var d1 = v1.position.subtract(point);
  89882. d1 = d1.normalize();
  89883. var d2 = v2.position.subtract(point);
  89884. d2 = d2.normalize();
  89885. if (Math.abs(BABYLON.Vector3.Dot(d1, d2)) > 0.999)
  89886. return true;
  89887. var normal = BABYLON.Vector3.Cross(d1, d2).normalize();
  89888. deletedArray[i] = false;
  89889. if (BABYLON.Vector3.Dot(normal, t.normal) < 0.2)
  89890. return true;
  89891. }
  89892. return false;
  89893. };
  89894. QuadraticErrorSimplification.prototype.updateTriangles = function (origVertex, vertex, deletedArray, deletedTriangles) {
  89895. var newDeleted = deletedTriangles;
  89896. for (var i = 0; i < vertex.triangleCount; ++i) {
  89897. var ref = this.references[vertex.triangleStart + i];
  89898. var t = this.triangles[ref.triangleId];
  89899. if (t.deleted)
  89900. continue;
  89901. if (deletedArray[i] && t.deletePending) {
  89902. t.deleted = true;
  89903. newDeleted++;
  89904. continue;
  89905. }
  89906. t.vertices[ref.vertexId] = origVertex;
  89907. t.isDirty = true;
  89908. t.error[0] = this.calculateError(t.vertices[0], t.vertices[1]) + (t.borderFactor / 2);
  89909. t.error[1] = this.calculateError(t.vertices[1], t.vertices[2]) + (t.borderFactor / 2);
  89910. t.error[2] = this.calculateError(t.vertices[2], t.vertices[0]) + (t.borderFactor / 2);
  89911. t.error[3] = Math.min(t.error[0], t.error[1], t.error[2]);
  89912. this.references.push(ref);
  89913. }
  89914. return newDeleted;
  89915. };
  89916. QuadraticErrorSimplification.prototype.identifyBorder = function () {
  89917. for (var i = 0; i < this.vertices.length; ++i) {
  89918. var vCount = [];
  89919. var vId = [];
  89920. var v = this.vertices[i];
  89921. var j;
  89922. for (j = 0; j < v.triangleCount; ++j) {
  89923. var triangle = this.triangles[this.references[v.triangleStart + j].triangleId];
  89924. for (var ii = 0; ii < 3; ii++) {
  89925. var ofs = 0;
  89926. var vv = triangle.vertices[ii];
  89927. while (ofs < vCount.length) {
  89928. if (vId[ofs] === vv.id)
  89929. break;
  89930. ++ofs;
  89931. }
  89932. if (ofs === vCount.length) {
  89933. vCount.push(1);
  89934. vId.push(vv.id);
  89935. }
  89936. else {
  89937. vCount[ofs]++;
  89938. }
  89939. }
  89940. }
  89941. for (j = 0; j < vCount.length; ++j) {
  89942. if (vCount[j] === 1) {
  89943. this.vertices[vId[j]].isBorder = true;
  89944. }
  89945. else {
  89946. this.vertices[vId[j]].isBorder = false;
  89947. }
  89948. }
  89949. }
  89950. };
  89951. QuadraticErrorSimplification.prototype.updateMesh = function (identifyBorders) {
  89952. if (identifyBorders === void 0) { identifyBorders = false; }
  89953. var i;
  89954. if (!identifyBorders) {
  89955. var newTrianglesVector = [];
  89956. for (i = 0; i < this.triangles.length; ++i) {
  89957. if (!this.triangles[i].deleted) {
  89958. newTrianglesVector.push(this.triangles[i]);
  89959. }
  89960. }
  89961. this.triangles = newTrianglesVector;
  89962. }
  89963. for (i = 0; i < this.vertices.length; ++i) {
  89964. this.vertices[i].triangleCount = 0;
  89965. this.vertices[i].triangleStart = 0;
  89966. }
  89967. var t;
  89968. var j;
  89969. var v;
  89970. for (i = 0; i < this.triangles.length; ++i) {
  89971. t = this.triangles[i];
  89972. for (j = 0; j < 3; ++j) {
  89973. v = t.vertices[j];
  89974. v.triangleCount++;
  89975. }
  89976. }
  89977. var tStart = 0;
  89978. for (i = 0; i < this.vertices.length; ++i) {
  89979. this.vertices[i].triangleStart = tStart;
  89980. tStart += this.vertices[i].triangleCount;
  89981. this.vertices[i].triangleCount = 0;
  89982. }
  89983. var newReferences = new Array(this.triangles.length * 3);
  89984. for (i = 0; i < this.triangles.length; ++i) {
  89985. t = this.triangles[i];
  89986. for (j = 0; j < 3; ++j) {
  89987. v = t.vertices[j];
  89988. newReferences[v.triangleStart + v.triangleCount] = new Reference(j, i);
  89989. v.triangleCount++;
  89990. }
  89991. }
  89992. this.references = newReferences;
  89993. if (identifyBorders) {
  89994. this.identifyBorder();
  89995. }
  89996. };
  89997. QuadraticErrorSimplification.prototype.vertexError = function (q, point) {
  89998. var x = point.x;
  89999. var y = point.y;
  90000. var z = point.z;
  90001. 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
  90002. + 2 * q.data[5] * y * z + 2 * q.data[6] * y + q.data[7] * z * z + 2 * q.data[8] * z + q.data[9];
  90003. };
  90004. QuadraticErrorSimplification.prototype.calculateError = function (vertex1, vertex2, pointResult, normalResult, uvResult, colorResult) {
  90005. var q = vertex1.q.add(vertex2.q);
  90006. var border = vertex1.isBorder && vertex2.isBorder;
  90007. var error = 0;
  90008. var qDet = q.det(0, 1, 2, 1, 4, 5, 2, 5, 7);
  90009. if (qDet !== 0 && !border) {
  90010. if (!pointResult) {
  90011. pointResult = BABYLON.Vector3.Zero();
  90012. }
  90013. pointResult.x = -1 / qDet * (q.det(1, 2, 3, 4, 5, 6, 5, 7, 8));
  90014. pointResult.y = 1 / qDet * (q.det(0, 2, 3, 1, 5, 6, 2, 7, 8));
  90015. pointResult.z = -1 / qDet * (q.det(0, 1, 3, 1, 4, 6, 2, 5, 8));
  90016. error = this.vertexError(q, pointResult);
  90017. }
  90018. else {
  90019. var p3 = (vertex1.position.add(vertex2.position)).divide(new BABYLON.Vector3(2, 2, 2));
  90020. //var norm3 = (vertex1.normal.add(vertex2.normal)).divide(new Vector3(2, 2, 2)).normalize();
  90021. var error1 = this.vertexError(q, vertex1.position);
  90022. var error2 = this.vertexError(q, vertex2.position);
  90023. var error3 = this.vertexError(q, p3);
  90024. error = Math.min(error1, error2, error3);
  90025. if (error === error1) {
  90026. if (pointResult) {
  90027. pointResult.copyFrom(vertex1.position);
  90028. }
  90029. }
  90030. else if (error === error2) {
  90031. if (pointResult) {
  90032. pointResult.copyFrom(vertex2.position);
  90033. }
  90034. }
  90035. else {
  90036. if (pointResult) {
  90037. pointResult.copyFrom(p3);
  90038. }
  90039. }
  90040. }
  90041. return error;
  90042. };
  90043. return QuadraticErrorSimplification;
  90044. }());
  90045. BABYLON.QuadraticErrorSimplification = QuadraticErrorSimplification;
  90046. })(BABYLON || (BABYLON = {}));
  90047. //# sourceMappingURL=babylon.meshSimplification.js.map
  90048. var BABYLON;
  90049. (function (BABYLON) {
  90050. var MeshLODLevel = /** @class */ (function () {
  90051. function MeshLODLevel(distance, mesh) {
  90052. this.distance = distance;
  90053. this.mesh = mesh;
  90054. }
  90055. return MeshLODLevel;
  90056. }());
  90057. BABYLON.MeshLODLevel = MeshLODLevel;
  90058. })(BABYLON || (BABYLON = {}));
  90059. //# sourceMappingURL=babylon.meshLODLevel.js.map
  90060. var BABYLON;
  90061. (function (BABYLON) {
  90062. /**
  90063. * Defines the root class used to create scene optimization to use with SceneOptimizer
  90064. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  90065. */
  90066. var SceneOptimization = /** @class */ (function () {
  90067. /**
  90068. * Creates the SceneOptimization object
  90069. * @param priority defines the priority of this optimization (0 by default which means first in the list)
  90070. * @param desc defines the description associated with the optimization
  90071. */
  90072. function SceneOptimization(
  90073. /**
  90074. * Defines the priority of this optimization (0 by default which means first in the list)
  90075. */
  90076. priority) {
  90077. if (priority === void 0) { priority = 0; }
  90078. this.priority = priority;
  90079. }
  90080. /**
  90081. * Gets a string describing the action executed by the current optimization
  90082. * @returns description string
  90083. */
  90084. SceneOptimization.prototype.getDescription = function () {
  90085. return "";
  90086. };
  90087. /**
  90088. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  90089. * @param scene defines the current scene where to apply this optimization
  90090. * @param optimizer defines the current optimizer
  90091. * @returns true if everything that can be done was applied
  90092. */
  90093. SceneOptimization.prototype.apply = function (scene, optimizer) {
  90094. return true;
  90095. };
  90096. ;
  90097. return SceneOptimization;
  90098. }());
  90099. BABYLON.SceneOptimization = SceneOptimization;
  90100. /**
  90101. * Defines an optimization used to reduce the size of render target textures
  90102. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  90103. */
  90104. var TextureOptimization = /** @class */ (function (_super) {
  90105. __extends(TextureOptimization, _super);
  90106. /**
  90107. * Creates the TextureOptimization object
  90108. * @param priority defines the priority of this optimization (0 by default which means first in the list)
  90109. * @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
  90110. * @param step defines the factor (0.5 by default) used to scale down textures bigger than maximum sized allowed.
  90111. */
  90112. function TextureOptimization(
  90113. /**
  90114. * Defines the priority of this optimization (0 by default which means first in the list)
  90115. */
  90116. priority,
  90117. /**
  90118. * 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
  90119. */
  90120. maximumSize,
  90121. /**
  90122. * Defines the factor (0.5 by default) used to scale down textures bigger than maximum sized allowed.
  90123. */
  90124. step) {
  90125. if (priority === void 0) { priority = 0; }
  90126. if (maximumSize === void 0) { maximumSize = 1024; }
  90127. if (step === void 0) { step = 0.5; }
  90128. var _this = _super.call(this, priority) || this;
  90129. _this.priority = priority;
  90130. _this.maximumSize = maximumSize;
  90131. _this.step = step;
  90132. return _this;
  90133. }
  90134. /**
  90135. * Gets a string describing the action executed by the current optimization
  90136. * @returns description string
  90137. */
  90138. TextureOptimization.prototype.getDescription = function () {
  90139. return "Reducing render target texture size to " + this.maximumSize;
  90140. };
  90141. /**
  90142. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  90143. * @param scene defines the current scene where to apply this optimization
  90144. * @param optimizer defines the current optimizer
  90145. * @returns true if everything that can be done was applied
  90146. */
  90147. TextureOptimization.prototype.apply = function (scene, optimizer) {
  90148. var allDone = true;
  90149. for (var index = 0; index < scene.textures.length; index++) {
  90150. var texture = scene.textures[index];
  90151. if (!texture.canRescale || texture.getContext) {
  90152. continue;
  90153. }
  90154. var currentSize = texture.getSize();
  90155. var maxDimension = Math.max(currentSize.width, currentSize.height);
  90156. if (maxDimension > this.maximumSize) {
  90157. texture.scale(this.step);
  90158. allDone = false;
  90159. }
  90160. }
  90161. return allDone;
  90162. };
  90163. return TextureOptimization;
  90164. }(SceneOptimization));
  90165. BABYLON.TextureOptimization = TextureOptimization;
  90166. /**
  90167. * Defines an optimization used to increase or decrease the rendering resolution
  90168. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  90169. */
  90170. var HardwareScalingOptimization = /** @class */ (function (_super) {
  90171. __extends(HardwareScalingOptimization, _super);
  90172. /**
  90173. * Creates the HardwareScalingOptimization object
  90174. * @param priority defines the priority of this optimization (0 by default which means first in the list)
  90175. * @param maximumScale defines the maximum scale to use (2 by default)
  90176. * @param step defines the step to use between two passes (0.5 by default)
  90177. */
  90178. function HardwareScalingOptimization(
  90179. /**
  90180. * Defines the priority of this optimization (0 by default which means first in the list)
  90181. */
  90182. priority,
  90183. /**
  90184. * Defines the maximum scale to use (2 by default)
  90185. */
  90186. maximumScale,
  90187. /**
  90188. * Defines the step to use between two passes (0.5 by default)
  90189. */
  90190. step) {
  90191. if (priority === void 0) { priority = 0; }
  90192. if (maximumScale === void 0) { maximumScale = 2; }
  90193. if (step === void 0) { step = 0.25; }
  90194. var _this = _super.call(this, priority) || this;
  90195. _this.priority = priority;
  90196. _this.maximumScale = maximumScale;
  90197. _this.step = step;
  90198. _this._currentScale = -1;
  90199. _this._directionOffset = 1;
  90200. return _this;
  90201. }
  90202. /**
  90203. * Gets a string describing the action executed by the current optimization
  90204. * @return description string
  90205. */
  90206. HardwareScalingOptimization.prototype.getDescription = function () {
  90207. return "Setting hardware scaling level to " + this._currentScale;
  90208. };
  90209. /**
  90210. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  90211. * @param scene defines the current scene where to apply this optimization
  90212. * @param optimizer defines the current optimizer
  90213. * @returns true if everything that can be done was applied
  90214. */
  90215. HardwareScalingOptimization.prototype.apply = function (scene, optimizer) {
  90216. if (this._currentScale === -1) {
  90217. this._currentScale = scene.getEngine().getHardwareScalingLevel();
  90218. if (this._currentScale > this.maximumScale) {
  90219. this._directionOffset = -1;
  90220. }
  90221. }
  90222. this._currentScale += this._directionOffset * this.step;
  90223. scene.getEngine().setHardwareScalingLevel(this._currentScale);
  90224. return this._directionOffset === 1 ? this._currentScale >= this.maximumScale : this._currentScale <= this.maximumScale;
  90225. };
  90226. ;
  90227. return HardwareScalingOptimization;
  90228. }(SceneOptimization));
  90229. BABYLON.HardwareScalingOptimization = HardwareScalingOptimization;
  90230. /**
  90231. * Defines an optimization used to remove shadows
  90232. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  90233. */
  90234. var ShadowsOptimization = /** @class */ (function (_super) {
  90235. __extends(ShadowsOptimization, _super);
  90236. function ShadowsOptimization() {
  90237. return _super !== null && _super.apply(this, arguments) || this;
  90238. }
  90239. /**
  90240. * Gets a string describing the action executed by the current optimization
  90241. * @return description string
  90242. */
  90243. ShadowsOptimization.prototype.getDescription = function () {
  90244. return "Turning shadows on/off";
  90245. };
  90246. /**
  90247. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  90248. * @param scene defines the current scene where to apply this optimization
  90249. * @param optimizer defines the current optimizer
  90250. * @returns true if everything that can be done was applied
  90251. */
  90252. ShadowsOptimization.prototype.apply = function (scene, optimizer) {
  90253. scene.shadowsEnabled = optimizer.isInImprovementMode;
  90254. return true;
  90255. };
  90256. ;
  90257. return ShadowsOptimization;
  90258. }(SceneOptimization));
  90259. BABYLON.ShadowsOptimization = ShadowsOptimization;
  90260. /**
  90261. * Defines an optimization used to turn post-processes off
  90262. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  90263. */
  90264. var PostProcessesOptimization = /** @class */ (function (_super) {
  90265. __extends(PostProcessesOptimization, _super);
  90266. function PostProcessesOptimization() {
  90267. return _super !== null && _super.apply(this, arguments) || this;
  90268. }
  90269. /**
  90270. * Gets a string describing the action executed by the current optimization
  90271. * @return description string
  90272. */
  90273. PostProcessesOptimization.prototype.getDescription = function () {
  90274. return "Turning post-processes on/off";
  90275. };
  90276. /**
  90277. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  90278. * @param scene defines the current scene where to apply this optimization
  90279. * @param optimizer defines the current optimizer
  90280. * @returns true if everything that can be done was applied
  90281. */
  90282. PostProcessesOptimization.prototype.apply = function (scene, optimizer) {
  90283. scene.postProcessesEnabled = optimizer.isInImprovementMode;
  90284. return true;
  90285. };
  90286. ;
  90287. return PostProcessesOptimization;
  90288. }(SceneOptimization));
  90289. BABYLON.PostProcessesOptimization = PostProcessesOptimization;
  90290. /**
  90291. * Defines an optimization used to turn lens flares off
  90292. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  90293. */
  90294. var LensFlaresOptimization = /** @class */ (function (_super) {
  90295. __extends(LensFlaresOptimization, _super);
  90296. function LensFlaresOptimization() {
  90297. return _super !== null && _super.apply(this, arguments) || this;
  90298. }
  90299. /**
  90300. * Gets a string describing the action executed by the current optimization
  90301. * @return description string
  90302. */
  90303. LensFlaresOptimization.prototype.getDescription = function () {
  90304. return "Turning lens flares on/off";
  90305. };
  90306. /**
  90307. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  90308. * @param scene defines the current scene where to apply this optimization
  90309. * @param optimizer defines the current optimizer
  90310. * @returns true if everything that can be done was applied
  90311. */
  90312. LensFlaresOptimization.prototype.apply = function (scene, optimizer) {
  90313. scene.lensFlaresEnabled = optimizer.isInImprovementMode;
  90314. return true;
  90315. };
  90316. ;
  90317. return LensFlaresOptimization;
  90318. }(SceneOptimization));
  90319. BABYLON.LensFlaresOptimization = LensFlaresOptimization;
  90320. /**
  90321. * Defines an optimization based on user defined callback.
  90322. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  90323. */
  90324. var CustomOptimization = /** @class */ (function (_super) {
  90325. __extends(CustomOptimization, _super);
  90326. function CustomOptimization() {
  90327. return _super !== null && _super.apply(this, arguments) || this;
  90328. }
  90329. /**
  90330. * Gets a string describing the action executed by the current optimization
  90331. * @returns description string
  90332. */
  90333. CustomOptimization.prototype.getDescription = function () {
  90334. if (this.onGetDescription) {
  90335. return this.onGetDescription();
  90336. }
  90337. return "Running user defined callback";
  90338. };
  90339. /**
  90340. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  90341. * @param scene defines the current scene where to apply this optimization
  90342. * @param optimizer defines the current optimizer
  90343. * @returns true if everything that can be done was applied
  90344. */
  90345. CustomOptimization.prototype.apply = function (scene, optimizer) {
  90346. if (this.onApply) {
  90347. return this.onApply(scene, optimizer);
  90348. }
  90349. return true;
  90350. };
  90351. ;
  90352. return CustomOptimization;
  90353. }(SceneOptimization));
  90354. BABYLON.CustomOptimization = CustomOptimization;
  90355. /**
  90356. * Defines an optimization used to turn particles off
  90357. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  90358. */
  90359. var ParticlesOptimization = /** @class */ (function (_super) {
  90360. __extends(ParticlesOptimization, _super);
  90361. function ParticlesOptimization() {
  90362. return _super !== null && _super.apply(this, arguments) || this;
  90363. }
  90364. /**
  90365. * Gets a string describing the action executed by the current optimization
  90366. * @return description string
  90367. */
  90368. ParticlesOptimization.prototype.getDescription = function () {
  90369. return "Turning particles on/off";
  90370. };
  90371. /**
  90372. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  90373. * @param scene defines the current scene where to apply this optimization
  90374. * @param optimizer defines the current optimizer
  90375. * @returns true if everything that can be done was applied
  90376. */
  90377. ParticlesOptimization.prototype.apply = function (scene, optimizer) {
  90378. scene.particlesEnabled = optimizer.isInImprovementMode;
  90379. return true;
  90380. };
  90381. ;
  90382. return ParticlesOptimization;
  90383. }(SceneOptimization));
  90384. BABYLON.ParticlesOptimization = ParticlesOptimization;
  90385. /**
  90386. * Defines an optimization used to turn render targets off
  90387. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  90388. */
  90389. var RenderTargetsOptimization = /** @class */ (function (_super) {
  90390. __extends(RenderTargetsOptimization, _super);
  90391. function RenderTargetsOptimization() {
  90392. return _super !== null && _super.apply(this, arguments) || this;
  90393. }
  90394. /**
  90395. * Gets a string describing the action executed by the current optimization
  90396. * @return description string
  90397. */
  90398. RenderTargetsOptimization.prototype.getDescription = function () {
  90399. return "Turning render targets off";
  90400. };
  90401. /**
  90402. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  90403. * @param scene defines the current scene where to apply this optimization
  90404. * @param optimizer defines the current optimizer
  90405. * @returns true if everything that can be done was applied
  90406. */
  90407. RenderTargetsOptimization.prototype.apply = function (scene, optimizer) {
  90408. scene.renderTargetsEnabled = optimizer.isInImprovementMode;
  90409. return true;
  90410. };
  90411. ;
  90412. return RenderTargetsOptimization;
  90413. }(SceneOptimization));
  90414. BABYLON.RenderTargetsOptimization = RenderTargetsOptimization;
  90415. /**
  90416. * Defines an optimization used to merge meshes with compatible materials
  90417. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  90418. */
  90419. var MergeMeshesOptimization = /** @class */ (function (_super) {
  90420. __extends(MergeMeshesOptimization, _super);
  90421. function MergeMeshesOptimization() {
  90422. var _this = _super !== null && _super.apply(this, arguments) || this;
  90423. _this._canBeMerged = function (abstractMesh) {
  90424. if (!(abstractMesh instanceof BABYLON.Mesh)) {
  90425. return false;
  90426. }
  90427. var mesh = abstractMesh;
  90428. if (!mesh.isVisible || !mesh.isEnabled()) {
  90429. return false;
  90430. }
  90431. if (mesh.instances.length > 0) {
  90432. return false;
  90433. }
  90434. if (mesh.skeleton || mesh.hasLODLevels) {
  90435. return false;
  90436. }
  90437. if (mesh.parent) {
  90438. return false;
  90439. }
  90440. return true;
  90441. };
  90442. return _this;
  90443. }
  90444. Object.defineProperty(MergeMeshesOptimization, "UpdateSelectionTree", {
  90445. /**
  90446. * Gets or sets a boolean which defines if optimization octree has to be updated
  90447. */
  90448. get: function () {
  90449. return MergeMeshesOptimization._UpdateSelectionTree;
  90450. },
  90451. /**
  90452. * Gets or sets a boolean which defines if optimization octree has to be updated
  90453. */
  90454. set: function (value) {
  90455. MergeMeshesOptimization._UpdateSelectionTree = value;
  90456. },
  90457. enumerable: true,
  90458. configurable: true
  90459. });
  90460. /**
  90461. * Gets a string describing the action executed by the current optimization
  90462. * @return description string
  90463. */
  90464. MergeMeshesOptimization.prototype.getDescription = function () {
  90465. return "Merging similar meshes together";
  90466. };
  90467. /**
  90468. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  90469. * @param scene defines the current scene where to apply this optimization
  90470. * @param optimizer defines the current optimizer
  90471. * @param updateSelectionTree defines that the selection octree has to be updated (false by default)
  90472. * @returns true if everything that can be done was applied
  90473. */
  90474. MergeMeshesOptimization.prototype.apply = function (scene, optimizer, updateSelectionTree) {
  90475. var globalPool = scene.meshes.slice(0);
  90476. var globalLength = globalPool.length;
  90477. for (var index = 0; index < globalLength; index++) {
  90478. var currentPool = new Array();
  90479. var current = globalPool[index];
  90480. // Checks
  90481. if (!this._canBeMerged(current)) {
  90482. continue;
  90483. }
  90484. currentPool.push(current);
  90485. // Find compatible meshes
  90486. for (var subIndex = index + 1; subIndex < globalLength; subIndex++) {
  90487. var otherMesh = globalPool[subIndex];
  90488. if (!this._canBeMerged(otherMesh)) {
  90489. continue;
  90490. }
  90491. if (otherMesh.material !== current.material) {
  90492. continue;
  90493. }
  90494. if (otherMesh.checkCollisions !== current.checkCollisions) {
  90495. continue;
  90496. }
  90497. currentPool.push(otherMesh);
  90498. globalLength--;
  90499. globalPool.splice(subIndex, 1);
  90500. subIndex--;
  90501. }
  90502. if (currentPool.length < 2) {
  90503. continue;
  90504. }
  90505. // Merge meshes
  90506. BABYLON.Mesh.MergeMeshes(currentPool);
  90507. }
  90508. if (updateSelectionTree != undefined) {
  90509. if (updateSelectionTree) {
  90510. scene.createOrUpdateSelectionOctree();
  90511. }
  90512. }
  90513. else if (MergeMeshesOptimization.UpdateSelectionTree) {
  90514. scene.createOrUpdateSelectionOctree();
  90515. }
  90516. return true;
  90517. };
  90518. ;
  90519. MergeMeshesOptimization._UpdateSelectionTree = false;
  90520. return MergeMeshesOptimization;
  90521. }(SceneOptimization));
  90522. BABYLON.MergeMeshesOptimization = MergeMeshesOptimization;
  90523. /**
  90524. * Defines a list of options used by SceneOptimizer
  90525. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  90526. */
  90527. var SceneOptimizerOptions = /** @class */ (function () {
  90528. /**
  90529. * Creates a new list of options used by SceneOptimizer
  90530. * @param targetFrameRate defines the target frame rate to reach (60 by default)
  90531. * @param trackerDuration defines the interval between two checkes (2000ms by default)
  90532. */
  90533. function SceneOptimizerOptions(
  90534. /**
  90535. * Defines the target frame rate to reach (60 by default)
  90536. */
  90537. targetFrameRate,
  90538. /**
  90539. * Defines the interval between two checkes (2000ms by default)
  90540. */
  90541. trackerDuration) {
  90542. if (targetFrameRate === void 0) { targetFrameRate = 60; }
  90543. if (trackerDuration === void 0) { trackerDuration = 2000; }
  90544. this.targetFrameRate = targetFrameRate;
  90545. this.trackerDuration = trackerDuration;
  90546. /**
  90547. * Gets the list of optimizations to apply
  90548. */
  90549. this.optimizations = new Array();
  90550. }
  90551. /**
  90552. * Add a new optimization
  90553. * @param optimization defines the SceneOptimization to add to the list of active optimizations
  90554. * @returns the current SceneOptimizerOptions
  90555. */
  90556. SceneOptimizerOptions.prototype.addOptimization = function (optimization) {
  90557. this.optimizations.push(optimization);
  90558. return this;
  90559. };
  90560. /**
  90561. * Add a new custom optimization
  90562. * @param onApply defines the callback called to apply the custom optimization (true if everything that can be done was applied)
  90563. * @param onGetDescription defines the callback called to get the description attached with the optimization.
  90564. * @param priority defines the priority of this optimization (0 by default which means first in the list)
  90565. * @returns the current SceneOptimizerOptions
  90566. */
  90567. SceneOptimizerOptions.prototype.addCustomOptimization = function (onApply, onGetDescription, priority) {
  90568. if (priority === void 0) { priority = 0; }
  90569. var optimization = new CustomOptimization(priority);
  90570. optimization.onApply = onApply;
  90571. optimization.onGetDescription = onGetDescription;
  90572. this.optimizations.push(optimization);
  90573. return this;
  90574. };
  90575. /**
  90576. * Creates a list of pre-defined optimizations aimed to reduce the visual impact on the scene
  90577. * @param targetFrameRate defines the target frame rate (60 by default)
  90578. * @returns a SceneOptimizerOptions object
  90579. */
  90580. SceneOptimizerOptions.LowDegradationAllowed = function (targetFrameRate) {
  90581. var result = new SceneOptimizerOptions(targetFrameRate);
  90582. var priority = 0;
  90583. result.addOptimization(new MergeMeshesOptimization(priority));
  90584. result.addOptimization(new ShadowsOptimization(priority));
  90585. result.addOptimization(new LensFlaresOptimization(priority));
  90586. // Next priority
  90587. priority++;
  90588. result.addOptimization(new PostProcessesOptimization(priority));
  90589. result.addOptimization(new ParticlesOptimization(priority));
  90590. // Next priority
  90591. priority++;
  90592. result.addOptimization(new TextureOptimization(priority, 1024));
  90593. return result;
  90594. };
  90595. /**
  90596. * Creates a list of pre-defined optimizations aimed to have a moderate impact on the scene visual
  90597. * @param targetFrameRate defines the target frame rate (60 by default)
  90598. * @returns a SceneOptimizerOptions object
  90599. */
  90600. SceneOptimizerOptions.ModerateDegradationAllowed = function (targetFrameRate) {
  90601. var result = new SceneOptimizerOptions(targetFrameRate);
  90602. var priority = 0;
  90603. result.addOptimization(new MergeMeshesOptimization(priority));
  90604. result.addOptimization(new ShadowsOptimization(priority));
  90605. result.addOptimization(new LensFlaresOptimization(priority));
  90606. // Next priority
  90607. priority++;
  90608. result.addOptimization(new PostProcessesOptimization(priority));
  90609. result.addOptimization(new ParticlesOptimization(priority));
  90610. // Next priority
  90611. priority++;
  90612. result.addOptimization(new TextureOptimization(priority, 512));
  90613. // Next priority
  90614. priority++;
  90615. result.addOptimization(new RenderTargetsOptimization(priority));
  90616. // Next priority
  90617. priority++;
  90618. result.addOptimization(new HardwareScalingOptimization(priority, 2));
  90619. return result;
  90620. };
  90621. /**
  90622. * Creates a list of pre-defined optimizations aimed to have a big impact on the scene visual
  90623. * @param targetFrameRate defines the target frame rate (60 by default)
  90624. * @returns a SceneOptimizerOptions object
  90625. */
  90626. SceneOptimizerOptions.HighDegradationAllowed = function (targetFrameRate) {
  90627. var result = new SceneOptimizerOptions(targetFrameRate);
  90628. var priority = 0;
  90629. result.addOptimization(new MergeMeshesOptimization(priority));
  90630. result.addOptimization(new ShadowsOptimization(priority));
  90631. result.addOptimization(new LensFlaresOptimization(priority));
  90632. // Next priority
  90633. priority++;
  90634. result.addOptimization(new PostProcessesOptimization(priority));
  90635. result.addOptimization(new ParticlesOptimization(priority));
  90636. // Next priority
  90637. priority++;
  90638. result.addOptimization(new TextureOptimization(priority, 256));
  90639. // Next priority
  90640. priority++;
  90641. result.addOptimization(new RenderTargetsOptimization(priority));
  90642. // Next priority
  90643. priority++;
  90644. result.addOptimization(new HardwareScalingOptimization(priority, 4));
  90645. return result;
  90646. };
  90647. return SceneOptimizerOptions;
  90648. }());
  90649. BABYLON.SceneOptimizerOptions = SceneOptimizerOptions;
  90650. /**
  90651. * Class used to run optimizations in order to reach a target frame rate
  90652. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  90653. */
  90654. var SceneOptimizer = /** @class */ (function () {
  90655. /**
  90656. * Creates a new SceneOptimizer
  90657. * @param scene defines the scene to work on
  90658. * @param options defines the options to use with the SceneOptimizer
  90659. * @param autoGeneratePriorities defines if priorities must be generated and not read from SceneOptimization property (true by default)
  90660. * @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)
  90661. */
  90662. function SceneOptimizer(scene, options, autoGeneratePriorities, improvementMode) {
  90663. if (autoGeneratePriorities === void 0) { autoGeneratePriorities = true; }
  90664. if (improvementMode === void 0) { improvementMode = false; }
  90665. var _this = this;
  90666. this._isRunning = false;
  90667. this._currentPriorityLevel = 0;
  90668. this._targetFrameRate = 60;
  90669. this._trackerDuration = 2000;
  90670. this._currentFrameRate = 0;
  90671. this._improvementMode = false;
  90672. /**
  90673. * Defines an observable called when the optimizer reaches the target frame rate
  90674. */
  90675. this.onSuccessObservable = new BABYLON.Observable();
  90676. /**
  90677. * Defines an observable called when the optimizer enables an optimization
  90678. */
  90679. this.onNewOptimizationAppliedObservable = new BABYLON.Observable();
  90680. /**
  90681. * Defines an observable called when the optimizer is not able to reach the target frame rate
  90682. */
  90683. this.onFailureObservable = new BABYLON.Observable();
  90684. if (!options) {
  90685. this._options = new SceneOptimizerOptions();
  90686. }
  90687. else {
  90688. this._options = options;
  90689. }
  90690. if (this._options.targetFrameRate) {
  90691. this._targetFrameRate = this._options.targetFrameRate;
  90692. }
  90693. if (this._options.trackerDuration) {
  90694. this._trackerDuration = this._options.trackerDuration;
  90695. }
  90696. if (autoGeneratePriorities) {
  90697. var priority = 0;
  90698. for (var _i = 0, _a = this._options.optimizations; _i < _a.length; _i++) {
  90699. var optim = _a[_i];
  90700. optim.priority = priority++;
  90701. }
  90702. }
  90703. this._improvementMode = improvementMode;
  90704. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  90705. this._sceneDisposeObserver = this._scene.onDisposeObservable.add(function () {
  90706. _this._sceneDisposeObserver = null;
  90707. _this.dispose();
  90708. });
  90709. }
  90710. Object.defineProperty(SceneOptimizer.prototype, "isInImprovementMode", {
  90711. /**
  90712. * Gets a boolean indicating if the optimizer is in improvement mode
  90713. */
  90714. get: function () {
  90715. return this._improvementMode;
  90716. },
  90717. enumerable: true,
  90718. configurable: true
  90719. });
  90720. Object.defineProperty(SceneOptimizer.prototype, "currentPriorityLevel", {
  90721. /**
  90722. * Gets the current priority level (0 at start)
  90723. */
  90724. get: function () {
  90725. return this._currentPriorityLevel;
  90726. },
  90727. enumerable: true,
  90728. configurable: true
  90729. });
  90730. Object.defineProperty(SceneOptimizer.prototype, "currentFrameRate", {
  90731. /**
  90732. * Gets the current frame rate checked by the SceneOptimizer
  90733. */
  90734. get: function () {
  90735. return this._currentFrameRate;
  90736. },
  90737. enumerable: true,
  90738. configurable: true
  90739. });
  90740. Object.defineProperty(SceneOptimizer.prototype, "targetFrameRate", {
  90741. /**
  90742. * Gets or sets the current target frame rate (60 by default)
  90743. */
  90744. get: function () {
  90745. return this._targetFrameRate;
  90746. },
  90747. /**
  90748. * Gets or sets the current target frame rate (60 by default)
  90749. */
  90750. set: function (value) {
  90751. this._targetFrameRate = value;
  90752. },
  90753. enumerable: true,
  90754. configurable: true
  90755. });
  90756. Object.defineProperty(SceneOptimizer.prototype, "trackerDuration", {
  90757. /**
  90758. * Gets or sets the current interval between two checks (every 2000ms by default)
  90759. */
  90760. get: function () {
  90761. return this._trackerDuration;
  90762. },
  90763. /**
  90764. * Gets or sets the current interval between two checks (every 2000ms by default)
  90765. */
  90766. set: function (value) {
  90767. this._trackerDuration = value;
  90768. },
  90769. enumerable: true,
  90770. configurable: true
  90771. });
  90772. Object.defineProperty(SceneOptimizer.prototype, "optimizations", {
  90773. /**
  90774. * Gets the list of active optimizations
  90775. */
  90776. get: function () {
  90777. return this._options.optimizations;
  90778. },
  90779. enumerable: true,
  90780. configurable: true
  90781. });
  90782. /**
  90783. * Stops the current optimizer
  90784. */
  90785. SceneOptimizer.prototype.stop = function () {
  90786. this._isRunning = false;
  90787. };
  90788. /**
  90789. * Reset the optimizer to initial step (current priority level = 0)
  90790. */
  90791. SceneOptimizer.prototype.reset = function () {
  90792. this._currentPriorityLevel = 0;
  90793. };
  90794. /**
  90795. * Start the optimizer. By default it will try to reach a specific framerate
  90796. * but if the optimizer is set with improvementMode === true then it will run all optimiatiation while frame rate is above the target frame rate
  90797. */
  90798. SceneOptimizer.prototype.start = function () {
  90799. var _this = this;
  90800. if (this._isRunning) {
  90801. return;
  90802. }
  90803. this._isRunning = true;
  90804. // Let's wait for the scene to be ready before running our check
  90805. this._scene.executeWhenReady(function () {
  90806. setTimeout(function () {
  90807. _this._checkCurrentState();
  90808. }, _this._trackerDuration);
  90809. });
  90810. };
  90811. SceneOptimizer.prototype._checkCurrentState = function () {
  90812. var _this = this;
  90813. if (!this._isRunning) {
  90814. return;
  90815. }
  90816. var scene = this._scene;
  90817. var options = this._options;
  90818. this._currentFrameRate = Math.round(scene.getEngine().getFps());
  90819. if (this._improvementMode && this._currentFrameRate <= this._targetFrameRate ||
  90820. !this._improvementMode && this._currentFrameRate >= this._targetFrameRate) {
  90821. this._isRunning = false;
  90822. this.onSuccessObservable.notifyObservers(this);
  90823. return;
  90824. }
  90825. // Apply current level of optimizations
  90826. var allDone = true;
  90827. var noOptimizationApplied = true;
  90828. for (var index = 0; index < options.optimizations.length; index++) {
  90829. var optimization = options.optimizations[index];
  90830. if (optimization.priority === this._currentPriorityLevel) {
  90831. noOptimizationApplied = false;
  90832. allDone = allDone && optimization.apply(scene, this);
  90833. this.onNewOptimizationAppliedObservable.notifyObservers(optimization);
  90834. }
  90835. }
  90836. // If no optimization was applied, this is a failure :(
  90837. if (noOptimizationApplied) {
  90838. this._isRunning = false;
  90839. this.onFailureObservable.notifyObservers(this);
  90840. return;
  90841. }
  90842. // If all optimizations were done, move to next level
  90843. if (allDone) {
  90844. this._currentPriorityLevel++;
  90845. }
  90846. // Let's the system running for a specific amount of time before checking FPS
  90847. scene.executeWhenReady(function () {
  90848. setTimeout(function () {
  90849. _this._checkCurrentState();
  90850. }, _this._trackerDuration);
  90851. });
  90852. };
  90853. /**
  90854. * Release all resources
  90855. */
  90856. SceneOptimizer.prototype.dispose = function () {
  90857. this.stop();
  90858. this.onSuccessObservable.clear();
  90859. this.onFailureObservable.clear();
  90860. this.onNewOptimizationAppliedObservable.clear();
  90861. if (this._sceneDisposeObserver) {
  90862. this._scene.onDisposeObservable.remove(this._sceneDisposeObserver);
  90863. }
  90864. };
  90865. /**
  90866. * Helper function to create a SceneOptimizer with one single line of code
  90867. * @param scene defines the scene to work on
  90868. * @param options defines the options to use with the SceneOptimizer
  90869. * @param onSuccess defines a callback to call on success
  90870. * @param onFailure defines a callback to call on failure
  90871. * @returns the new SceneOptimizer object
  90872. */
  90873. SceneOptimizer.OptimizeAsync = function (scene, options, onSuccess, onFailure) {
  90874. var optimizer = new SceneOptimizer(scene, options || SceneOptimizerOptions.ModerateDegradationAllowed(), false);
  90875. if (onSuccess) {
  90876. optimizer.onSuccessObservable.add(function () {
  90877. onSuccess();
  90878. });
  90879. }
  90880. if (onFailure) {
  90881. optimizer.onFailureObservable.add(function () {
  90882. onFailure();
  90883. });
  90884. }
  90885. optimizer.start();
  90886. return optimizer;
  90887. };
  90888. return SceneOptimizer;
  90889. }());
  90890. BABYLON.SceneOptimizer = SceneOptimizer;
  90891. })(BABYLON || (BABYLON = {}));
  90892. //# sourceMappingURL=babylon.sceneOptimizer.js.map
  90893. var BABYLON;
  90894. (function (BABYLON) {
  90895. var OutlineRenderer = /** @class */ (function () {
  90896. function OutlineRenderer(scene) {
  90897. this.zOffset = 1;
  90898. this._scene = scene;
  90899. }
  90900. OutlineRenderer.prototype.render = function (subMesh, batch, useOverlay) {
  90901. var _this = this;
  90902. if (useOverlay === void 0) { useOverlay = false; }
  90903. var scene = this._scene;
  90904. var engine = this._scene.getEngine();
  90905. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  90906. if (!this.isReady(subMesh, hardwareInstancedRendering)) {
  90907. return;
  90908. }
  90909. var mesh = subMesh.getRenderingMesh();
  90910. var material = subMesh.getMaterial();
  90911. if (!material || !scene.activeCamera) {
  90912. return;
  90913. }
  90914. engine.enableEffect(this._effect);
  90915. // Logarithmic depth
  90916. if (material.useLogarithmicDepth) {
  90917. this._effect.setFloat("logarithmicDepthConstant", 2.0 / (Math.log(scene.activeCamera.maxZ + 1.0) / Math.LN2));
  90918. }
  90919. this._effect.setFloat("offset", useOverlay ? 0 : mesh.outlineWidth);
  90920. this._effect.setColor4("color", useOverlay ? mesh.overlayColor : mesh.outlineColor, useOverlay ? mesh.overlayAlpha : material.alpha);
  90921. this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
  90922. // Bones
  90923. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  90924. this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  90925. }
  90926. mesh._bind(subMesh, this._effect, BABYLON.Material.TriangleFillMode);
  90927. // Alpha test
  90928. if (material && material.needAlphaTesting()) {
  90929. var alphaTexture = material.getAlphaTestTexture();
  90930. if (alphaTexture) {
  90931. this._effect.setTexture("diffuseSampler", alphaTexture);
  90932. this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  90933. }
  90934. }
  90935. engine.setZOffset(-this.zOffset);
  90936. mesh._processRendering(subMesh, this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { _this._effect.setMatrix("world", world); });
  90937. engine.setZOffset(0);
  90938. };
  90939. OutlineRenderer.prototype.isReady = function (subMesh, useInstances) {
  90940. var defines = [];
  90941. var attribs = [BABYLON.VertexBuffer.PositionKind, BABYLON.VertexBuffer.NormalKind];
  90942. var mesh = subMesh.getMesh();
  90943. var material = subMesh.getMaterial();
  90944. if (material) {
  90945. // Alpha test
  90946. if (material.needAlphaTesting()) {
  90947. defines.push("#define ALPHATEST");
  90948. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  90949. attribs.push(BABYLON.VertexBuffer.UVKind);
  90950. defines.push("#define UV1");
  90951. }
  90952. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  90953. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  90954. defines.push("#define UV2");
  90955. }
  90956. }
  90957. //Logarithmic depth
  90958. if (material.useLogarithmicDepth) {
  90959. defines.push("#define LOGARITHMICDEPTH");
  90960. }
  90961. }
  90962. // Bones
  90963. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  90964. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  90965. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  90966. if (mesh.numBoneInfluencers > 4) {
  90967. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  90968. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  90969. }
  90970. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  90971. defines.push("#define BonesPerMesh " + (mesh.skeleton ? mesh.skeleton.bones.length + 1 : 0));
  90972. }
  90973. else {
  90974. defines.push("#define NUM_BONE_INFLUENCERS 0");
  90975. }
  90976. // Instances
  90977. if (useInstances) {
  90978. defines.push("#define INSTANCES");
  90979. attribs.push("world0");
  90980. attribs.push("world1");
  90981. attribs.push("world2");
  90982. attribs.push("world3");
  90983. }
  90984. // Get correct effect
  90985. var join = defines.join("\n");
  90986. if (this._cachedDefines !== join) {
  90987. this._cachedDefines = join;
  90988. this._effect = this._scene.getEngine().createEffect("outline", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "offset", "color", "logarithmicDepthConstant"], ["diffuseSampler"], join);
  90989. }
  90990. return this._effect.isReady();
  90991. };
  90992. return OutlineRenderer;
  90993. }());
  90994. BABYLON.OutlineRenderer = OutlineRenderer;
  90995. })(BABYLON || (BABYLON = {}));
  90996. //# sourceMappingURL=babylon.outlineRenderer.js.map
  90997. var BABYLON;
  90998. (function (BABYLON) {
  90999. var FaceAdjacencies = /** @class */ (function () {
  91000. function FaceAdjacencies() {
  91001. this.edges = new Array();
  91002. this.edgesConnectedCount = 0;
  91003. }
  91004. return FaceAdjacencies;
  91005. }());
  91006. var EdgesRenderer = /** @class */ (function () {
  91007. // Beware when you use this class with complex objects as the adjacencies computation can be really long
  91008. function EdgesRenderer(source, epsilon, checkVerticesInsteadOfIndices) {
  91009. if (epsilon === void 0) { epsilon = 0.95; }
  91010. if (checkVerticesInsteadOfIndices === void 0) { checkVerticesInsteadOfIndices = false; }
  91011. this.edgesWidthScalerForOrthographic = 1000.0;
  91012. this.edgesWidthScalerForPerspective = 50.0;
  91013. this._linesPositions = new Array();
  91014. this._linesNormals = new Array();
  91015. this._linesIndices = new Array();
  91016. this._buffers = {};
  91017. this._checkVerticesInsteadOfIndices = false;
  91018. this._source = source;
  91019. this._checkVerticesInsteadOfIndices = checkVerticesInsteadOfIndices;
  91020. this._epsilon = epsilon;
  91021. this._prepareRessources();
  91022. this._generateEdgesLines();
  91023. }
  91024. EdgesRenderer.prototype._prepareRessources = function () {
  91025. if (this._lineShader) {
  91026. return;
  91027. }
  91028. this._lineShader = new BABYLON.ShaderMaterial("lineShader", this._source.getScene(), "line", {
  91029. attributes: ["position", "normal"],
  91030. uniforms: ["worldViewProjection", "color", "width", "aspectRatio"]
  91031. });
  91032. this._lineShader.disableDepthWrite = true;
  91033. this._lineShader.backFaceCulling = false;
  91034. };
  91035. EdgesRenderer.prototype._rebuild = function () {
  91036. var buffer = this._buffers[BABYLON.VertexBuffer.PositionKind];
  91037. if (buffer) {
  91038. buffer._rebuild();
  91039. }
  91040. buffer = this._buffers[BABYLON.VertexBuffer.NormalKind];
  91041. if (buffer) {
  91042. buffer._rebuild();
  91043. }
  91044. var scene = this._source.getScene();
  91045. var engine = scene.getEngine();
  91046. this._ib = engine.createIndexBuffer(this._linesIndices);
  91047. };
  91048. EdgesRenderer.prototype.dispose = function () {
  91049. var buffer = this._buffers[BABYLON.VertexBuffer.PositionKind];
  91050. if (buffer) {
  91051. buffer.dispose();
  91052. this._buffers[BABYLON.VertexBuffer.PositionKind] = null;
  91053. }
  91054. buffer = this._buffers[BABYLON.VertexBuffer.NormalKind];
  91055. if (buffer) {
  91056. buffer.dispose();
  91057. this._buffers[BABYLON.VertexBuffer.NormalKind] = null;
  91058. }
  91059. this._source.getScene().getEngine()._releaseBuffer(this._ib);
  91060. this._lineShader.dispose();
  91061. };
  91062. EdgesRenderer.prototype._processEdgeForAdjacencies = function (pa, pb, p0, p1, p2) {
  91063. if (pa === p0 && pb === p1 || pa === p1 && pb === p0) {
  91064. return 0;
  91065. }
  91066. if (pa === p1 && pb === p2 || pa === p2 && pb === p1) {
  91067. return 1;
  91068. }
  91069. if (pa === p2 && pb === p0 || pa === p0 && pb === p2) {
  91070. return 2;
  91071. }
  91072. return -1;
  91073. };
  91074. EdgesRenderer.prototype._processEdgeForAdjacenciesWithVertices = function (pa, pb, p0, p1, p2) {
  91075. if (pa.equalsWithEpsilon(p0) && pb.equalsWithEpsilon(p1) || pa.equalsWithEpsilon(p1) && pb.equalsWithEpsilon(p0)) {
  91076. return 0;
  91077. }
  91078. if (pa.equalsWithEpsilon(p1) && pb.equalsWithEpsilon(p2) || pa.equalsWithEpsilon(p2) && pb.equalsWithEpsilon(p1)) {
  91079. return 1;
  91080. }
  91081. if (pa.equalsWithEpsilon(p2) && pb.equalsWithEpsilon(p0) || pa.equalsWithEpsilon(p0) && pb.equalsWithEpsilon(p2)) {
  91082. return 2;
  91083. }
  91084. return -1;
  91085. };
  91086. EdgesRenderer.prototype._checkEdge = function (faceIndex, edge, faceNormals, p0, p1) {
  91087. var needToCreateLine;
  91088. if (edge === undefined) {
  91089. needToCreateLine = true;
  91090. }
  91091. else {
  91092. var dotProduct = BABYLON.Vector3.Dot(faceNormals[faceIndex], faceNormals[edge]);
  91093. needToCreateLine = dotProduct < this._epsilon;
  91094. }
  91095. if (needToCreateLine) {
  91096. var offset = this._linesPositions.length / 3;
  91097. var normal = p0.subtract(p1);
  91098. normal.normalize();
  91099. // Positions
  91100. this._linesPositions.push(p0.x);
  91101. this._linesPositions.push(p0.y);
  91102. this._linesPositions.push(p0.z);
  91103. this._linesPositions.push(p0.x);
  91104. this._linesPositions.push(p0.y);
  91105. this._linesPositions.push(p0.z);
  91106. this._linesPositions.push(p1.x);
  91107. this._linesPositions.push(p1.y);
  91108. this._linesPositions.push(p1.z);
  91109. this._linesPositions.push(p1.x);
  91110. this._linesPositions.push(p1.y);
  91111. this._linesPositions.push(p1.z);
  91112. // Normals
  91113. this._linesNormals.push(p1.x);
  91114. this._linesNormals.push(p1.y);
  91115. this._linesNormals.push(p1.z);
  91116. this._linesNormals.push(-1);
  91117. this._linesNormals.push(p1.x);
  91118. this._linesNormals.push(p1.y);
  91119. this._linesNormals.push(p1.z);
  91120. this._linesNormals.push(1);
  91121. this._linesNormals.push(p0.x);
  91122. this._linesNormals.push(p0.y);
  91123. this._linesNormals.push(p0.z);
  91124. this._linesNormals.push(-1);
  91125. this._linesNormals.push(p0.x);
  91126. this._linesNormals.push(p0.y);
  91127. this._linesNormals.push(p0.z);
  91128. this._linesNormals.push(1);
  91129. // Indices
  91130. this._linesIndices.push(offset);
  91131. this._linesIndices.push(offset + 1);
  91132. this._linesIndices.push(offset + 2);
  91133. this._linesIndices.push(offset);
  91134. this._linesIndices.push(offset + 2);
  91135. this._linesIndices.push(offset + 3);
  91136. }
  91137. };
  91138. EdgesRenderer.prototype._generateEdgesLines = function () {
  91139. var positions = this._source.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  91140. var indices = this._source.getIndices();
  91141. if (!indices || !positions) {
  91142. return;
  91143. }
  91144. // First let's find adjacencies
  91145. var adjacencies = new Array();
  91146. var faceNormals = new Array();
  91147. var index;
  91148. var faceAdjacencies;
  91149. // Prepare faces
  91150. for (index = 0; index < indices.length; index += 3) {
  91151. faceAdjacencies = new FaceAdjacencies();
  91152. var p0Index = indices[index];
  91153. var p1Index = indices[index + 1];
  91154. var p2Index = indices[index + 2];
  91155. faceAdjacencies.p0 = new BABYLON.Vector3(positions[p0Index * 3], positions[p0Index * 3 + 1], positions[p0Index * 3 + 2]);
  91156. faceAdjacencies.p1 = new BABYLON.Vector3(positions[p1Index * 3], positions[p1Index * 3 + 1], positions[p1Index * 3 + 2]);
  91157. faceAdjacencies.p2 = new BABYLON.Vector3(positions[p2Index * 3], positions[p2Index * 3 + 1], positions[p2Index * 3 + 2]);
  91158. var faceNormal = BABYLON.Vector3.Cross(faceAdjacencies.p1.subtract(faceAdjacencies.p0), faceAdjacencies.p2.subtract(faceAdjacencies.p1));
  91159. faceNormal.normalize();
  91160. faceNormals.push(faceNormal);
  91161. adjacencies.push(faceAdjacencies);
  91162. }
  91163. // Scan
  91164. for (index = 0; index < adjacencies.length; index++) {
  91165. faceAdjacencies = adjacencies[index];
  91166. for (var otherIndex = index + 1; otherIndex < adjacencies.length; otherIndex++) {
  91167. var otherFaceAdjacencies = adjacencies[otherIndex];
  91168. if (faceAdjacencies.edgesConnectedCount === 3) { // Full
  91169. break;
  91170. }
  91171. if (otherFaceAdjacencies.edgesConnectedCount === 3) { // Full
  91172. continue;
  91173. }
  91174. var otherP0 = indices[otherIndex * 3];
  91175. var otherP1 = indices[otherIndex * 3 + 1];
  91176. var otherP2 = indices[otherIndex * 3 + 2];
  91177. for (var edgeIndex = 0; edgeIndex < 3; edgeIndex++) {
  91178. var otherEdgeIndex = 0;
  91179. if (faceAdjacencies.edges[edgeIndex] !== undefined) {
  91180. continue;
  91181. }
  91182. switch (edgeIndex) {
  91183. case 0:
  91184. if (this._checkVerticesInsteadOfIndices) {
  91185. otherEdgeIndex = this._processEdgeForAdjacenciesWithVertices(faceAdjacencies.p0, faceAdjacencies.p1, otherFaceAdjacencies.p0, otherFaceAdjacencies.p1, otherFaceAdjacencies.p2);
  91186. }
  91187. else {
  91188. otherEdgeIndex = this._processEdgeForAdjacencies(indices[index * 3], indices[index * 3 + 1], otherP0, otherP1, otherP2);
  91189. }
  91190. break;
  91191. case 1:
  91192. if (this._checkVerticesInsteadOfIndices) {
  91193. otherEdgeIndex = this._processEdgeForAdjacenciesWithVertices(faceAdjacencies.p1, faceAdjacencies.p2, otherFaceAdjacencies.p0, otherFaceAdjacencies.p1, otherFaceAdjacencies.p2);
  91194. }
  91195. else {
  91196. otherEdgeIndex = this._processEdgeForAdjacencies(indices[index * 3 + 1], indices[index * 3 + 2], otherP0, otherP1, otherP2);
  91197. }
  91198. break;
  91199. case 2:
  91200. if (this._checkVerticesInsteadOfIndices) {
  91201. otherEdgeIndex = this._processEdgeForAdjacenciesWithVertices(faceAdjacencies.p2, faceAdjacencies.p0, otherFaceAdjacencies.p0, otherFaceAdjacencies.p1, otherFaceAdjacencies.p2);
  91202. }
  91203. else {
  91204. otherEdgeIndex = this._processEdgeForAdjacencies(indices[index * 3 + 2], indices[index * 3], otherP0, otherP1, otherP2);
  91205. }
  91206. break;
  91207. }
  91208. if (otherEdgeIndex === -1) {
  91209. continue;
  91210. }
  91211. faceAdjacencies.edges[edgeIndex] = otherIndex;
  91212. otherFaceAdjacencies.edges[otherEdgeIndex] = index;
  91213. faceAdjacencies.edgesConnectedCount++;
  91214. otherFaceAdjacencies.edgesConnectedCount++;
  91215. if (faceAdjacencies.edgesConnectedCount === 3) {
  91216. break;
  91217. }
  91218. }
  91219. }
  91220. }
  91221. // Create lines
  91222. for (index = 0; index < adjacencies.length; index++) {
  91223. // 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
  91224. var current = adjacencies[index];
  91225. this._checkEdge(index, current.edges[0], faceNormals, current.p0, current.p1);
  91226. this._checkEdge(index, current.edges[1], faceNormals, current.p1, current.p2);
  91227. this._checkEdge(index, current.edges[2], faceNormals, current.p2, current.p0);
  91228. }
  91229. // Merge into a single mesh
  91230. var engine = this._source.getScene().getEngine();
  91231. this._buffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(engine, this._linesPositions, BABYLON.VertexBuffer.PositionKind, false);
  91232. this._buffers[BABYLON.VertexBuffer.NormalKind] = new BABYLON.VertexBuffer(engine, this._linesNormals, BABYLON.VertexBuffer.NormalKind, false, false, 4);
  91233. this._ib = engine.createIndexBuffer(this._linesIndices);
  91234. this._indicesCount = this._linesIndices.length;
  91235. };
  91236. EdgesRenderer.prototype.render = function () {
  91237. var scene = this._source.getScene();
  91238. if (!this._lineShader.isReady() || !scene.activeCamera) {
  91239. return;
  91240. }
  91241. var engine = scene.getEngine();
  91242. this._lineShader._preBind();
  91243. // VBOs
  91244. engine.bindBuffers(this._buffers, this._ib, this._lineShader.getEffect());
  91245. scene.resetCachedMaterial();
  91246. this._lineShader.setColor4("color", this._source.edgesColor);
  91247. if (scene.activeCamera.mode === BABYLON.Camera.ORTHOGRAPHIC_CAMERA) {
  91248. this._lineShader.setFloat("width", this._source.edgesWidth / this.edgesWidthScalerForOrthographic);
  91249. }
  91250. else {
  91251. this._lineShader.setFloat("width", this._source.edgesWidth / this.edgesWidthScalerForPerspective);
  91252. }
  91253. this._lineShader.setFloat("aspectRatio", engine.getAspectRatio(scene.activeCamera));
  91254. this._lineShader.bind(this._source.getWorldMatrix());
  91255. // Draw order
  91256. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, this._indicesCount);
  91257. this._lineShader.unbind();
  91258. engine.setDepthWrite(true);
  91259. };
  91260. return EdgesRenderer;
  91261. }());
  91262. BABYLON.EdgesRenderer = EdgesRenderer;
  91263. })(BABYLON || (BABYLON = {}));
  91264. //# sourceMappingURL=babylon.edgesRenderer.js.map
  91265. var __assign = (this && this.__assign) || Object.assign || function(t) {
  91266. for (var s, i = 1, n = arguments.length; i < n; i++) {
  91267. s = arguments[i];
  91268. for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
  91269. t[p] = s[p];
  91270. }
  91271. return t;
  91272. };
  91273. var BABYLON;
  91274. (function (BABYLON) {
  91275. /**
  91276. * The effect layer Helps adding post process effect blended with the main pass.
  91277. *
  91278. * This can be for instance use to generate glow or higlight effects on the scene.
  91279. *
  91280. * The effect layer class can not be used directly and is intented to inherited from to be
  91281. * customized per effects.
  91282. */
  91283. var EffectLayer = /** @class */ (function () {
  91284. /**
  91285. * Instantiates a new effect Layer and references it in the scene.
  91286. * @param name The name of the layer
  91287. * @param scene The scene to use the layer in
  91288. */
  91289. function EffectLayer(
  91290. /** The Friendly of the effect in the scene */
  91291. name, scene) {
  91292. this._vertexBuffers = {};
  91293. this._maxSize = 0;
  91294. this._mainTextureDesiredSize = { width: 0, height: 0 };
  91295. this._shouldRender = true;
  91296. this._postProcesses = [];
  91297. this._textures = [];
  91298. this._emissiveTextureAndColor = { texture: null, color: new BABYLON.Color4() };
  91299. /**
  91300. * The clear color of the texture used to generate the glow map.
  91301. */
  91302. this.neutralColor = new BABYLON.Color4();
  91303. /**
  91304. * Specifies wether the highlight layer is enabled or not.
  91305. */
  91306. this.isEnabled = true;
  91307. /**
  91308. * An event triggered when the effect layer has been disposed.
  91309. */
  91310. this.onDisposeObservable = new BABYLON.Observable();
  91311. /**
  91312. * An event triggered when the effect layer is about rendering the main texture with the glowy parts.
  91313. */
  91314. this.onBeforeRenderMainTextureObservable = new BABYLON.Observable();
  91315. /**
  91316. * An event triggered when the generated texture is being merged in the scene.
  91317. */
  91318. this.onBeforeComposeObservable = new BABYLON.Observable();
  91319. /**
  91320. * An event triggered when the generated texture has been merged in the scene.
  91321. */
  91322. this.onAfterComposeObservable = new BABYLON.Observable();
  91323. /**
  91324. * An event triggered when the efffect layer changes its size.
  91325. */
  91326. this.onSizeChangedObservable = new BABYLON.Observable();
  91327. this.name = name;
  91328. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  91329. this._engine = scene.getEngine();
  91330. this._maxSize = this._engine.getCaps().maxTextureSize;
  91331. this._scene.effectLayers.push(this);
  91332. // Generate Buffers
  91333. this._generateIndexBuffer();
  91334. this._genrateVertexBuffer();
  91335. }
  91336. Object.defineProperty(EffectLayer.prototype, "camera", {
  91337. /**
  91338. * Gets the camera attached to the layer.
  91339. */
  91340. get: function () {
  91341. return this._effectLayerOptions.camera;
  91342. },
  91343. enumerable: true,
  91344. configurable: true
  91345. });
  91346. /**
  91347. * Initializes the effect layer with the required options.
  91348. * @param options Sets of none mandatory options to use with the layer (see IEffectLayerOptions for more information)
  91349. */
  91350. EffectLayer.prototype._init = function (options) {
  91351. // Adapt options
  91352. this._effectLayerOptions = __assign({ mainTextureRatio: 0.5, alphaBlendingMode: BABYLON.Engine.ALPHA_COMBINE, camera: null }, options);
  91353. this._setMainTextureSize();
  91354. this._createMainTexture();
  91355. this._createTextureAndPostProcesses();
  91356. this._mergeEffect = this._createMergeEffect();
  91357. };
  91358. /**
  91359. * Generates the index buffer of the full screen quad blending to the main canvas.
  91360. */
  91361. EffectLayer.prototype._generateIndexBuffer = function () {
  91362. // Indices
  91363. var indices = [];
  91364. indices.push(0);
  91365. indices.push(1);
  91366. indices.push(2);
  91367. indices.push(0);
  91368. indices.push(2);
  91369. indices.push(3);
  91370. this._indexBuffer = this._engine.createIndexBuffer(indices);
  91371. };
  91372. /**
  91373. * Generates the vertex buffer of the full screen quad blending to the main canvas.
  91374. */
  91375. EffectLayer.prototype._genrateVertexBuffer = function () {
  91376. // VBO
  91377. var vertices = [];
  91378. vertices.push(1, 1);
  91379. vertices.push(-1, 1);
  91380. vertices.push(-1, -1);
  91381. vertices.push(1, -1);
  91382. var vertexBuffer = new BABYLON.VertexBuffer(this._engine, vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  91383. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = vertexBuffer;
  91384. };
  91385. /**
  91386. * Sets the main texture desired size which is the closest power of two
  91387. * of the engine canvas size.
  91388. */
  91389. EffectLayer.prototype._setMainTextureSize = function () {
  91390. if (this._effectLayerOptions.mainTextureFixedSize) {
  91391. this._mainTextureDesiredSize.width = this._effectLayerOptions.mainTextureFixedSize;
  91392. this._mainTextureDesiredSize.height = this._effectLayerOptions.mainTextureFixedSize;
  91393. }
  91394. else {
  91395. this._mainTextureDesiredSize.width = this._engine.getRenderWidth() * this._effectLayerOptions.mainTextureRatio;
  91396. this._mainTextureDesiredSize.height = this._engine.getRenderHeight() * this._effectLayerOptions.mainTextureRatio;
  91397. this._mainTextureDesiredSize.width = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(this._mainTextureDesiredSize.width, this._maxSize) : this._mainTextureDesiredSize.width;
  91398. this._mainTextureDesiredSize.height = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(this._mainTextureDesiredSize.height, this._maxSize) : this._mainTextureDesiredSize.height;
  91399. }
  91400. this._mainTextureDesiredSize.width = Math.floor(this._mainTextureDesiredSize.width);
  91401. this._mainTextureDesiredSize.height = Math.floor(this._mainTextureDesiredSize.height);
  91402. };
  91403. /**
  91404. * Creates the main texture for the effect layer.
  91405. */
  91406. EffectLayer.prototype._createMainTexture = function () {
  91407. var _this = this;
  91408. this._mainTexture = new BABYLON.RenderTargetTexture("HighlightLayerMainRTT", {
  91409. width: this._mainTextureDesiredSize.width,
  91410. height: this._mainTextureDesiredSize.height
  91411. }, this._scene, false, true, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  91412. this._mainTexture.activeCamera = this._effectLayerOptions.camera;
  91413. this._mainTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  91414. this._mainTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  91415. this._mainTexture.anisotropicFilteringLevel = 1;
  91416. this._mainTexture.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  91417. this._mainTexture.renderParticles = false;
  91418. this._mainTexture.renderList = null;
  91419. this._mainTexture.ignoreCameraViewport = true;
  91420. // Custom render function
  91421. this._mainTexture.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes, depthOnlySubMeshes) {
  91422. _this.onBeforeRenderMainTextureObservable.notifyObservers(_this);
  91423. var index;
  91424. var engine = _this._scene.getEngine();
  91425. if (depthOnlySubMeshes.length) {
  91426. engine.setColorWrite(false);
  91427. for (index = 0; index < depthOnlySubMeshes.length; index++) {
  91428. _this._renderSubMesh(depthOnlySubMeshes.data[index]);
  91429. }
  91430. engine.setColorWrite(true);
  91431. }
  91432. for (index = 0; index < opaqueSubMeshes.length; index++) {
  91433. _this._renderSubMesh(opaqueSubMeshes.data[index]);
  91434. }
  91435. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  91436. _this._renderSubMesh(alphaTestSubMeshes.data[index]);
  91437. }
  91438. for (index = 0; index < transparentSubMeshes.length; index++) {
  91439. _this._renderSubMesh(transparentSubMeshes.data[index]);
  91440. }
  91441. };
  91442. this._mainTexture.onClearObservable.add(function (engine) {
  91443. engine.clear(_this.neutralColor, true, true, true);
  91444. });
  91445. };
  91446. /**
  91447. * Checks for the readiness of the element composing the layer.
  91448. * @param subMesh the mesh to check for
  91449. * @param useInstances specify wether or not to use instances to render the mesh
  91450. * @param emissiveTexture the associated emissive texture used to generate the glow
  91451. * @return true if ready otherwise, false
  91452. */
  91453. EffectLayer.prototype._isReady = function (subMesh, useInstances, emissiveTexture) {
  91454. var material = subMesh.getMaterial();
  91455. if (!material) {
  91456. return false;
  91457. }
  91458. if (!material.isReady(subMesh.getMesh(), useInstances)) {
  91459. return false;
  91460. }
  91461. var defines = [];
  91462. var attribs = [BABYLON.VertexBuffer.PositionKind];
  91463. var mesh = subMesh.getMesh();
  91464. var uv1 = false;
  91465. var uv2 = false;
  91466. // Alpha test
  91467. if (material && material.needAlphaTesting()) {
  91468. var alphaTexture = material.getAlphaTestTexture();
  91469. if (alphaTexture) {
  91470. defines.push("#define ALPHATEST");
  91471. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind) &&
  91472. alphaTexture.coordinatesIndex === 1) {
  91473. defines.push("#define DIFFUSEUV2");
  91474. uv2 = true;
  91475. }
  91476. else if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  91477. defines.push("#define DIFFUSEUV1");
  91478. uv1 = true;
  91479. }
  91480. }
  91481. }
  91482. // Emissive
  91483. if (emissiveTexture) {
  91484. defines.push("#define EMISSIVE");
  91485. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind) &&
  91486. emissiveTexture.coordinatesIndex === 1) {
  91487. defines.push("#define EMISSIVEUV2");
  91488. uv2 = true;
  91489. }
  91490. else if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  91491. defines.push("#define EMISSIVEUV1");
  91492. uv1 = true;
  91493. }
  91494. }
  91495. if (uv1) {
  91496. attribs.push(BABYLON.VertexBuffer.UVKind);
  91497. defines.push("#define UV1");
  91498. }
  91499. if (uv2) {
  91500. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  91501. defines.push("#define UV2");
  91502. }
  91503. // Bones
  91504. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  91505. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  91506. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  91507. if (mesh.numBoneInfluencers > 4) {
  91508. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  91509. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  91510. }
  91511. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  91512. defines.push("#define BonesPerMesh " + (mesh.skeleton ? (mesh.skeleton.bones.length + 1) : 0));
  91513. }
  91514. else {
  91515. defines.push("#define NUM_BONE_INFLUENCERS 0");
  91516. }
  91517. // Morph targets
  91518. var manager = mesh.morphTargetManager;
  91519. var morphInfluencers = 0;
  91520. if (manager) {
  91521. if (manager.numInfluencers > 0) {
  91522. defines.push("#define MORPHTARGETS");
  91523. morphInfluencers = manager.numInfluencers;
  91524. defines.push("#define NUM_MORPH_INFLUENCERS " + morphInfluencers);
  91525. BABYLON.MaterialHelper.PrepareAttributesForMorphTargets(attribs, mesh, { "NUM_MORPH_INFLUENCERS": morphInfluencers });
  91526. }
  91527. }
  91528. // Instances
  91529. if (useInstances) {
  91530. defines.push("#define INSTANCES");
  91531. attribs.push("world0");
  91532. attribs.push("world1");
  91533. attribs.push("world2");
  91534. attribs.push("world3");
  91535. }
  91536. // Get correct effect
  91537. var join = defines.join("\n");
  91538. if (this._cachedDefines !== join) {
  91539. this._cachedDefines = join;
  91540. this._effectLayerMapGenerationEffect = this._scene.getEngine().createEffect("glowMapGeneration", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "color", "emissiveMatrix", "morphTargetInfluences"], ["diffuseSampler", "emissiveSampler"], join, undefined, undefined, undefined, { maxSimultaneousMorphTargets: morphInfluencers });
  91541. }
  91542. return this._effectLayerMapGenerationEffect.isReady();
  91543. };
  91544. /**
  91545. * Renders the glowing part of the scene by blending the blurred glowing meshes on top of the rendered scene.
  91546. */
  91547. EffectLayer.prototype.render = function () {
  91548. var currentEffect = this._mergeEffect;
  91549. // Check
  91550. if (!currentEffect.isReady())
  91551. return;
  91552. for (var i = 0; i < this._postProcesses.length; i++) {
  91553. if (!this._postProcesses[i].isReady()) {
  91554. return;
  91555. }
  91556. }
  91557. var engine = this._scene.getEngine();
  91558. this.onBeforeComposeObservable.notifyObservers(this);
  91559. // Render
  91560. engine.enableEffect(currentEffect);
  91561. engine.setState(false);
  91562. // VBOs
  91563. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, currentEffect);
  91564. // Cache
  91565. var previousAlphaMode = engine.getAlphaMode();
  91566. // Go Blend.
  91567. engine.setAlphaMode(this._effectLayerOptions.alphaBlendingMode);
  91568. // Blends the map on the main canvas.
  91569. this._internalRender(currentEffect);
  91570. // Restore Alpha
  91571. engine.setAlphaMode(previousAlphaMode);
  91572. this.onAfterComposeObservable.notifyObservers(this);
  91573. // Handle size changes.
  91574. var size = this._mainTexture.getSize();
  91575. this._setMainTextureSize();
  91576. if (size.width !== this._mainTextureDesiredSize.width || size.height !== this._mainTextureDesiredSize.height) {
  91577. // Recreate RTT and post processes on size change.
  91578. this.onSizeChangedObservable.notifyObservers(this);
  91579. this._disposeTextureAndPostProcesses();
  91580. this._createMainTexture();
  91581. this._createTextureAndPostProcesses();
  91582. }
  91583. };
  91584. /**
  91585. * Determine if a given mesh will be used in the current effect.
  91586. * @param mesh mesh to test
  91587. * @returns true if the mesh will be used
  91588. */
  91589. EffectLayer.prototype.hasMesh = function (mesh) {
  91590. return true;
  91591. };
  91592. /**
  91593. * Returns true if the layer contains information to display, otherwise false.
  91594. * @returns true if the glow layer should be rendered
  91595. */
  91596. EffectLayer.prototype.shouldRender = function () {
  91597. return this.isEnabled && this._shouldRender;
  91598. };
  91599. /**
  91600. * Returns true if the mesh should render, otherwise false.
  91601. * @param mesh The mesh to render
  91602. * @returns true if it should render otherwise false
  91603. */
  91604. EffectLayer.prototype._shouldRenderMesh = function (mesh) {
  91605. return true;
  91606. };
  91607. /**
  91608. * Returns true if the mesh should render, otherwise false.
  91609. * @param mesh The mesh to render
  91610. * @returns true if it should render otherwise false
  91611. */
  91612. EffectLayer.prototype._shouldRenderEmissiveTextureForMesh = function (mesh) {
  91613. return true;
  91614. };
  91615. /**
  91616. * Renders the submesh passed in parameter to the generation map.
  91617. */
  91618. EffectLayer.prototype._renderSubMesh = function (subMesh) {
  91619. var _this = this;
  91620. if (!this.shouldRender()) {
  91621. return;
  91622. }
  91623. var material = subMesh.getMaterial();
  91624. var mesh = subMesh.getRenderingMesh();
  91625. var scene = this._scene;
  91626. var engine = scene.getEngine();
  91627. if (!material) {
  91628. return;
  91629. }
  91630. // Do not block in blend mode.
  91631. if (material.needAlphaBlendingForMesh(mesh)) {
  91632. return;
  91633. }
  91634. // Culling
  91635. engine.setState(material.backFaceCulling);
  91636. // Managing instances
  91637. var batch = mesh._getInstancesRenderList(subMesh._id);
  91638. if (batch.mustReturn) {
  91639. return;
  91640. }
  91641. // Early Exit per mesh
  91642. if (!this._shouldRenderMesh(mesh)) {
  91643. return;
  91644. }
  91645. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  91646. this._setEmissiveTextureAndColor(mesh, subMesh, material);
  91647. if (this._isReady(subMesh, hardwareInstancedRendering, this._emissiveTextureAndColor.texture)) {
  91648. engine.enableEffect(this._effectLayerMapGenerationEffect);
  91649. mesh._bind(subMesh, this._effectLayerMapGenerationEffect, BABYLON.Material.TriangleFillMode);
  91650. this._effectLayerMapGenerationEffect.setMatrix("viewProjection", scene.getTransformMatrix());
  91651. this._effectLayerMapGenerationEffect.setFloat4("color", this._emissiveTextureAndColor.color.r, this._emissiveTextureAndColor.color.g, this._emissiveTextureAndColor.color.b, this._emissiveTextureAndColor.color.a);
  91652. // Alpha test
  91653. if (material && material.needAlphaTesting()) {
  91654. var alphaTexture = material.getAlphaTestTexture();
  91655. if (alphaTexture) {
  91656. this._effectLayerMapGenerationEffect.setTexture("diffuseSampler", alphaTexture);
  91657. var textureMatrix = alphaTexture.getTextureMatrix();
  91658. if (textureMatrix) {
  91659. this._effectLayerMapGenerationEffect.setMatrix("diffuseMatrix", textureMatrix);
  91660. }
  91661. }
  91662. }
  91663. // Glow emissive only
  91664. if (this._emissiveTextureAndColor.texture) {
  91665. this._effectLayerMapGenerationEffect.setTexture("emissiveSampler", this._emissiveTextureAndColor.texture);
  91666. this._effectLayerMapGenerationEffect.setMatrix("emissiveMatrix", this._emissiveTextureAndColor.texture.getTextureMatrix());
  91667. }
  91668. // Bones
  91669. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  91670. this._effectLayerMapGenerationEffect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  91671. }
  91672. // Morph targets
  91673. BABYLON.MaterialHelper.BindMorphTargetParameters(mesh, this._effectLayerMapGenerationEffect);
  91674. // Draw
  91675. mesh._processRendering(subMesh, this._effectLayerMapGenerationEffect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._effectLayerMapGenerationEffect.setMatrix("world", world); });
  91676. }
  91677. else {
  91678. // Need to reset refresh rate of the shadowMap
  91679. this._mainTexture.resetRefreshCounter();
  91680. }
  91681. };
  91682. /**
  91683. * Rebuild the required buffers.
  91684. * @hidden Internal use only.
  91685. */
  91686. EffectLayer.prototype._rebuild = function () {
  91687. var vb = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  91688. if (vb) {
  91689. vb._rebuild();
  91690. }
  91691. this._generateIndexBuffer();
  91692. };
  91693. /**
  91694. * Dispose only the render target textures and post process.
  91695. */
  91696. EffectLayer.prototype._disposeTextureAndPostProcesses = function () {
  91697. this._mainTexture.dispose();
  91698. for (var i = 0; i < this._postProcesses.length; i++) {
  91699. if (this._postProcesses[i]) {
  91700. this._postProcesses[i].dispose();
  91701. }
  91702. }
  91703. this._postProcesses = [];
  91704. for (var i = 0; i < this._textures.length; i++) {
  91705. if (this._textures[i]) {
  91706. this._textures[i].dispose();
  91707. }
  91708. }
  91709. this._textures = [];
  91710. };
  91711. /**
  91712. * Dispose the highlight layer and free resources.
  91713. */
  91714. EffectLayer.prototype.dispose = function () {
  91715. var vertexBuffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  91716. if (vertexBuffer) {
  91717. vertexBuffer.dispose();
  91718. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  91719. }
  91720. if (this._indexBuffer) {
  91721. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  91722. this._indexBuffer = null;
  91723. }
  91724. // Clean textures and post processes
  91725. this._disposeTextureAndPostProcesses();
  91726. // Remove from scene
  91727. var index = this._scene.effectLayers.indexOf(this, 0);
  91728. if (index > -1) {
  91729. this._scene.effectLayers.splice(index, 1);
  91730. }
  91731. // Callback
  91732. this.onDisposeObservable.notifyObservers(this);
  91733. this.onDisposeObservable.clear();
  91734. this.onBeforeRenderMainTextureObservable.clear();
  91735. this.onBeforeComposeObservable.clear();
  91736. this.onAfterComposeObservable.clear();
  91737. this.onSizeChangedObservable.clear();
  91738. };
  91739. /**
  91740. * Gets the class name of the effect layer
  91741. * @returns the string with the class name of the effect layer
  91742. */
  91743. EffectLayer.prototype.getClassName = function () {
  91744. return "EffectLayer";
  91745. };
  91746. /**
  91747. * Creates an effect layer from parsed effect layer data
  91748. * @param parsedEffectLayer defines effect layer data
  91749. * @param scene defines the current scene
  91750. * @param rootUrl defines the root URL containing the effect layer information
  91751. * @returns a parsed effect Layer
  91752. */
  91753. EffectLayer.Parse = function (parsedEffectLayer, scene, rootUrl) {
  91754. var effectLayerType = BABYLON.Tools.Instantiate(parsedEffectLayer.customType);
  91755. return effectLayerType.Parse(parsedEffectLayer, scene, rootUrl);
  91756. };
  91757. __decorate([
  91758. BABYLON.serialize()
  91759. ], EffectLayer.prototype, "name", void 0);
  91760. __decorate([
  91761. BABYLON.serializeAsColor4()
  91762. ], EffectLayer.prototype, "neutralColor", void 0);
  91763. __decorate([
  91764. BABYLON.serialize()
  91765. ], EffectLayer.prototype, "isEnabled", void 0);
  91766. __decorate([
  91767. BABYLON.serializeAsCameraReference()
  91768. ], EffectLayer.prototype, "camera", null);
  91769. return EffectLayer;
  91770. }());
  91771. BABYLON.EffectLayer = EffectLayer;
  91772. })(BABYLON || (BABYLON = {}));
  91773. //# sourceMappingURL=babylon.effectLayer.js.map
  91774. var BABYLON;
  91775. (function (BABYLON) {
  91776. /**
  91777. * Special Glow Blur post process only blurring the alpha channel
  91778. * It enforces keeping the most luminous color in the color channel.
  91779. */
  91780. var GlowBlurPostProcess = /** @class */ (function (_super) {
  91781. __extends(GlowBlurPostProcess, _super);
  91782. function GlowBlurPostProcess(name, direction, kernel, options, camera, samplingMode, engine, reusable) {
  91783. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  91784. var _this = _super.call(this, name, "glowBlurPostProcess", ["screenSize", "direction", "blurWidth"], null, options, camera, samplingMode, engine, reusable) || this;
  91785. _this.direction = direction;
  91786. _this.kernel = kernel;
  91787. _this.onApplyObservable.add(function (effect) {
  91788. effect.setFloat2("screenSize", _this.width, _this.height);
  91789. effect.setVector2("direction", _this.direction);
  91790. effect.setFloat("blurWidth", _this.kernel);
  91791. });
  91792. return _this;
  91793. }
  91794. return GlowBlurPostProcess;
  91795. }(BABYLON.PostProcess));
  91796. /**
  91797. * The highlight layer Helps adding a glow effect around a mesh.
  91798. *
  91799. * Once instantiated in a scene, simply use the pushMesh or removeMesh method to add or remove
  91800. * glowy meshes to your scene.
  91801. *
  91802. * !!! THIS REQUIRES AN ACTIVE STENCIL BUFFER ON THE CANVAS !!!
  91803. */
  91804. var HighlightLayer = /** @class */ (function (_super) {
  91805. __extends(HighlightLayer, _super);
  91806. /**
  91807. * Instantiates a new highlight Layer and references it to the scene..
  91808. * @param name The name of the layer
  91809. * @param scene The scene to use the layer in
  91810. * @param options Sets of none mandatory options to use with the layer (see IHighlightLayerOptions for more information)
  91811. */
  91812. function HighlightLayer(name, scene, options) {
  91813. var _this = _super.call(this, name, scene) || this;
  91814. _this.name = name;
  91815. /**
  91816. * Specifies whether or not the inner glow is ACTIVE in the layer.
  91817. */
  91818. _this.innerGlow = true;
  91819. /**
  91820. * Specifies whether or not the outer glow is ACTIVE in the layer.
  91821. */
  91822. _this.outerGlow = true;
  91823. /**
  91824. * An event triggered when the highlight layer is being blurred.
  91825. */
  91826. _this.onBeforeBlurObservable = new BABYLON.Observable();
  91827. /**
  91828. * An event triggered when the highlight layer has been blurred.
  91829. */
  91830. _this.onAfterBlurObservable = new BABYLON.Observable();
  91831. _this._instanceGlowingMeshStencilReference = HighlightLayer.GlowingMeshStencilReference++;
  91832. _this._meshes = {};
  91833. _this._excludedMeshes = {};
  91834. _this.neutralColor = HighlightLayer.NeutralColor;
  91835. // Warn on stencil
  91836. if (!_this._engine.isStencilEnable) {
  91837. 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 }");
  91838. }
  91839. // Adapt options
  91840. _this._options = __assign({ mainTextureRatio: 0.5, blurTextureSizeRatio: 0.5, blurHorizontalSize: 1.0, blurVerticalSize: 1.0, alphaBlendingMode: BABYLON.Engine.ALPHA_COMBINE, camera: null }, options);
  91841. // Initialize the layer
  91842. _this._init({
  91843. alphaBlendingMode: _this._options.alphaBlendingMode,
  91844. camera: _this._options.camera,
  91845. mainTextureFixedSize: _this._options.mainTextureFixedSize,
  91846. mainTextureRatio: _this._options.mainTextureRatio
  91847. });
  91848. // Do not render as long as no meshes have been added
  91849. _this._shouldRender = false;
  91850. return _this;
  91851. }
  91852. Object.defineProperty(HighlightLayer.prototype, "blurHorizontalSize", {
  91853. /**
  91854. * Gets the horizontal size of the blur.
  91855. */
  91856. get: function () {
  91857. return this._horizontalBlurPostprocess.kernel;
  91858. },
  91859. /**
  91860. * Specifies the horizontal size of the blur.
  91861. */
  91862. set: function (value) {
  91863. this._horizontalBlurPostprocess.kernel = value;
  91864. },
  91865. enumerable: true,
  91866. configurable: true
  91867. });
  91868. Object.defineProperty(HighlightLayer.prototype, "blurVerticalSize", {
  91869. /**
  91870. * Gets the vertical size of the blur.
  91871. */
  91872. get: function () {
  91873. return this._verticalBlurPostprocess.kernel;
  91874. },
  91875. /**
  91876. * Specifies the vertical size of the blur.
  91877. */
  91878. set: function (value) {
  91879. this._verticalBlurPostprocess.kernel = value;
  91880. },
  91881. enumerable: true,
  91882. configurable: true
  91883. });
  91884. /**
  91885. * Get the effect name of the layer.
  91886. * @return The effect name
  91887. */
  91888. HighlightLayer.prototype.getEffectName = function () {
  91889. return HighlightLayer.EffectName;
  91890. };
  91891. /**
  91892. * Create the merge effect. This is the shader use to blit the information back
  91893. * to the main canvas at the end of the scene rendering.
  91894. */
  91895. HighlightLayer.prototype._createMergeEffect = function () {
  91896. // Effect
  91897. return this._engine.createEffect("glowMapMerge", [BABYLON.VertexBuffer.PositionKind], ["offset"], ["textureSampler"], this._options.isStroke ? "#define STROKE \n" : undefined);
  91898. };
  91899. /**
  91900. * Creates the render target textures and post processes used in the highlight layer.
  91901. */
  91902. HighlightLayer.prototype._createTextureAndPostProcesses = function () {
  91903. var _this = this;
  91904. var blurTextureWidth = this._mainTextureDesiredSize.width * this._options.blurTextureSizeRatio;
  91905. var blurTextureHeight = this._mainTextureDesiredSize.height * this._options.blurTextureSizeRatio;
  91906. blurTextureWidth = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(blurTextureWidth, this._maxSize) : blurTextureWidth;
  91907. blurTextureHeight = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(blurTextureHeight, this._maxSize) : blurTextureHeight;
  91908. this._blurTexture = new BABYLON.RenderTargetTexture("HighlightLayerBlurRTT", {
  91909. width: blurTextureWidth,
  91910. height: blurTextureHeight
  91911. }, this._scene, false, true, BABYLON.Engine.TEXTURETYPE_HALF_FLOAT);
  91912. this._blurTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  91913. this._blurTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  91914. this._blurTexture.anisotropicFilteringLevel = 16;
  91915. this._blurTexture.updateSamplingMode(BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  91916. this._blurTexture.renderParticles = false;
  91917. this._blurTexture.ignoreCameraViewport = true;
  91918. this._textures = [this._blurTexture];
  91919. if (this._options.alphaBlendingMode === BABYLON.Engine.ALPHA_COMBINE) {
  91920. this._downSamplePostprocess = new BABYLON.PassPostProcess("HighlightLayerPPP", this._options.blurTextureSizeRatio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine());
  91921. this._downSamplePostprocess.onApplyObservable.add(function (effect) {
  91922. effect.setTexture("textureSampler", _this._mainTexture);
  91923. });
  91924. this._horizontalBlurPostprocess = new GlowBlurPostProcess("HighlightLayerHBP", new BABYLON.Vector2(1.0, 0), this._options.blurHorizontalSize, 1, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine());
  91925. this._horizontalBlurPostprocess.onApplyObservable.add(function (effect) {
  91926. effect.setFloat2("screenSize", blurTextureWidth, blurTextureHeight);
  91927. });
  91928. this._verticalBlurPostprocess = new GlowBlurPostProcess("HighlightLayerVBP", new BABYLON.Vector2(0, 1.0), this._options.blurVerticalSize, 1, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine());
  91929. this._verticalBlurPostprocess.onApplyObservable.add(function (effect) {
  91930. effect.setFloat2("screenSize", blurTextureWidth, blurTextureHeight);
  91931. });
  91932. this._postProcesses = [this._downSamplePostprocess, this._horizontalBlurPostprocess, this._verticalBlurPostprocess];
  91933. }
  91934. else {
  91935. this._horizontalBlurPostprocess = new BABYLON.BlurPostProcess("HighlightLayerHBP", new BABYLON.Vector2(1.0, 0), this._options.blurHorizontalSize / 2, {
  91936. width: blurTextureWidth,
  91937. height: blurTextureHeight
  91938. }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, BABYLON.Engine.TEXTURETYPE_HALF_FLOAT);
  91939. this._horizontalBlurPostprocess.width = blurTextureWidth;
  91940. this._horizontalBlurPostprocess.height = blurTextureHeight;
  91941. this._horizontalBlurPostprocess.onApplyObservable.add(function (effect) {
  91942. effect.setTexture("textureSampler", _this._mainTexture);
  91943. });
  91944. this._verticalBlurPostprocess = new BABYLON.BlurPostProcess("HighlightLayerVBP", new BABYLON.Vector2(0, 1.0), this._options.blurVerticalSize / 2, {
  91945. width: blurTextureWidth,
  91946. height: blurTextureHeight
  91947. }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, BABYLON.Engine.TEXTURETYPE_HALF_FLOAT);
  91948. this._postProcesses = [this._horizontalBlurPostprocess, this._verticalBlurPostprocess];
  91949. }
  91950. this._mainTexture.onAfterUnbindObservable.add(function () {
  91951. _this.onBeforeBlurObservable.notifyObservers(_this);
  91952. var internalTexture = _this._blurTexture.getInternalTexture();
  91953. if (internalTexture) {
  91954. _this._scene.postProcessManager.directRender(_this._postProcesses, internalTexture, true);
  91955. }
  91956. _this.onAfterBlurObservable.notifyObservers(_this);
  91957. });
  91958. // Prevent autoClear.
  91959. this._postProcesses.map(function (pp) { pp.autoClear = false; });
  91960. };
  91961. /**
  91962. * Returns wether or nood the layer needs stencil enabled during the mesh rendering.
  91963. */
  91964. HighlightLayer.prototype.needStencil = function () {
  91965. return true;
  91966. };
  91967. /**
  91968. * Checks for the readiness of the element composing the layer.
  91969. * @param subMesh the mesh to check for
  91970. * @param useInstances specify wether or not to use instances to render the mesh
  91971. * @param emissiveTexture the associated emissive texture used to generate the glow
  91972. * @return true if ready otherwise, false
  91973. */
  91974. HighlightLayer.prototype.isReady = function (subMesh, useInstances) {
  91975. var material = subMesh.getMaterial();
  91976. var mesh = subMesh.getRenderingMesh();
  91977. if (!material || !mesh || !this._meshes) {
  91978. return false;
  91979. }
  91980. var emissiveTexture = null;
  91981. var highlightLayerMesh = this._meshes[mesh.uniqueId];
  91982. if (highlightLayerMesh && highlightLayerMesh.glowEmissiveOnly && material) {
  91983. emissiveTexture = material.emissiveTexture;
  91984. }
  91985. return _super.prototype._isReady.call(this, subMesh, useInstances, emissiveTexture);
  91986. };
  91987. /**
  91988. * Implementation specific of rendering the generating effect on the main canvas.
  91989. * @param effect The effect used to render through
  91990. */
  91991. HighlightLayer.prototype._internalRender = function (effect) {
  91992. // Texture
  91993. effect.setTexture("textureSampler", this._blurTexture);
  91994. // Cache
  91995. var engine = this._engine;
  91996. var previousStencilBuffer = engine.getStencilBuffer();
  91997. var previousStencilFunction = engine.getStencilFunction();
  91998. var previousStencilMask = engine.getStencilMask();
  91999. var previousStencilOperationPass = engine.getStencilOperationPass();
  92000. var previousStencilOperationFail = engine.getStencilOperationFail();
  92001. var previousStencilOperationDepthFail = engine.getStencilOperationDepthFail();
  92002. var previousStencilReference = engine.getStencilFunctionReference();
  92003. // Stencil operations
  92004. engine.setStencilOperationPass(BABYLON.Engine.REPLACE);
  92005. engine.setStencilOperationFail(BABYLON.Engine.KEEP);
  92006. engine.setStencilOperationDepthFail(BABYLON.Engine.KEEP);
  92007. // Draw order
  92008. engine.setStencilMask(0x00);
  92009. engine.setStencilBuffer(true);
  92010. engine.setStencilFunctionReference(this._instanceGlowingMeshStencilReference);
  92011. // 2 passes inner outer
  92012. if (this.outerGlow) {
  92013. effect.setFloat("offset", 0);
  92014. engine.setStencilFunction(BABYLON.Engine.NOTEQUAL);
  92015. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  92016. }
  92017. if (this.innerGlow) {
  92018. effect.setFloat("offset", 1);
  92019. engine.setStencilFunction(BABYLON.Engine.EQUAL);
  92020. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  92021. }
  92022. // Restore Cache
  92023. engine.setStencilFunction(previousStencilFunction);
  92024. engine.setStencilMask(previousStencilMask);
  92025. engine.setStencilBuffer(previousStencilBuffer);
  92026. engine.setStencilOperationPass(previousStencilOperationPass);
  92027. engine.setStencilOperationFail(previousStencilOperationFail);
  92028. engine.setStencilOperationDepthFail(previousStencilOperationDepthFail);
  92029. engine.setStencilFunctionReference(previousStencilReference);
  92030. };
  92031. /**
  92032. * Returns true if the layer contains information to display, otherwise false.
  92033. */
  92034. HighlightLayer.prototype.shouldRender = function () {
  92035. if (_super.prototype.shouldRender.call(this)) {
  92036. return this._meshes ? true : false;
  92037. }
  92038. return false;
  92039. };
  92040. /**
  92041. * Returns true if the mesh should render, otherwise false.
  92042. * @param mesh The mesh to render
  92043. * @returns true if it should render otherwise false
  92044. */
  92045. HighlightLayer.prototype._shouldRenderMesh = function (mesh) {
  92046. // Excluded Mesh
  92047. if (this._excludedMeshes && this._excludedMeshes[mesh.uniqueId]) {
  92048. return false;
  92049. }
  92050. ;
  92051. return true;
  92052. };
  92053. /**
  92054. * Sets the required values for both the emissive texture and and the main color.
  92055. */
  92056. HighlightLayer.prototype._setEmissiveTextureAndColor = function (mesh, subMesh, material) {
  92057. var highlightLayerMesh = this._meshes[mesh.uniqueId];
  92058. if (highlightLayerMesh) {
  92059. this._emissiveTextureAndColor.color.set(highlightLayerMesh.color.r, highlightLayerMesh.color.g, highlightLayerMesh.color.b, 1.0);
  92060. }
  92061. else {
  92062. this._emissiveTextureAndColor.color.set(this.neutralColor.r, this.neutralColor.g, this.neutralColor.b, this.neutralColor.a);
  92063. }
  92064. if (highlightLayerMesh && highlightLayerMesh.glowEmissiveOnly && material) {
  92065. this._emissiveTextureAndColor.texture = material.emissiveTexture;
  92066. this._emissiveTextureAndColor.color.set(1.0, 1.0, 1.0, 1.0);
  92067. }
  92068. else {
  92069. this._emissiveTextureAndColor.texture = null;
  92070. }
  92071. };
  92072. /**
  92073. * Add a mesh in the exclusion list to prevent it to impact or being impacted by the highlight layer.
  92074. * @param mesh The mesh to exclude from the highlight layer
  92075. */
  92076. HighlightLayer.prototype.addExcludedMesh = function (mesh) {
  92077. if (!this._excludedMeshes) {
  92078. return;
  92079. }
  92080. var meshExcluded = this._excludedMeshes[mesh.uniqueId];
  92081. if (!meshExcluded) {
  92082. this._excludedMeshes[mesh.uniqueId] = {
  92083. mesh: mesh,
  92084. beforeRender: mesh.onBeforeRenderObservable.add(function (mesh) {
  92085. mesh.getEngine().setStencilBuffer(false);
  92086. }),
  92087. afterRender: mesh.onAfterRenderObservable.add(function (mesh) {
  92088. mesh.getEngine().setStencilBuffer(true);
  92089. }),
  92090. };
  92091. }
  92092. };
  92093. /**
  92094. * Remove a mesh from the exclusion list to let it impact or being impacted by the highlight layer.
  92095. * @param mesh The mesh to highlight
  92096. */
  92097. HighlightLayer.prototype.removeExcludedMesh = function (mesh) {
  92098. if (!this._excludedMeshes) {
  92099. return;
  92100. }
  92101. var meshExcluded = this._excludedMeshes[mesh.uniqueId];
  92102. if (meshExcluded) {
  92103. if (meshExcluded.beforeRender) {
  92104. mesh.onBeforeRenderObservable.remove(meshExcluded.beforeRender);
  92105. }
  92106. if (meshExcluded.afterRender) {
  92107. mesh.onAfterRenderObservable.remove(meshExcluded.afterRender);
  92108. }
  92109. }
  92110. this._excludedMeshes[mesh.uniqueId] = null;
  92111. };
  92112. /**
  92113. * Determine if a given mesh will be highlighted by the current HighlightLayer
  92114. * @param mesh mesh to test
  92115. * @returns true if the mesh will be highlighted by the current HighlightLayer
  92116. */
  92117. HighlightLayer.prototype.hasMesh = function (mesh) {
  92118. if (!this._meshes) {
  92119. return false;
  92120. }
  92121. return this._meshes[mesh.uniqueId] !== undefined && this._meshes[mesh.uniqueId] !== null;
  92122. };
  92123. /**
  92124. * Add a mesh in the highlight layer in order to make it glow with the chosen color.
  92125. * @param mesh The mesh to highlight
  92126. * @param color The color of the highlight
  92127. * @param glowEmissiveOnly Extract the glow from the emissive texture
  92128. */
  92129. HighlightLayer.prototype.addMesh = function (mesh, color, glowEmissiveOnly) {
  92130. var _this = this;
  92131. if (glowEmissiveOnly === void 0) { glowEmissiveOnly = false; }
  92132. if (!this._meshes) {
  92133. return;
  92134. }
  92135. var meshHighlight = this._meshes[mesh.uniqueId];
  92136. if (meshHighlight) {
  92137. meshHighlight.color = color;
  92138. }
  92139. else {
  92140. this._meshes[mesh.uniqueId] = {
  92141. mesh: mesh,
  92142. color: color,
  92143. // Lambda required for capture due to Observable this context
  92144. observerHighlight: mesh.onBeforeRenderObservable.add(function (mesh) {
  92145. if (_this._excludedMeshes && _this._excludedMeshes[mesh.uniqueId]) {
  92146. _this._defaultStencilReference(mesh);
  92147. }
  92148. else {
  92149. mesh.getScene().getEngine().setStencilFunctionReference(_this._instanceGlowingMeshStencilReference);
  92150. }
  92151. }),
  92152. observerDefault: mesh.onAfterRenderObservable.add(this._defaultStencilReference),
  92153. glowEmissiveOnly: glowEmissiveOnly
  92154. };
  92155. }
  92156. this._shouldRender = true;
  92157. };
  92158. /**
  92159. * Remove a mesh from the highlight layer in order to make it stop glowing.
  92160. * @param mesh The mesh to highlight
  92161. */
  92162. HighlightLayer.prototype.removeMesh = function (mesh) {
  92163. if (!this._meshes) {
  92164. return;
  92165. }
  92166. var meshHighlight = this._meshes[mesh.uniqueId];
  92167. if (meshHighlight) {
  92168. if (meshHighlight.observerHighlight) {
  92169. mesh.onBeforeRenderObservable.remove(meshHighlight.observerHighlight);
  92170. }
  92171. if (meshHighlight.observerDefault) {
  92172. mesh.onAfterRenderObservable.remove(meshHighlight.observerDefault);
  92173. }
  92174. delete this._meshes[mesh.uniqueId];
  92175. }
  92176. this._shouldRender = false;
  92177. for (var meshHighlightToCheck in this._meshes) {
  92178. if (this._meshes[meshHighlightToCheck]) {
  92179. this._shouldRender = true;
  92180. break;
  92181. }
  92182. }
  92183. };
  92184. /**
  92185. * Force the stencil to the normal expected value for none glowing parts
  92186. */
  92187. HighlightLayer.prototype._defaultStencilReference = function (mesh) {
  92188. mesh.getScene().getEngine().setStencilFunctionReference(HighlightLayer.NormalMeshStencilReference);
  92189. };
  92190. /**
  92191. * Free any resources and references associated to a mesh.
  92192. * Internal use
  92193. * @param mesh The mesh to free.
  92194. */
  92195. HighlightLayer.prototype._disposeMesh = function (mesh) {
  92196. this.removeMesh(mesh);
  92197. this.removeExcludedMesh(mesh);
  92198. };
  92199. /**
  92200. * Dispose the highlight layer and free resources.
  92201. */
  92202. HighlightLayer.prototype.dispose = function () {
  92203. if (this._meshes) {
  92204. // Clean mesh references
  92205. for (var id in this._meshes) {
  92206. var meshHighlight = this._meshes[id];
  92207. if (meshHighlight && meshHighlight.mesh) {
  92208. if (meshHighlight.observerHighlight) {
  92209. meshHighlight.mesh.onBeforeRenderObservable.remove(meshHighlight.observerHighlight);
  92210. }
  92211. if (meshHighlight.observerDefault) {
  92212. meshHighlight.mesh.onAfterRenderObservable.remove(meshHighlight.observerDefault);
  92213. }
  92214. }
  92215. }
  92216. this._meshes = null;
  92217. }
  92218. if (this._excludedMeshes) {
  92219. for (var id in this._excludedMeshes) {
  92220. var meshHighlight = this._excludedMeshes[id];
  92221. if (meshHighlight) {
  92222. if (meshHighlight.beforeRender) {
  92223. meshHighlight.mesh.onBeforeRenderObservable.remove(meshHighlight.beforeRender);
  92224. }
  92225. if (meshHighlight.afterRender) {
  92226. meshHighlight.mesh.onAfterRenderObservable.remove(meshHighlight.afterRender);
  92227. }
  92228. }
  92229. }
  92230. this._excludedMeshes = null;
  92231. }
  92232. _super.prototype.dispose.call(this);
  92233. };
  92234. /**
  92235. * Gets the class name of the effect layer
  92236. * @returns the string with the class name of the effect layer
  92237. */
  92238. HighlightLayer.prototype.getClassName = function () {
  92239. return "HighlightLayer";
  92240. };
  92241. /**
  92242. * Serializes this Highlight layer
  92243. * @returns a serialized Highlight layer object
  92244. */
  92245. HighlightLayer.prototype.serialize = function () {
  92246. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  92247. serializationObject.customType = "BABYLON.HighlightLayer";
  92248. // Highlighted meshes
  92249. serializationObject.meshes = [];
  92250. if (this._meshes) {
  92251. for (var m in this._meshes) {
  92252. var mesh = this._meshes[m];
  92253. if (mesh) {
  92254. serializationObject.meshes.push({
  92255. glowEmissiveOnly: mesh.glowEmissiveOnly,
  92256. color: mesh.color.asArray(),
  92257. meshId: mesh.mesh.id
  92258. });
  92259. }
  92260. }
  92261. }
  92262. // Excluded meshes
  92263. serializationObject.excludedMeshes = [];
  92264. if (this._excludedMeshes) {
  92265. for (var e in this._excludedMeshes) {
  92266. var excludedMesh = this._excludedMeshes[e];
  92267. if (excludedMesh) {
  92268. serializationObject.excludedMeshes.push(excludedMesh.mesh.id);
  92269. }
  92270. }
  92271. }
  92272. return serializationObject;
  92273. };
  92274. /**
  92275. * Creates a Highlight layer from parsed Highlight layer data
  92276. * @param parsedHightlightLayer defines the Highlight layer data
  92277. * @param scene defines the current scene
  92278. * @param rootUrl defines the root URL containing the Highlight layer information
  92279. * @returns a parsed Highlight layer
  92280. */
  92281. HighlightLayer.Parse = function (parsedHightlightLayer, scene, rootUrl) {
  92282. var hl = BABYLON.SerializationHelper.Parse(function () { return new HighlightLayer(parsedHightlightLayer.name, scene, parsedHightlightLayer.options); }, parsedHightlightLayer, scene, rootUrl);
  92283. var index;
  92284. // Excluded meshes
  92285. for (index = 0; index < parsedHightlightLayer.excludedMeshes.length; index++) {
  92286. var mesh = scene.getMeshByID(parsedHightlightLayer.excludedMeshes[index]);
  92287. if (mesh) {
  92288. hl.addExcludedMesh(mesh);
  92289. }
  92290. }
  92291. // Included meshes
  92292. for (index = 0; index < parsedHightlightLayer.meshes.length; index++) {
  92293. var highlightedMesh = parsedHightlightLayer.meshes[index];
  92294. var mesh = scene.getMeshByID(highlightedMesh.meshId);
  92295. if (mesh) {
  92296. hl.addMesh(mesh, BABYLON.Color3.FromArray(highlightedMesh.color), highlightedMesh.glowEmissiveOnly);
  92297. }
  92298. }
  92299. return hl;
  92300. };
  92301. /**
  92302. * Effect Name of the highlight layer.
  92303. */
  92304. HighlightLayer.EffectName = "HighlightLayer";
  92305. /**
  92306. * The neutral color used during the preparation of the glow effect.
  92307. * This is black by default as the blend operation is a blend operation.
  92308. */
  92309. HighlightLayer.NeutralColor = new BABYLON.Color4(0, 0, 0, 0);
  92310. /**
  92311. * Stencil value used for glowing meshes.
  92312. */
  92313. HighlightLayer.GlowingMeshStencilReference = 0x02;
  92314. /**
  92315. * Stencil value used for the other meshes in the scene.
  92316. */
  92317. HighlightLayer.NormalMeshStencilReference = 0x01;
  92318. __decorate([
  92319. BABYLON.serialize()
  92320. ], HighlightLayer.prototype, "innerGlow", void 0);
  92321. __decorate([
  92322. BABYLON.serialize()
  92323. ], HighlightLayer.prototype, "outerGlow", void 0);
  92324. __decorate([
  92325. BABYLON.serialize()
  92326. ], HighlightLayer.prototype, "blurHorizontalSize", null);
  92327. __decorate([
  92328. BABYLON.serialize()
  92329. ], HighlightLayer.prototype, "blurVerticalSize", null);
  92330. __decorate([
  92331. BABYLON.serialize("options")
  92332. ], HighlightLayer.prototype, "_options", void 0);
  92333. return HighlightLayer;
  92334. }(BABYLON.EffectLayer));
  92335. BABYLON.HighlightLayer = HighlightLayer;
  92336. })(BABYLON || (BABYLON = {}));
  92337. //# sourceMappingURL=babylon.highlightLayer.js.map
  92338. var BABYLON;
  92339. (function (BABYLON) {
  92340. /**
  92341. * The glow layer Helps adding a glow effect around the emissive parts of a mesh.
  92342. *
  92343. * Once instantiated in a scene, simply use the pushMesh or removeMesh method to add or remove
  92344. * glowy meshes to your scene.
  92345. *
  92346. * Documentation: https://doc.babylonjs.com/how_to/glow_layer
  92347. */
  92348. var GlowLayer = /** @class */ (function (_super) {
  92349. __extends(GlowLayer, _super);
  92350. /**
  92351. * Instantiates a new glow Layer and references it to the scene.
  92352. * @param name The name of the layer
  92353. * @param scene The scene to use the layer in
  92354. * @param options Sets of none mandatory options to use with the layer (see IGlowLayerOptions for more information)
  92355. */
  92356. function GlowLayer(name, scene, options) {
  92357. var _this = _super.call(this, name, scene) || this;
  92358. _this._intensity = 1.0;
  92359. _this._includedOnlyMeshes = [];
  92360. _this._excludedMeshes = [];
  92361. _this.neutralColor = new BABYLON.Color4(0, 0, 0, 1);
  92362. // Adapt options
  92363. _this._options = __assign({ mainTextureRatio: GlowLayer.DefaultTextureRatio, blurKernelSize: 32, mainTextureFixedSize: undefined, camera: null, mainTextureSamples: 1 }, options);
  92364. // Initialize the layer
  92365. _this._init({
  92366. alphaBlendingMode: BABYLON.Engine.ALPHA_ADD,
  92367. camera: _this._options.camera,
  92368. mainTextureFixedSize: _this._options.mainTextureFixedSize,
  92369. mainTextureRatio: _this._options.mainTextureRatio
  92370. });
  92371. return _this;
  92372. }
  92373. Object.defineProperty(GlowLayer.prototype, "blurKernelSize", {
  92374. /**
  92375. * Gets the kernel size of the blur.
  92376. */
  92377. get: function () {
  92378. return this._horizontalBlurPostprocess1.kernel;
  92379. },
  92380. /**
  92381. * Sets the kernel size of the blur.
  92382. */
  92383. set: function (value) {
  92384. this._horizontalBlurPostprocess1.kernel = value;
  92385. this._verticalBlurPostprocess1.kernel = value;
  92386. this._horizontalBlurPostprocess2.kernel = value;
  92387. this._verticalBlurPostprocess2.kernel = value;
  92388. },
  92389. enumerable: true,
  92390. configurable: true
  92391. });
  92392. Object.defineProperty(GlowLayer.prototype, "intensity", {
  92393. /**
  92394. * Gets the glow intensity.
  92395. */
  92396. get: function () {
  92397. return this._intensity;
  92398. },
  92399. /**
  92400. * Sets the glow intensity.
  92401. */
  92402. set: function (value) {
  92403. this._intensity = value;
  92404. },
  92405. enumerable: true,
  92406. configurable: true
  92407. });
  92408. /**
  92409. * Get the effect name of the layer.
  92410. * @return The effect name
  92411. */
  92412. GlowLayer.prototype.getEffectName = function () {
  92413. return GlowLayer.EffectName;
  92414. };
  92415. /**
  92416. * Create the merge effect. This is the shader use to blit the information back
  92417. * to the main canvas at the end of the scene rendering.
  92418. */
  92419. GlowLayer.prototype._createMergeEffect = function () {
  92420. // Effect
  92421. return this._engine.createEffect("glowMapMerge", [BABYLON.VertexBuffer.PositionKind], ["offset"], ["textureSampler", "textureSampler2"], "#define EMISSIVE \n");
  92422. };
  92423. /**
  92424. * Creates the render target textures and post processes used in the glow layer.
  92425. */
  92426. GlowLayer.prototype._createTextureAndPostProcesses = function () {
  92427. var _this = this;
  92428. var blurTextureWidth = this._mainTextureDesiredSize.width;
  92429. var blurTextureHeight = this._mainTextureDesiredSize.height;
  92430. blurTextureWidth = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(blurTextureWidth, this._maxSize) : blurTextureWidth;
  92431. blurTextureHeight = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(blurTextureHeight, this._maxSize) : blurTextureHeight;
  92432. var textureType = 0;
  92433. if (this._engine.getCaps().textureHalfFloatRender) {
  92434. textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  92435. }
  92436. else {
  92437. textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  92438. }
  92439. this._blurTexture1 = new BABYLON.RenderTargetTexture("GlowLayerBlurRTT", {
  92440. width: blurTextureWidth,
  92441. height: blurTextureHeight
  92442. }, this._scene, false, true, textureType);
  92443. this._blurTexture1.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  92444. this._blurTexture1.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  92445. this._blurTexture1.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  92446. this._blurTexture1.renderParticles = false;
  92447. this._blurTexture1.ignoreCameraViewport = true;
  92448. var blurTextureWidth2 = Math.floor(blurTextureWidth / 2);
  92449. var blurTextureHeight2 = Math.floor(blurTextureHeight / 2);
  92450. this._blurTexture2 = new BABYLON.RenderTargetTexture("GlowLayerBlurRTT2", {
  92451. width: blurTextureWidth2,
  92452. height: blurTextureHeight2
  92453. }, this._scene, false, true, textureType);
  92454. this._blurTexture2.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  92455. this._blurTexture2.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  92456. this._blurTexture2.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  92457. this._blurTexture2.renderParticles = false;
  92458. this._blurTexture2.ignoreCameraViewport = true;
  92459. this._textures = [this._blurTexture1, this._blurTexture2];
  92460. this._horizontalBlurPostprocess1 = new BABYLON.BlurPostProcess("GlowLayerHBP1", new BABYLON.Vector2(1.0, 0), this._options.blurKernelSize / 2, {
  92461. width: blurTextureWidth,
  92462. height: blurTextureHeight
  92463. }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, textureType);
  92464. this._horizontalBlurPostprocess1.width = blurTextureWidth;
  92465. this._horizontalBlurPostprocess1.height = blurTextureHeight;
  92466. this._horizontalBlurPostprocess1.onApplyObservable.add(function (effect) {
  92467. effect.setTexture("textureSampler", _this._mainTexture);
  92468. });
  92469. this._verticalBlurPostprocess1 = new BABYLON.BlurPostProcess("GlowLayerVBP1", new BABYLON.Vector2(0, 1.0), this._options.blurKernelSize / 2, {
  92470. width: blurTextureWidth,
  92471. height: blurTextureHeight
  92472. }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, textureType);
  92473. this._horizontalBlurPostprocess2 = new BABYLON.BlurPostProcess("GlowLayerHBP2", new BABYLON.Vector2(1.0, 0), this._options.blurKernelSize / 2, {
  92474. width: blurTextureWidth2,
  92475. height: blurTextureHeight2
  92476. }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, textureType);
  92477. this._horizontalBlurPostprocess2.width = blurTextureWidth2;
  92478. this._horizontalBlurPostprocess2.height = blurTextureHeight2;
  92479. this._horizontalBlurPostprocess2.onApplyObservable.add(function (effect) {
  92480. effect.setTexture("textureSampler", _this._blurTexture1);
  92481. });
  92482. this._verticalBlurPostprocess2 = new BABYLON.BlurPostProcess("GlowLayerVBP2", new BABYLON.Vector2(0, 1.0), this._options.blurKernelSize / 2, {
  92483. width: blurTextureWidth2,
  92484. height: blurTextureHeight2
  92485. }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, textureType);
  92486. this._postProcesses = [this._horizontalBlurPostprocess1, this._verticalBlurPostprocess1, this._horizontalBlurPostprocess2, this._verticalBlurPostprocess2];
  92487. this._postProcesses1 = [this._horizontalBlurPostprocess1, this._verticalBlurPostprocess1];
  92488. this._postProcesses2 = [this._horizontalBlurPostprocess2, this._verticalBlurPostprocess2];
  92489. this._mainTexture.samples = this._options.mainTextureSamples;
  92490. this._mainTexture.onAfterUnbindObservable.add(function () {
  92491. var internalTexture = _this._blurTexture1.getInternalTexture();
  92492. if (internalTexture) {
  92493. _this._scene.postProcessManager.directRender(_this._postProcesses1, internalTexture, true);
  92494. internalTexture = _this._blurTexture2.getInternalTexture();
  92495. if (internalTexture) {
  92496. _this._scene.postProcessManager.directRender(_this._postProcesses2, internalTexture, true);
  92497. }
  92498. }
  92499. });
  92500. // Prevent autoClear.
  92501. this._postProcesses.map(function (pp) { pp.autoClear = false; });
  92502. };
  92503. /**
  92504. * Checks for the readiness of the element composing the layer.
  92505. * @param subMesh the mesh to check for
  92506. * @param useInstances specify wether or not to use instances to render the mesh
  92507. * @param emissiveTexture the associated emissive texture used to generate the glow
  92508. * @return true if ready otherwise, false
  92509. */
  92510. GlowLayer.prototype.isReady = function (subMesh, useInstances) {
  92511. var material = subMesh.getMaterial();
  92512. var mesh = subMesh.getRenderingMesh();
  92513. if (!material || !mesh) {
  92514. return false;
  92515. }
  92516. var emissiveTexture = material.emissiveTexture;
  92517. return _super.prototype._isReady.call(this, subMesh, useInstances, emissiveTexture);
  92518. };
  92519. /**
  92520. * Returns wether or nood the layer needs stencil enabled during the mesh rendering.
  92521. */
  92522. GlowLayer.prototype.needStencil = function () {
  92523. return false;
  92524. };
  92525. /**
  92526. * Implementation specific of rendering the generating effect on the main canvas.
  92527. * @param effect The effect used to render through
  92528. */
  92529. GlowLayer.prototype._internalRender = function (effect) {
  92530. // Texture
  92531. effect.setTexture("textureSampler", this._blurTexture1);
  92532. effect.setTexture("textureSampler2", this._blurTexture2);
  92533. effect.setFloat("offset", this._intensity);
  92534. // Cache
  92535. var engine = this._engine;
  92536. var previousStencilBuffer = engine.getStencilBuffer();
  92537. // Draw order
  92538. engine.setStencilBuffer(false);
  92539. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  92540. // Draw order
  92541. engine.setStencilBuffer(previousStencilBuffer);
  92542. };
  92543. /**
  92544. * Sets the required values for both the emissive texture and and the main color.
  92545. */
  92546. GlowLayer.prototype._setEmissiveTextureAndColor = function (mesh, subMesh, material) {
  92547. var textureLevel = 1.0;
  92548. if (this.customEmissiveTextureSelector) {
  92549. this._emissiveTextureAndColor.texture = this.customEmissiveTextureSelector(mesh, subMesh, material);
  92550. }
  92551. else {
  92552. if (material) {
  92553. this._emissiveTextureAndColor.texture = material.emissiveTexture;
  92554. if (this._emissiveTextureAndColor.texture) {
  92555. textureLevel = this._emissiveTextureAndColor.texture.level;
  92556. }
  92557. }
  92558. else {
  92559. this._emissiveTextureAndColor.texture = null;
  92560. }
  92561. }
  92562. if (this.customEmissiveColorSelector) {
  92563. this.customEmissiveColorSelector(mesh, subMesh, material, this._emissiveTextureAndColor.color);
  92564. }
  92565. else {
  92566. if (material.emissiveColor) {
  92567. this._emissiveTextureAndColor.color.set(material.emissiveColor.r * textureLevel, material.emissiveColor.g * textureLevel, material.emissiveColor.b * textureLevel, 1.0);
  92568. }
  92569. else {
  92570. this._emissiveTextureAndColor.color.set(this.neutralColor.r, this.neutralColor.g, this.neutralColor.b, this.neutralColor.a);
  92571. }
  92572. }
  92573. };
  92574. /**
  92575. * Returns true if the mesh should render, otherwise false.
  92576. * @param mesh The mesh to render
  92577. * @returns true if it should render otherwise false
  92578. */
  92579. GlowLayer.prototype._shouldRenderMesh = function (mesh) {
  92580. return this.hasMesh(mesh);
  92581. };
  92582. /**
  92583. * Add a mesh in the exclusion list to prevent it to impact or being impacted by the glow layer.
  92584. * @param mesh The mesh to exclude from the glow layer
  92585. */
  92586. GlowLayer.prototype.addExcludedMesh = function (mesh) {
  92587. if (this._excludedMeshes.indexOf(mesh.uniqueId) === -1) {
  92588. this._excludedMeshes.push(mesh.uniqueId);
  92589. }
  92590. };
  92591. /**
  92592. * Remove a mesh from the exclusion list to let it impact or being impacted by the glow layer.
  92593. * @param mesh The mesh to remove
  92594. */
  92595. GlowLayer.prototype.removeExcludedMesh = function (mesh) {
  92596. var index = this._excludedMeshes.indexOf(mesh.uniqueId);
  92597. if (index !== -1) {
  92598. this._excludedMeshes.splice(index, 1);
  92599. }
  92600. };
  92601. /**
  92602. * Add a mesh in the inclusion list to impact or being impacted by the glow layer.
  92603. * @param mesh The mesh to include in the glow layer
  92604. */
  92605. GlowLayer.prototype.addIncludedOnlyMesh = function (mesh) {
  92606. if (this._includedOnlyMeshes.indexOf(mesh.uniqueId) === -1) {
  92607. this._includedOnlyMeshes.push(mesh.uniqueId);
  92608. }
  92609. };
  92610. /**
  92611. * Remove a mesh from the Inclusion list to prevent it to impact or being impacted by the glow layer.
  92612. * @param mesh The mesh to remove
  92613. */
  92614. GlowLayer.prototype.removeIncludedOnlyMesh = function (mesh) {
  92615. var index = this._includedOnlyMeshes.indexOf(mesh.uniqueId);
  92616. if (index !== -1) {
  92617. this._includedOnlyMeshes.splice(index, 1);
  92618. }
  92619. };
  92620. /**
  92621. * Determine if a given mesh will be used in the glow layer
  92622. * @param mesh The mesh to test
  92623. * @returns true if the mesh will be highlighted by the current glow layer
  92624. */
  92625. GlowLayer.prototype.hasMesh = function (mesh) {
  92626. // Included Mesh
  92627. if (this._includedOnlyMeshes.length) {
  92628. return this._includedOnlyMeshes.indexOf(mesh.uniqueId) !== -1;
  92629. }
  92630. ;
  92631. // Excluded Mesh
  92632. if (this._excludedMeshes.length) {
  92633. return this._excludedMeshes.indexOf(mesh.uniqueId) === -1;
  92634. }
  92635. ;
  92636. return true;
  92637. };
  92638. /**
  92639. * Free any resources and references associated to a mesh.
  92640. * Internal use
  92641. * @param mesh The mesh to free.
  92642. */
  92643. GlowLayer.prototype._disposeMesh = function (mesh) {
  92644. this.removeIncludedOnlyMesh(mesh);
  92645. this.removeExcludedMesh(mesh);
  92646. };
  92647. /**
  92648. * Gets the class name of the effect layer
  92649. * @returns the string with the class name of the effect layer
  92650. */
  92651. GlowLayer.prototype.getClassName = function () {
  92652. return "GlowLayer";
  92653. };
  92654. /**
  92655. * Serializes this glow layer
  92656. * @returns a serialized glow layer object
  92657. */
  92658. GlowLayer.prototype.serialize = function () {
  92659. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  92660. serializationObject.customType = "BABYLON.GlowLayer";
  92661. var index;
  92662. // Included meshes
  92663. serializationObject.includedMeshes = [];
  92664. if (this._includedOnlyMeshes.length) {
  92665. for (index = 0; index < this._includedOnlyMeshes.length; index++) {
  92666. var mesh = this._scene.getMeshByUniqueID(this._includedOnlyMeshes[index]);
  92667. if (mesh) {
  92668. serializationObject.includedMeshes.push(mesh.id);
  92669. }
  92670. }
  92671. }
  92672. // Excluded meshes
  92673. serializationObject.excludedMeshes = [];
  92674. if (this._excludedMeshes.length) {
  92675. for (index = 0; index < this._excludedMeshes.length; index++) {
  92676. var mesh = this._scene.getMeshByUniqueID(this._excludedMeshes[index]);
  92677. if (mesh) {
  92678. serializationObject.excludedMeshes.push(mesh.id);
  92679. }
  92680. }
  92681. }
  92682. return serializationObject;
  92683. };
  92684. /**
  92685. * Creates a Glow Layer from parsed glow layer data
  92686. * @param parsedGlowLayer defines glow layer data
  92687. * @param scene defines the current scene
  92688. * @param rootUrl defines the root URL containing the glow layer information
  92689. * @returns a parsed Glow Layer
  92690. */
  92691. GlowLayer.Parse = function (parsedGlowLayer, scene, rootUrl) {
  92692. var gl = BABYLON.SerializationHelper.Parse(function () { return new GlowLayer(parsedGlowLayer.name, scene, parsedGlowLayer.options); }, parsedGlowLayer, scene, rootUrl);
  92693. var index;
  92694. // Excluded meshes
  92695. for (index = 0; index < parsedGlowLayer.excludedMeshes.length; index++) {
  92696. var mesh = scene.getMeshByID(parsedGlowLayer.excludedMeshes[index]);
  92697. if (mesh) {
  92698. gl.addExcludedMesh(mesh);
  92699. }
  92700. }
  92701. // Included meshes
  92702. for (index = 0; index < parsedGlowLayer.includedMeshes.length; index++) {
  92703. var mesh = scene.getMeshByID(parsedGlowLayer.includedMeshes[index]);
  92704. if (mesh) {
  92705. gl.addIncludedOnlyMesh(mesh);
  92706. }
  92707. }
  92708. return gl;
  92709. };
  92710. /**
  92711. * Effect Name of the layer.
  92712. */
  92713. GlowLayer.EffectName = "GlowLayer";
  92714. /**
  92715. * The default blur kernel size used for the glow.
  92716. */
  92717. GlowLayer.DefaultBlurKernelSize = 32;
  92718. /**
  92719. * The default texture size ratio used for the glow.
  92720. */
  92721. GlowLayer.DefaultTextureRatio = 0.5;
  92722. __decorate([
  92723. BABYLON.serialize()
  92724. ], GlowLayer.prototype, "blurKernelSize", null);
  92725. __decorate([
  92726. BABYLON.serialize()
  92727. ], GlowLayer.prototype, "intensity", null);
  92728. __decorate([
  92729. BABYLON.serialize("options")
  92730. ], GlowLayer.prototype, "_options", void 0);
  92731. return GlowLayer;
  92732. }(BABYLON.EffectLayer));
  92733. BABYLON.GlowLayer = GlowLayer;
  92734. })(BABYLON || (BABYLON = {}));
  92735. //# sourceMappingURL=babylon.glowLayer.js.map
  92736. var BABYLON;
  92737. (function (BABYLON) {
  92738. /**
  92739. * Defines the list of states available for a task inside a {BABYLON.AssetsManager}
  92740. */
  92741. var AssetTaskState;
  92742. (function (AssetTaskState) {
  92743. /**
  92744. * Initialization
  92745. */
  92746. AssetTaskState[AssetTaskState["INIT"] = 0] = "INIT";
  92747. /**
  92748. * Running
  92749. */
  92750. AssetTaskState[AssetTaskState["RUNNING"] = 1] = "RUNNING";
  92751. /**
  92752. * Done
  92753. */
  92754. AssetTaskState[AssetTaskState["DONE"] = 2] = "DONE";
  92755. /**
  92756. * Error
  92757. */
  92758. AssetTaskState[AssetTaskState["ERROR"] = 3] = "ERROR";
  92759. })(AssetTaskState = BABYLON.AssetTaskState || (BABYLON.AssetTaskState = {}));
  92760. /**
  92761. * Define an abstract asset task used with a {BABYLON.AssetsManager} class to load assets into a scene
  92762. */
  92763. var AbstractAssetTask = /** @class */ (function () {
  92764. /**
  92765. * Creates a new {BABYLON.AssetsManager}
  92766. * @param name defines the name of the task
  92767. */
  92768. function AbstractAssetTask(
  92769. /**
  92770. * Task name
  92771. */ name) {
  92772. this.name = name;
  92773. this._isCompleted = false;
  92774. this._taskState = AssetTaskState.INIT;
  92775. }
  92776. Object.defineProperty(AbstractAssetTask.prototype, "isCompleted", {
  92777. /**
  92778. * Get if the task is completed
  92779. */
  92780. get: function () {
  92781. return this._isCompleted;
  92782. },
  92783. enumerable: true,
  92784. configurable: true
  92785. });
  92786. Object.defineProperty(AbstractAssetTask.prototype, "taskState", {
  92787. /**
  92788. * Gets the current state of the task
  92789. */
  92790. get: function () {
  92791. return this._taskState;
  92792. },
  92793. enumerable: true,
  92794. configurable: true
  92795. });
  92796. Object.defineProperty(AbstractAssetTask.prototype, "errorObject", {
  92797. /**
  92798. * Gets the current error object (if task is in error)
  92799. */
  92800. get: function () {
  92801. return this._errorObject;
  92802. },
  92803. enumerable: true,
  92804. configurable: true
  92805. });
  92806. /**
  92807. * Internal only
  92808. * @hidden
  92809. */
  92810. AbstractAssetTask.prototype._setErrorObject = function (message, exception) {
  92811. if (this._errorObject) {
  92812. return;
  92813. }
  92814. this._errorObject = {
  92815. message: message,
  92816. exception: exception
  92817. };
  92818. };
  92819. /**
  92820. * Execute the current task
  92821. * @param scene defines the scene where you want your assets to be loaded
  92822. * @param onSuccess is a callback called when the task is successfully executed
  92823. * @param onError is a callback called if an error occurs
  92824. */
  92825. AbstractAssetTask.prototype.run = function (scene, onSuccess, onError) {
  92826. var _this = this;
  92827. this._taskState = AssetTaskState.RUNNING;
  92828. this.runTask(scene, function () {
  92829. _this.onDoneCallback(onSuccess, onError);
  92830. }, function (msg, exception) {
  92831. _this.onErrorCallback(onError, msg, exception);
  92832. });
  92833. };
  92834. /**
  92835. * Execute the current task
  92836. * @param scene defines the scene where you want your assets to be loaded
  92837. * @param onSuccess is a callback called when the task is successfully executed
  92838. * @param onError is a callback called if an error occurs
  92839. */
  92840. AbstractAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  92841. throw new Error("runTask is not implemented");
  92842. };
  92843. AbstractAssetTask.prototype.onErrorCallback = function (onError, message, exception) {
  92844. this._taskState = AssetTaskState.ERROR;
  92845. this._errorObject = {
  92846. message: message,
  92847. exception: exception
  92848. };
  92849. if (this.onError) {
  92850. this.onError(this, message, exception);
  92851. }
  92852. onError();
  92853. };
  92854. AbstractAssetTask.prototype.onDoneCallback = function (onSuccess, onError) {
  92855. try {
  92856. this._taskState = AssetTaskState.DONE;
  92857. this._isCompleted = true;
  92858. if (this.onSuccess) {
  92859. this.onSuccess(this);
  92860. }
  92861. onSuccess();
  92862. }
  92863. catch (e) {
  92864. this.onErrorCallback(onError, "Task is done, error executing success callback(s)", e);
  92865. }
  92866. };
  92867. return AbstractAssetTask;
  92868. }());
  92869. BABYLON.AbstractAssetTask = AbstractAssetTask;
  92870. /**
  92871. * Class used to share progress information about assets loading
  92872. */
  92873. var AssetsProgressEvent = /** @class */ (function () {
  92874. /**
  92875. * Creates a {BABYLON.AssetsProgressEvent}
  92876. * @param remainingCount defines the number of remaining tasks to process
  92877. * @param totalCount defines the total number of tasks
  92878. * @param task defines the task that was just processed
  92879. */
  92880. function AssetsProgressEvent(remainingCount, totalCount, task) {
  92881. this.remainingCount = remainingCount;
  92882. this.totalCount = totalCount;
  92883. this.task = task;
  92884. }
  92885. return AssetsProgressEvent;
  92886. }());
  92887. BABYLON.AssetsProgressEvent = AssetsProgressEvent;
  92888. /**
  92889. * Define a task used by {BABYLON.AssetsManager} to load meshes
  92890. */
  92891. var MeshAssetTask = /** @class */ (function (_super) {
  92892. __extends(MeshAssetTask, _super);
  92893. /**
  92894. * Creates a new {BABYLON.MeshAssetTask}
  92895. * @param name defines the name of the task
  92896. * @param meshesNames defines the list of mesh's names you want to load
  92897. * @param rootUrl defines the root url to use as a base to load your meshes and associated resources
  92898. * @param sceneFilename defines the filename of the scene to load from
  92899. */
  92900. function MeshAssetTask(
  92901. /**
  92902. * Defines the name of the task
  92903. */
  92904. name,
  92905. /**
  92906. * Defines the list of mesh's names you want to load
  92907. */
  92908. meshesNames,
  92909. /**
  92910. * Defines the root url to use as a base to load your meshes and associated resources
  92911. */
  92912. rootUrl,
  92913. /**
  92914. * Defines the filename of the scene to load from
  92915. */
  92916. sceneFilename) {
  92917. var _this = _super.call(this, name) || this;
  92918. _this.name = name;
  92919. _this.meshesNames = meshesNames;
  92920. _this.rootUrl = rootUrl;
  92921. _this.sceneFilename = sceneFilename;
  92922. return _this;
  92923. }
  92924. /**
  92925. * Execute the current task
  92926. * @param scene defines the scene where you want your assets to be loaded
  92927. * @param onSuccess is a callback called when the task is successfully executed
  92928. * @param onError is a callback called if an error occurs
  92929. */
  92930. MeshAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  92931. var _this = this;
  92932. BABYLON.SceneLoader.ImportMesh(this.meshesNames, this.rootUrl, this.sceneFilename, scene, function (meshes, particleSystems, skeletons) {
  92933. _this.loadedMeshes = meshes;
  92934. _this.loadedParticleSystems = particleSystems;
  92935. _this.loadedSkeletons = skeletons;
  92936. onSuccess();
  92937. }, null, function (scene, message, exception) {
  92938. onError(message, exception);
  92939. });
  92940. };
  92941. return MeshAssetTask;
  92942. }(AbstractAssetTask));
  92943. BABYLON.MeshAssetTask = MeshAssetTask;
  92944. /**
  92945. * Define a task used by {BABYLON.AssetsManager} to load text content
  92946. */
  92947. var TextFileAssetTask = /** @class */ (function (_super) {
  92948. __extends(TextFileAssetTask, _super);
  92949. /**
  92950. * Creates a new TextFileAssetTask object
  92951. * @param name defines the name of the task
  92952. * @param url defines the location of the file to load
  92953. */
  92954. function TextFileAssetTask(
  92955. /**
  92956. * Defines the name of the task
  92957. */
  92958. name,
  92959. /**
  92960. * Defines the location of the file to load
  92961. */
  92962. url) {
  92963. var _this = _super.call(this, name) || this;
  92964. _this.name = name;
  92965. _this.url = url;
  92966. return _this;
  92967. }
  92968. /**
  92969. * Execute the current task
  92970. * @param scene defines the scene where you want your assets to be loaded
  92971. * @param onSuccess is a callback called when the task is successfully executed
  92972. * @param onError is a callback called if an error occurs
  92973. */
  92974. TextFileAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  92975. var _this = this;
  92976. scene._loadFile(this.url, function (data) {
  92977. _this.text = data;
  92978. onSuccess();
  92979. }, undefined, false, false, function (request, exception) {
  92980. if (request) {
  92981. onError(request.status + " " + request.statusText, exception);
  92982. }
  92983. });
  92984. };
  92985. return TextFileAssetTask;
  92986. }(AbstractAssetTask));
  92987. BABYLON.TextFileAssetTask = TextFileAssetTask;
  92988. /**
  92989. * Define a task used by {BABYLON.AssetsManager} to load binary data
  92990. */
  92991. var BinaryFileAssetTask = /** @class */ (function (_super) {
  92992. __extends(BinaryFileAssetTask, _super);
  92993. /**
  92994. * Creates a new BinaryFileAssetTask object
  92995. * @param name defines the name of the new task
  92996. * @param url defines the location of the file to load
  92997. */
  92998. function BinaryFileAssetTask(
  92999. /**
  93000. * Defines the name of the task
  93001. */
  93002. name,
  93003. /**
  93004. * Defines the location of the file to load
  93005. */
  93006. url) {
  93007. var _this = _super.call(this, name) || this;
  93008. _this.name = name;
  93009. _this.url = url;
  93010. return _this;
  93011. }
  93012. /**
  93013. * Execute the current task
  93014. * @param scene defines the scene where you want your assets to be loaded
  93015. * @param onSuccess is a callback called when the task is successfully executed
  93016. * @param onError is a callback called if an error occurs
  93017. */
  93018. BinaryFileAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  93019. var _this = this;
  93020. scene._loadFile(this.url, function (data) {
  93021. _this.data = data;
  93022. onSuccess();
  93023. }, undefined, true, true, function (request, exception) {
  93024. if (request) {
  93025. onError(request.status + " " + request.statusText, exception);
  93026. }
  93027. });
  93028. };
  93029. return BinaryFileAssetTask;
  93030. }(AbstractAssetTask));
  93031. BABYLON.BinaryFileAssetTask = BinaryFileAssetTask;
  93032. /**
  93033. * Define a task used by {BABYLON.AssetsManager} to load images
  93034. */
  93035. var ImageAssetTask = /** @class */ (function (_super) {
  93036. __extends(ImageAssetTask, _super);
  93037. /**
  93038. * Creates a new ImageAssetTask
  93039. * @param name defines the name of the task
  93040. * @param url defines the location of the image to load
  93041. */
  93042. function ImageAssetTask(
  93043. /**
  93044. * Defines the name of the task
  93045. */
  93046. name,
  93047. /**
  93048. * Defines the location of the image to load
  93049. */
  93050. url) {
  93051. var _this = _super.call(this, name) || this;
  93052. _this.name = name;
  93053. _this.url = url;
  93054. return _this;
  93055. }
  93056. /**
  93057. * Execute the current task
  93058. * @param scene defines the scene where you want your assets to be loaded
  93059. * @param onSuccess is a callback called when the task is successfully executed
  93060. * @param onError is a callback called if an error occurs
  93061. */
  93062. ImageAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  93063. var _this = this;
  93064. var img = new Image();
  93065. BABYLON.Tools.SetCorsBehavior(this.url, img);
  93066. img.onload = function () {
  93067. _this.image = img;
  93068. onSuccess();
  93069. };
  93070. img.onerror = function (err) {
  93071. onError("Error loading image", err);
  93072. };
  93073. img.src = this.url;
  93074. };
  93075. return ImageAssetTask;
  93076. }(AbstractAssetTask));
  93077. BABYLON.ImageAssetTask = ImageAssetTask;
  93078. /**
  93079. * Define a task used by {BABYLON.AssetsManager} to load 2D textures
  93080. */
  93081. var TextureAssetTask = /** @class */ (function (_super) {
  93082. __extends(TextureAssetTask, _super);
  93083. /**
  93084. * Creates a new TextureAssetTask object
  93085. * @param name defines the name of the task
  93086. * @param url defines the location of the file to load
  93087. * @param noMipmap defines if mipmap should not be generated (default is false)
  93088. * @param invertY defines if texture must be inverted on Y axis (default is false)
  93089. * @param samplingMode defines the sampling mode to use (default is BABYLON.Texture.TRILINEAR_SAMPLINGMODE)
  93090. */
  93091. function TextureAssetTask(
  93092. /**
  93093. * Defines the name of the task
  93094. */
  93095. name,
  93096. /**
  93097. * Defines the location of the file to load
  93098. */
  93099. url,
  93100. /**
  93101. * Defines if mipmap should not be generated (default is false)
  93102. */
  93103. noMipmap,
  93104. /**
  93105. * Defines if texture must be inverted on Y axis (default is false)
  93106. */
  93107. invertY,
  93108. /**
  93109. * Defines the sampling mode to use (default is BABYLON.Texture.TRILINEAR_SAMPLINGMODE)
  93110. */
  93111. samplingMode) {
  93112. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  93113. var _this = _super.call(this, name) || this;
  93114. _this.name = name;
  93115. _this.url = url;
  93116. _this.noMipmap = noMipmap;
  93117. _this.invertY = invertY;
  93118. _this.samplingMode = samplingMode;
  93119. return _this;
  93120. }
  93121. /**
  93122. * Execute the current task
  93123. * @param scene defines the scene where you want your assets to be loaded
  93124. * @param onSuccess is a callback called when the task is successfully executed
  93125. * @param onError is a callback called if an error occurs
  93126. */
  93127. TextureAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  93128. var onload = function () {
  93129. onSuccess();
  93130. };
  93131. var onerror = function (message, exception) {
  93132. onError(message, exception);
  93133. };
  93134. this.texture = new BABYLON.Texture(this.url, scene, this.noMipmap, this.invertY, this.samplingMode, onload, onerror);
  93135. };
  93136. return TextureAssetTask;
  93137. }(AbstractAssetTask));
  93138. BABYLON.TextureAssetTask = TextureAssetTask;
  93139. /**
  93140. * Define a task used by {BABYLON.AssetsManager} to load cube textures
  93141. */
  93142. var CubeTextureAssetTask = /** @class */ (function (_super) {
  93143. __extends(CubeTextureAssetTask, _super);
  93144. /**
  93145. * Creates a new CubeTextureAssetTask
  93146. * @param name defines the name of the task
  93147. * @param url defines the location of the files to load (You have to specify the folder where the files are + filename with no extension)
  93148. * @param extensions defines the extensions to use to load files (["_px", "_py", "_pz", "_nx", "_ny", "_nz"] by default)
  93149. * @param noMipmap defines if mipmaps should not be generated (default is false)
  93150. * @param files defines the explicit list of files (undefined by default)
  93151. */
  93152. function CubeTextureAssetTask(
  93153. /**
  93154. * Defines the name of the task
  93155. */
  93156. name,
  93157. /**
  93158. * Defines the location of the files to load (You have to specify the folder where the files are + filename with no extension)
  93159. */
  93160. url,
  93161. /**
  93162. * Defines the extensions to use to load files (["_px", "_py", "_pz", "_nx", "_ny", "_nz"] by default)
  93163. */
  93164. extensions,
  93165. /**
  93166. * Defines if mipmaps should not be generated (default is false)
  93167. */
  93168. noMipmap,
  93169. /**
  93170. * Defines the explicit list of files (undefined by default)
  93171. */
  93172. files) {
  93173. var _this = _super.call(this, name) || this;
  93174. _this.name = name;
  93175. _this.url = url;
  93176. _this.extensions = extensions;
  93177. _this.noMipmap = noMipmap;
  93178. _this.files = files;
  93179. return _this;
  93180. }
  93181. /**
  93182. * Execute the current task
  93183. * @param scene defines the scene where you want your assets to be loaded
  93184. * @param onSuccess is a callback called when the task is successfully executed
  93185. * @param onError is a callback called if an error occurs
  93186. */
  93187. CubeTextureAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  93188. var onload = function () {
  93189. onSuccess();
  93190. };
  93191. var onerror = function (message, exception) {
  93192. onError(message, exception);
  93193. };
  93194. this.texture = new BABYLON.CubeTexture(this.url, scene, this.extensions, this.noMipmap, this.files, onload, onerror);
  93195. };
  93196. return CubeTextureAssetTask;
  93197. }(AbstractAssetTask));
  93198. BABYLON.CubeTextureAssetTask = CubeTextureAssetTask;
  93199. /**
  93200. * Define a task used by {BABYLON.AssetsManager} to load HDR cube textures
  93201. */
  93202. var HDRCubeTextureAssetTask = /** @class */ (function (_super) {
  93203. __extends(HDRCubeTextureAssetTask, _super);
  93204. /**
  93205. * Creates a new HDRCubeTextureAssetTask object
  93206. * @param name defines the name of the task
  93207. * @param url defines the location of the file to load
  93208. * @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.
  93209. * @param noMipmap defines if mipmaps should not be generated (default is false)
  93210. * @param generateHarmonics specifies whether you want to extract the polynomial harmonics during the generation process (default is true)
  93211. * @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)
  93212. * @param usePMREMGenerator specifies whether or not to generate the CubeMap through CubeMapGen to avoid seams issue at run time (default is false)
  93213. */
  93214. function HDRCubeTextureAssetTask(
  93215. /**
  93216. * Defines the name of the task
  93217. */
  93218. name,
  93219. /**
  93220. * Defines the location of the file to load
  93221. */
  93222. url,
  93223. /**
  93224. * 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.
  93225. */
  93226. size,
  93227. /**
  93228. * Defines if mipmaps should not be generated (default is false)
  93229. */
  93230. noMipmap,
  93231. /**
  93232. * Specifies whether you want to extract the polynomial harmonics during the generation process (default is true)
  93233. */
  93234. generateHarmonics,
  93235. /**
  93236. * 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)
  93237. */
  93238. useInGammaSpace,
  93239. /**
  93240. * Specifies whether or not to generate the CubeMap through CubeMapGen to avoid seams issue at run time (default is false)
  93241. */
  93242. usePMREMGenerator) {
  93243. if (noMipmap === void 0) { noMipmap = false; }
  93244. if (generateHarmonics === void 0) { generateHarmonics = true; }
  93245. if (useInGammaSpace === void 0) { useInGammaSpace = false; }
  93246. if (usePMREMGenerator === void 0) { usePMREMGenerator = false; }
  93247. var _this = _super.call(this, name) || this;
  93248. _this.name = name;
  93249. _this.url = url;
  93250. _this.size = size;
  93251. _this.noMipmap = noMipmap;
  93252. _this.generateHarmonics = generateHarmonics;
  93253. _this.useInGammaSpace = useInGammaSpace;
  93254. _this.usePMREMGenerator = usePMREMGenerator;
  93255. return _this;
  93256. }
  93257. /**
  93258. * Execute the current task
  93259. * @param scene defines the scene where you want your assets to be loaded
  93260. * @param onSuccess is a callback called when the task is successfully executed
  93261. * @param onError is a callback called if an error occurs
  93262. */
  93263. HDRCubeTextureAssetTask.prototype.run = function (scene, onSuccess, onError) {
  93264. var onload = function () {
  93265. onSuccess();
  93266. };
  93267. var onerror = function (message, exception) {
  93268. onError(message, exception);
  93269. };
  93270. this.texture = new BABYLON.HDRCubeTexture(this.url, scene, this.size, this.noMipmap, this.generateHarmonics, this.useInGammaSpace, this.usePMREMGenerator, onload, onerror);
  93271. };
  93272. return HDRCubeTextureAssetTask;
  93273. }(AbstractAssetTask));
  93274. BABYLON.HDRCubeTextureAssetTask = HDRCubeTextureAssetTask;
  93275. /**
  93276. * This class can be used to easily import assets into a scene
  93277. * @see http://doc.babylonjs.com/how_to/how_to_use_assetsmanager
  93278. */
  93279. var AssetsManager = /** @class */ (function () {
  93280. /**
  93281. * Creates a new AssetsManager
  93282. * @param scene defines the scene to work on
  93283. */
  93284. function AssetsManager(scene) {
  93285. this._isLoading = false;
  93286. this._tasks = new Array();
  93287. this._waitingTasksCount = 0;
  93288. this._totalTasksCount = 0;
  93289. /**
  93290. * Observable called when all tasks are processed
  93291. */
  93292. this.onTaskSuccessObservable = new BABYLON.Observable();
  93293. /**
  93294. * Observable called when a task had an error
  93295. */
  93296. this.onTaskErrorObservable = new BABYLON.Observable();
  93297. /**
  93298. * Observable called when a task is successful
  93299. */
  93300. this.onTasksDoneObservable = new BABYLON.Observable();
  93301. /**
  93302. * Observable called when a task is done (whatever the result is)
  93303. */
  93304. this.onProgressObservable = new BABYLON.Observable();
  93305. /**
  93306. * Gets or sets a boolean defining if the {BABYLON.AssetsManager} should use the default loading screen
  93307. * @see http://doc.babylonjs.com/how_to/creating_a_custom_loading_screen
  93308. */
  93309. this.useDefaultLoadingScreen = true;
  93310. this._scene = scene;
  93311. }
  93312. /**
  93313. * Add a {BABYLON.MeshAssetTask} to the list of active tasks
  93314. * @param taskName defines the name of the new task
  93315. * @param meshesNames defines the name of meshes to load
  93316. * @param rootUrl defines the root url to use to locate files
  93317. * @param sceneFilename defines the filename of the scene file
  93318. * @returns a new {BABYLON.MeshAssetTask} object
  93319. */
  93320. AssetsManager.prototype.addMeshTask = function (taskName, meshesNames, rootUrl, sceneFilename) {
  93321. var task = new MeshAssetTask(taskName, meshesNames, rootUrl, sceneFilename);
  93322. this._tasks.push(task);
  93323. return task;
  93324. };
  93325. /**
  93326. * Add a {BABYLON.TextFileAssetTask} to the list of active tasks
  93327. * @param taskName defines the name of the new task
  93328. * @param url defines the url of the file to load
  93329. * @returns a new {BABYLON.TextFileAssetTask} object
  93330. */
  93331. AssetsManager.prototype.addTextFileTask = function (taskName, url) {
  93332. var task = new TextFileAssetTask(taskName, url);
  93333. this._tasks.push(task);
  93334. return task;
  93335. };
  93336. /**
  93337. * Add a {BABYLON.BinaryFileAssetTask} to the list of active tasks
  93338. * @param taskName defines the name of the new task
  93339. * @param url defines the url of the file to load
  93340. * @returns a new {BABYLON.BinaryFileAssetTask} object
  93341. */
  93342. AssetsManager.prototype.addBinaryFileTask = function (taskName, url) {
  93343. var task = new BinaryFileAssetTask(taskName, url);
  93344. this._tasks.push(task);
  93345. return task;
  93346. };
  93347. /**
  93348. * Add a {BABYLON.ImageAssetTask} to the list of active tasks
  93349. * @param taskName defines the name of the new task
  93350. * @param url defines the url of the file to load
  93351. * @returns a new {BABYLON.ImageAssetTask} object
  93352. */
  93353. AssetsManager.prototype.addImageTask = function (taskName, url) {
  93354. var task = new ImageAssetTask(taskName, url);
  93355. this._tasks.push(task);
  93356. return task;
  93357. };
  93358. /**
  93359. * Add a {BABYLON.TextureAssetTask} to the list of active tasks
  93360. * @param taskName defines the name of the new task
  93361. * @param url defines the url of the file to load
  93362. * @param noMipmap defines if the texture must not receive mipmaps (false by default)
  93363. * @param invertY defines if you want to invert Y axis of the loaded texture (false by default)
  93364. * @param samplingMode defines the sampling mode to use (BABYLON.Texture.TRILINEAR_SAMPLINGMODE by default)
  93365. * @returns a new {BABYLON.TextureAssetTask} object
  93366. */
  93367. AssetsManager.prototype.addTextureTask = function (taskName, url, noMipmap, invertY, samplingMode) {
  93368. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  93369. var task = new TextureAssetTask(taskName, url, noMipmap, invertY, samplingMode);
  93370. this._tasks.push(task);
  93371. return task;
  93372. };
  93373. /**
  93374. * Add a {BABYLON.CubeTextureAssetTask} to the list of active tasks
  93375. * @param taskName defines the name of the new task
  93376. * @param url defines the url of the file to load
  93377. * @param extensions defines the extension to use to load the cube map (can be null)
  93378. * @param noMipmap defines if the texture must not receive mipmaps (false by default)
  93379. * @param files defines the list of files to load (can be null)
  93380. * @returns a new {BABYLON.CubeTextureAssetTask} object
  93381. */
  93382. AssetsManager.prototype.addCubeTextureTask = function (taskName, url, extensions, noMipmap, files) {
  93383. var task = new CubeTextureAssetTask(taskName, url, extensions, noMipmap, files);
  93384. this._tasks.push(task);
  93385. return task;
  93386. };
  93387. /**
  93388. *
  93389. * Add a {BABYLON.HDRCubeTextureAssetTask} to the list of active tasks
  93390. * @param taskName defines the name of the new task
  93391. * @param url defines the url of the file to load
  93392. * @param size defines the size you want for the cubemap (can be null)
  93393. * @param noMipmap defines if the texture must not receive mipmaps (false by default)
  93394. * @param generateHarmonics defines if you want to automatically generate (true by default)
  93395. * @param useInGammaSpace defines if the texture must be considered in gamma space (false by default)
  93396. * @param usePMREMGenerator is a reserved parameter and must be set to false or ignored
  93397. * @returns a new {BABYLON.HDRCubeTextureAssetTask} object
  93398. */
  93399. AssetsManager.prototype.addHDRCubeTextureTask = function (taskName, url, size, noMipmap, generateHarmonics, useInGammaSpace, usePMREMGenerator) {
  93400. if (noMipmap === void 0) { noMipmap = false; }
  93401. if (generateHarmonics === void 0) { generateHarmonics = true; }
  93402. if (useInGammaSpace === void 0) { useInGammaSpace = false; }
  93403. if (usePMREMGenerator === void 0) { usePMREMGenerator = false; }
  93404. var task = new HDRCubeTextureAssetTask(taskName, url, size, noMipmap, generateHarmonics, useInGammaSpace, usePMREMGenerator);
  93405. this._tasks.push(task);
  93406. return task;
  93407. };
  93408. AssetsManager.prototype._decreaseWaitingTasksCount = function (task) {
  93409. var _this = this;
  93410. this._waitingTasksCount--;
  93411. try {
  93412. if (task.taskState === AssetTaskState.DONE) {
  93413. // Let's remove successfull tasks
  93414. BABYLON.Tools.SetImmediate(function () {
  93415. var index = _this._tasks.indexOf(task);
  93416. if (index > -1) {
  93417. _this._tasks.splice(index, 1);
  93418. }
  93419. });
  93420. }
  93421. if (this.onProgress) {
  93422. this.onProgress(this._waitingTasksCount, this._totalTasksCount, task);
  93423. }
  93424. this.onProgressObservable.notifyObservers(new AssetsProgressEvent(this._waitingTasksCount, this._totalTasksCount, task));
  93425. }
  93426. catch (e) {
  93427. BABYLON.Tools.Error("Error running progress callbacks.");
  93428. console.log(e);
  93429. }
  93430. if (this._waitingTasksCount === 0) {
  93431. try {
  93432. if (this.onFinish) {
  93433. this.onFinish(this._tasks);
  93434. }
  93435. this.onTasksDoneObservable.notifyObservers(this._tasks);
  93436. }
  93437. catch (e) {
  93438. BABYLON.Tools.Error("Error running tasks-done callbacks.");
  93439. console.log(e);
  93440. }
  93441. this._isLoading = false;
  93442. this._scene.getEngine().hideLoadingUI();
  93443. }
  93444. };
  93445. AssetsManager.prototype._runTask = function (task) {
  93446. var _this = this;
  93447. var done = function () {
  93448. try {
  93449. if (_this.onTaskSuccess) {
  93450. _this.onTaskSuccess(task);
  93451. }
  93452. _this.onTaskSuccessObservable.notifyObservers(task);
  93453. _this._decreaseWaitingTasksCount(task);
  93454. }
  93455. catch (e) {
  93456. error("Error executing task success callbacks", e);
  93457. }
  93458. };
  93459. var error = function (message, exception) {
  93460. task._setErrorObject(message, exception);
  93461. if (_this.onTaskError) {
  93462. _this.onTaskError(task);
  93463. }
  93464. _this.onTaskErrorObservable.notifyObservers(task);
  93465. _this._decreaseWaitingTasksCount(task);
  93466. };
  93467. task.run(this._scene, done, error);
  93468. };
  93469. /**
  93470. * Reset the {BABYLON.AssetsManager} and remove all tasks
  93471. * @return the current instance of the {BABYLON.AssetsManager}
  93472. */
  93473. AssetsManager.prototype.reset = function () {
  93474. this._isLoading = false;
  93475. this._tasks = new Array();
  93476. return this;
  93477. };
  93478. /**
  93479. * Start the loading process
  93480. * @return the current instance of the {BABYLON.AssetsManager}
  93481. */
  93482. AssetsManager.prototype.load = function () {
  93483. if (this._isLoading) {
  93484. return this;
  93485. }
  93486. this._isLoading = true;
  93487. this._waitingTasksCount = this._tasks.length;
  93488. this._totalTasksCount = this._tasks.length;
  93489. if (this._waitingTasksCount === 0) {
  93490. this._isLoading = false;
  93491. if (this.onFinish) {
  93492. this.onFinish(this._tasks);
  93493. }
  93494. this.onTasksDoneObservable.notifyObservers(this._tasks);
  93495. return this;
  93496. }
  93497. if (this.useDefaultLoadingScreen) {
  93498. this._scene.getEngine().displayLoadingUI();
  93499. }
  93500. for (var index = 0; index < this._tasks.length; index++) {
  93501. var task = this._tasks[index];
  93502. this._runTask(task);
  93503. }
  93504. return this;
  93505. };
  93506. return AssetsManager;
  93507. }());
  93508. BABYLON.AssetsManager = AssetsManager;
  93509. })(BABYLON || (BABYLON = {}));
  93510. //# sourceMappingURL=babylon.assetsManager.js.map
  93511. var BABYLON;
  93512. (function (BABYLON) {
  93513. var serializedGeometries = [];
  93514. var serializeGeometry = function (geometry, serializationGeometries) {
  93515. if (serializedGeometries[geometry.id]) {
  93516. return;
  93517. }
  93518. if (geometry.doNotSerialize) {
  93519. return;
  93520. }
  93521. if (geometry instanceof BABYLON.BoxGeometry) {
  93522. serializationGeometries.boxes.push(geometry.serialize());
  93523. }
  93524. else if (geometry instanceof BABYLON.SphereGeometry) {
  93525. serializationGeometries.spheres.push(geometry.serialize());
  93526. }
  93527. else if (geometry instanceof BABYLON.CylinderGeometry) {
  93528. serializationGeometries.cylinders.push(geometry.serialize());
  93529. }
  93530. else if (geometry instanceof BABYLON.TorusGeometry) {
  93531. serializationGeometries.toruses.push(geometry.serialize());
  93532. }
  93533. else if (geometry instanceof BABYLON.GroundGeometry) {
  93534. serializationGeometries.grounds.push(geometry.serialize());
  93535. }
  93536. else if (geometry instanceof BABYLON.Plane) {
  93537. serializationGeometries.planes.push(geometry.serialize());
  93538. }
  93539. else if (geometry instanceof BABYLON.TorusKnotGeometry) {
  93540. serializationGeometries.torusKnots.push(geometry.serialize());
  93541. }
  93542. else if (geometry instanceof BABYLON._PrimitiveGeometry) {
  93543. throw new Error("Unknown primitive type");
  93544. }
  93545. else {
  93546. serializationGeometries.vertexData.push(geometry.serializeVerticeData());
  93547. }
  93548. serializedGeometries[geometry.id] = true;
  93549. };
  93550. var serializeMesh = function (mesh, serializationScene) {
  93551. var serializationObject = {};
  93552. // Geometry
  93553. var geometry = mesh._geometry;
  93554. if (geometry) {
  93555. if (!mesh.getScene().getGeometryByID(geometry.id)) {
  93556. // 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
  93557. serializeGeometry(geometry, serializationScene.geometries);
  93558. }
  93559. }
  93560. // Custom
  93561. if (mesh.serialize) {
  93562. mesh.serialize(serializationObject);
  93563. }
  93564. return serializationObject;
  93565. };
  93566. var finalizeSingleMesh = function (mesh, serializationObject) {
  93567. //only works if the mesh is already loaded
  93568. if (mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADED || mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NONE) {
  93569. //serialize material
  93570. if (mesh.material) {
  93571. if (mesh.material instanceof BABYLON.StandardMaterial) {
  93572. serializationObject.materials = serializationObject.materials || [];
  93573. if (!serializationObject.materials.some(function (mat) { return (mat.id === mesh.material.id); })) {
  93574. serializationObject.materials.push(mesh.material.serialize());
  93575. }
  93576. }
  93577. else if (mesh.material instanceof BABYLON.MultiMaterial) {
  93578. serializationObject.multiMaterials = serializationObject.multiMaterials || [];
  93579. if (!serializationObject.multiMaterials.some(function (mat) { return (mat.id === mesh.material.id); })) {
  93580. serializationObject.multiMaterials.push(mesh.material.serialize());
  93581. }
  93582. }
  93583. }
  93584. //serialize geometry
  93585. var geometry = mesh._geometry;
  93586. if (geometry) {
  93587. if (!serializationObject.geometries) {
  93588. serializationObject.geometries = {};
  93589. serializationObject.geometries.boxes = [];
  93590. serializationObject.geometries.spheres = [];
  93591. serializationObject.geometries.cylinders = [];
  93592. serializationObject.geometries.toruses = [];
  93593. serializationObject.geometries.grounds = [];
  93594. serializationObject.geometries.planes = [];
  93595. serializationObject.geometries.torusKnots = [];
  93596. serializationObject.geometries.vertexData = [];
  93597. }
  93598. serializeGeometry(geometry, serializationObject.geometries);
  93599. }
  93600. // Skeletons
  93601. if (mesh.skeleton) {
  93602. serializationObject.skeletons = serializationObject.skeletons || [];
  93603. serializationObject.skeletons.push(mesh.skeleton.serialize());
  93604. }
  93605. //serialize the actual mesh
  93606. serializationObject.meshes = serializationObject.meshes || [];
  93607. serializationObject.meshes.push(serializeMesh(mesh, serializationObject));
  93608. }
  93609. };
  93610. var SceneSerializer = /** @class */ (function () {
  93611. function SceneSerializer() {
  93612. }
  93613. SceneSerializer.ClearCache = function () {
  93614. serializedGeometries = [];
  93615. };
  93616. SceneSerializer.Serialize = function (scene) {
  93617. var serializationObject = {};
  93618. SceneSerializer.ClearCache();
  93619. // Scene
  93620. serializationObject.useDelayedTextureLoading = scene.useDelayedTextureLoading;
  93621. serializationObject.autoClear = scene.autoClear;
  93622. serializationObject.clearColor = scene.clearColor.asArray();
  93623. serializationObject.ambientColor = scene.ambientColor.asArray();
  93624. serializationObject.gravity = scene.gravity.asArray();
  93625. serializationObject.collisionsEnabled = scene.collisionsEnabled;
  93626. serializationObject.workerCollisions = scene.workerCollisions;
  93627. // Fog
  93628. if (scene.fogMode && scene.fogMode !== 0) {
  93629. serializationObject.fogMode = scene.fogMode;
  93630. serializationObject.fogColor = scene.fogColor.asArray();
  93631. serializationObject.fogStart = scene.fogStart;
  93632. serializationObject.fogEnd = scene.fogEnd;
  93633. serializationObject.fogDensity = scene.fogDensity;
  93634. }
  93635. //Physics
  93636. if (scene.isPhysicsEnabled()) {
  93637. var physicEngine = scene.getPhysicsEngine();
  93638. if (physicEngine) {
  93639. serializationObject.physicsEnabled = true;
  93640. serializationObject.physicsGravity = physicEngine.gravity.asArray();
  93641. serializationObject.physicsEngine = physicEngine.getPhysicsPluginName();
  93642. }
  93643. }
  93644. // Metadata
  93645. if (scene.metadata) {
  93646. serializationObject.metadata = scene.metadata;
  93647. }
  93648. // Morph targets
  93649. serializationObject.morphTargetManagers = [];
  93650. for (var _i = 0, _a = scene.meshes; _i < _a.length; _i++) {
  93651. var abstractMesh = _a[_i];
  93652. var manager = abstractMesh.morphTargetManager;
  93653. if (manager) {
  93654. serializationObject.morphTargetManagers.push(manager.serialize());
  93655. }
  93656. }
  93657. // Lights
  93658. serializationObject.lights = [];
  93659. var index;
  93660. var light;
  93661. for (index = 0; index < scene.lights.length; index++) {
  93662. light = scene.lights[index];
  93663. if (!light.doNotSerialize) {
  93664. serializationObject.lights.push(light.serialize());
  93665. }
  93666. }
  93667. // Cameras
  93668. serializationObject.cameras = [];
  93669. for (index = 0; index < scene.cameras.length; index++) {
  93670. var camera = scene.cameras[index];
  93671. if (!camera.doNotSerialize) {
  93672. serializationObject.cameras.push(camera.serialize());
  93673. }
  93674. }
  93675. if (scene.activeCamera) {
  93676. serializationObject.activeCameraID = scene.activeCamera.id;
  93677. }
  93678. // Animations
  93679. BABYLON.Animation.AppendSerializedAnimations(scene, serializationObject);
  93680. // Materials
  93681. serializationObject.materials = [];
  93682. serializationObject.multiMaterials = [];
  93683. var material;
  93684. for (index = 0; index < scene.materials.length; index++) {
  93685. material = scene.materials[index];
  93686. if (!material.doNotSerialize) {
  93687. serializationObject.materials.push(material.serialize());
  93688. }
  93689. }
  93690. // MultiMaterials
  93691. serializationObject.multiMaterials = [];
  93692. for (index = 0; index < scene.multiMaterials.length; index++) {
  93693. var multiMaterial = scene.multiMaterials[index];
  93694. serializationObject.multiMaterials.push(multiMaterial.serialize());
  93695. }
  93696. // Environment texture
  93697. if (scene.environmentTexture) {
  93698. serializationObject.environmentTexture = scene.environmentTexture.name;
  93699. }
  93700. // Skeletons
  93701. serializationObject.skeletons = [];
  93702. for (index = 0; index < scene.skeletons.length; index++) {
  93703. var skeleton = scene.skeletons[index];
  93704. if (!skeleton.doNotSerialize) {
  93705. serializationObject.skeletons.push(skeleton.serialize());
  93706. }
  93707. }
  93708. // Transform nodes
  93709. serializationObject.transformNodes = [];
  93710. for (index = 0; index < scene.transformNodes.length; index++) {
  93711. serializationObject.transformNodes.push(scene.transformNodes[index].serialize());
  93712. }
  93713. // Geometries
  93714. serializationObject.geometries = {};
  93715. serializationObject.geometries.boxes = [];
  93716. serializationObject.geometries.spheres = [];
  93717. serializationObject.geometries.cylinders = [];
  93718. serializationObject.geometries.toruses = [];
  93719. serializationObject.geometries.grounds = [];
  93720. serializationObject.geometries.planes = [];
  93721. serializationObject.geometries.torusKnots = [];
  93722. serializationObject.geometries.vertexData = [];
  93723. serializedGeometries = [];
  93724. var geometries = scene.getGeometries();
  93725. for (index = 0; index < geometries.length; index++) {
  93726. var geometry = geometries[index];
  93727. if (geometry.isReady()) {
  93728. serializeGeometry(geometry, serializationObject.geometries);
  93729. }
  93730. }
  93731. // Meshes
  93732. serializationObject.meshes = [];
  93733. for (index = 0; index < scene.meshes.length; index++) {
  93734. var abstractMesh = scene.meshes[index];
  93735. if (abstractMesh instanceof BABYLON.Mesh) {
  93736. var mesh = abstractMesh;
  93737. if (!mesh.doNotSerialize) {
  93738. if (mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADED || mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NONE) {
  93739. serializationObject.meshes.push(serializeMesh(mesh, serializationObject));
  93740. }
  93741. }
  93742. }
  93743. }
  93744. // Particles Systems
  93745. serializationObject.particleSystems = [];
  93746. for (index = 0; index < scene.particleSystems.length; index++) {
  93747. serializationObject.particleSystems.push(scene.particleSystems[index].serialize());
  93748. }
  93749. // Lens flares
  93750. serializationObject.lensFlareSystems = [];
  93751. for (index = 0; index < scene.lensFlareSystems.length; index++) {
  93752. serializationObject.lensFlareSystems.push(scene.lensFlareSystems[index].serialize());
  93753. }
  93754. // Shadows
  93755. serializationObject.shadowGenerators = [];
  93756. for (index = 0; index < scene.lights.length; index++) {
  93757. light = scene.lights[index];
  93758. var shadowGenerator = light.getShadowGenerator();
  93759. if (shadowGenerator) {
  93760. serializationObject.shadowGenerators.push(shadowGenerator.serialize());
  93761. }
  93762. }
  93763. // Action Manager
  93764. if (scene.actionManager) {
  93765. serializationObject.actions = scene.actionManager.serialize("scene");
  93766. }
  93767. // Audio
  93768. serializationObject.sounds = [];
  93769. for (index = 0; index < scene.soundTracks.length; index++) {
  93770. var soundtrack = scene.soundTracks[index];
  93771. for (var soundId = 0; soundId < soundtrack.soundCollection.length; soundId++) {
  93772. serializationObject.sounds.push(soundtrack.soundCollection[soundId].serialize());
  93773. }
  93774. }
  93775. // Effect layers
  93776. serializationObject.effectLayers = [];
  93777. for (index = 0; index < scene.effectLayers.length; index++) {
  93778. var layer = scene.effectLayers[index];
  93779. if (layer.serialize) {
  93780. serializationObject.effectLayers.push(layer.serialize());
  93781. }
  93782. }
  93783. return serializationObject;
  93784. };
  93785. SceneSerializer.SerializeMesh = function (toSerialize /* Mesh || Mesh[] */, withParents, withChildren) {
  93786. if (withParents === void 0) { withParents = false; }
  93787. if (withChildren === void 0) { withChildren = false; }
  93788. var serializationObject = {};
  93789. SceneSerializer.ClearCache();
  93790. toSerialize = (toSerialize instanceof Array) ? toSerialize : [toSerialize];
  93791. if (withParents || withChildren) {
  93792. //deliberate for loop! not for each, appended should be processed as well.
  93793. for (var i = 0; i < toSerialize.length; ++i) {
  93794. if (withChildren) {
  93795. toSerialize[i].getDescendants().forEach(function (node) {
  93796. if (node instanceof BABYLON.Mesh && (toSerialize.indexOf(node) < 0)) {
  93797. toSerialize.push(node);
  93798. }
  93799. });
  93800. }
  93801. //make sure the array doesn't contain the object already
  93802. if (withParents && toSerialize[i].parent && (toSerialize.indexOf(toSerialize[i].parent) < 0)) {
  93803. toSerialize.push(toSerialize[i].parent);
  93804. }
  93805. }
  93806. }
  93807. toSerialize.forEach(function (mesh) {
  93808. finalizeSingleMesh(mesh, serializationObject);
  93809. });
  93810. return serializationObject;
  93811. };
  93812. return SceneSerializer;
  93813. }());
  93814. BABYLON.SceneSerializer = SceneSerializer;
  93815. })(BABYLON || (BABYLON = {}));
  93816. //# sourceMappingURL=babylon.sceneSerializer.js.map
  93817. var BABYLON;
  93818. (function (BABYLON) {
  93819. var ReflectionProbe = /** @class */ (function () {
  93820. function ReflectionProbe(name, size, scene, generateMipMaps) {
  93821. if (generateMipMaps === void 0) { generateMipMaps = true; }
  93822. var _this = this;
  93823. this.name = name;
  93824. this._viewMatrix = BABYLON.Matrix.Identity();
  93825. this._target = BABYLON.Vector3.Zero();
  93826. this._add = BABYLON.Vector3.Zero();
  93827. this._invertYAxis = false;
  93828. this.position = BABYLON.Vector3.Zero();
  93829. this._scene = scene;
  93830. this._scene.reflectionProbes.push(this);
  93831. this._renderTargetTexture = new BABYLON.RenderTargetTexture(name, size, scene, generateMipMaps, true, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT, true);
  93832. this._renderTargetTexture.onBeforeRenderObservable.add(function (faceIndex) {
  93833. switch (faceIndex) {
  93834. case 0:
  93835. _this._add.copyFromFloats(1, 0, 0);
  93836. break;
  93837. case 1:
  93838. _this._add.copyFromFloats(-1, 0, 0);
  93839. break;
  93840. case 2:
  93841. _this._add.copyFromFloats(0, _this._invertYAxis ? 1 : -1, 0);
  93842. break;
  93843. case 3:
  93844. _this._add.copyFromFloats(0, _this._invertYAxis ? -1 : 1, 0);
  93845. break;
  93846. case 4:
  93847. _this._add.copyFromFloats(0, 0, 1);
  93848. break;
  93849. case 5:
  93850. _this._add.copyFromFloats(0, 0, -1);
  93851. break;
  93852. }
  93853. if (_this._attachedMesh) {
  93854. _this.position.copyFrom(_this._attachedMesh.getAbsolutePosition());
  93855. }
  93856. _this.position.addToRef(_this._add, _this._target);
  93857. BABYLON.Matrix.LookAtLHToRef(_this.position, _this._target, BABYLON.Vector3.Up(), _this._viewMatrix);
  93858. scene.setTransformMatrix(_this._viewMatrix, _this._projectionMatrix);
  93859. scene._forcedViewPosition = _this.position;
  93860. });
  93861. this._renderTargetTexture.onAfterUnbindObservable.add(function () {
  93862. scene._forcedViewPosition = null;
  93863. scene.updateTransformMatrix(true);
  93864. });
  93865. if (scene.activeCamera) {
  93866. this._projectionMatrix = BABYLON.Matrix.PerspectiveFovLH(Math.PI / 2, 1, scene.activeCamera.minZ, scene.activeCamera.maxZ);
  93867. }
  93868. }
  93869. Object.defineProperty(ReflectionProbe.prototype, "samples", {
  93870. get: function () {
  93871. return this._renderTargetTexture.samples;
  93872. },
  93873. set: function (value) {
  93874. this._renderTargetTexture.samples = value;
  93875. },
  93876. enumerable: true,
  93877. configurable: true
  93878. });
  93879. Object.defineProperty(ReflectionProbe.prototype, "refreshRate", {
  93880. get: function () {
  93881. return this._renderTargetTexture.refreshRate;
  93882. },
  93883. set: function (value) {
  93884. this._renderTargetTexture.refreshRate = value;
  93885. },
  93886. enumerable: true,
  93887. configurable: true
  93888. });
  93889. ReflectionProbe.prototype.getScene = function () {
  93890. return this._scene;
  93891. };
  93892. Object.defineProperty(ReflectionProbe.prototype, "cubeTexture", {
  93893. get: function () {
  93894. return this._renderTargetTexture;
  93895. },
  93896. enumerable: true,
  93897. configurable: true
  93898. });
  93899. Object.defineProperty(ReflectionProbe.prototype, "renderList", {
  93900. get: function () {
  93901. return this._renderTargetTexture.renderList;
  93902. },
  93903. enumerable: true,
  93904. configurable: true
  93905. });
  93906. ReflectionProbe.prototype.attachToMesh = function (mesh) {
  93907. this._attachedMesh = mesh;
  93908. };
  93909. /**
  93910. * Specifies whether or not the stencil and depth buffer are cleared between two rendering groups.
  93911. *
  93912. * @param renderingGroupId The rendering group id corresponding to its index
  93913. * @param autoClearDepthStencil Automatically clears depth and stencil between groups if true.
  93914. */
  93915. ReflectionProbe.prototype.setRenderingAutoClearDepthStencil = function (renderingGroupId, autoClearDepthStencil) {
  93916. this._renderTargetTexture.setRenderingAutoClearDepthStencil(renderingGroupId, autoClearDepthStencil);
  93917. };
  93918. ReflectionProbe.prototype.dispose = function () {
  93919. var index = this._scene.reflectionProbes.indexOf(this);
  93920. if (index !== -1) {
  93921. // Remove from the scene if found
  93922. this._scene.reflectionProbes.splice(index, 1);
  93923. }
  93924. if (this._renderTargetTexture) {
  93925. this._renderTargetTexture.dispose();
  93926. this._renderTargetTexture = null;
  93927. }
  93928. };
  93929. return ReflectionProbe;
  93930. }());
  93931. BABYLON.ReflectionProbe = ReflectionProbe;
  93932. })(BABYLON || (BABYLON = {}));
  93933. //# sourceMappingURL=babylon.reflectionProbe.js.map
  93934. var BABYLON;
  93935. (function (BABYLON) {
  93936. var Layer = /** @class */ (function () {
  93937. function Layer(name, imgUrl, scene, isBackground, color) {
  93938. this.name = name;
  93939. this.scale = new BABYLON.Vector2(1, 1);
  93940. this.offset = new BABYLON.Vector2(0, 0);
  93941. this.alphaBlendingMode = BABYLON.Engine.ALPHA_COMBINE;
  93942. this.layerMask = 0x0FFFFFFF;
  93943. this._vertexBuffers = {};
  93944. // Events
  93945. /**
  93946. * An event triggered when the layer is disposed.
  93947. */
  93948. this.onDisposeObservable = new BABYLON.Observable();
  93949. /**
  93950. * An event triggered before rendering the scene
  93951. */
  93952. this.onBeforeRenderObservable = new BABYLON.Observable();
  93953. /**
  93954. * An event triggered after rendering the scene
  93955. */
  93956. this.onAfterRenderObservable = new BABYLON.Observable();
  93957. this.texture = imgUrl ? new BABYLON.Texture(imgUrl, scene, true) : null;
  93958. this.isBackground = isBackground === undefined ? true : isBackground;
  93959. this.color = color === undefined ? new BABYLON.Color4(1, 1, 1, 1) : color;
  93960. this._scene = (scene || BABYLON.Engine.LastCreatedScene);
  93961. this._scene.layers.push(this);
  93962. var engine = this._scene.getEngine();
  93963. // VBO
  93964. var vertices = [];
  93965. vertices.push(1, 1);
  93966. vertices.push(-1, 1);
  93967. vertices.push(-1, -1);
  93968. vertices.push(1, -1);
  93969. var vertexBuffer = new BABYLON.VertexBuffer(engine, vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  93970. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = vertexBuffer;
  93971. this._createIndexBuffer();
  93972. // Effects
  93973. this._effect = engine.createEffect("layer", [BABYLON.VertexBuffer.PositionKind], ["textureMatrix", "color", "scale", "offset"], ["textureSampler"], "");
  93974. this._alphaTestEffect = engine.createEffect("layer", [BABYLON.VertexBuffer.PositionKind], ["textureMatrix", "color", "scale", "offset"], ["textureSampler"], "#define ALPHATEST");
  93975. }
  93976. Object.defineProperty(Layer.prototype, "onDispose", {
  93977. set: function (callback) {
  93978. if (this._onDisposeObserver) {
  93979. this.onDisposeObservable.remove(this._onDisposeObserver);
  93980. }
  93981. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  93982. },
  93983. enumerable: true,
  93984. configurable: true
  93985. });
  93986. Object.defineProperty(Layer.prototype, "onBeforeRender", {
  93987. set: function (callback) {
  93988. if (this._onBeforeRenderObserver) {
  93989. this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
  93990. }
  93991. this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
  93992. },
  93993. enumerable: true,
  93994. configurable: true
  93995. });
  93996. Object.defineProperty(Layer.prototype, "onAfterRender", {
  93997. set: function (callback) {
  93998. if (this._onAfterRenderObserver) {
  93999. this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  94000. }
  94001. this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
  94002. },
  94003. enumerable: true,
  94004. configurable: true
  94005. });
  94006. Layer.prototype._createIndexBuffer = function () {
  94007. var engine = this._scene.getEngine();
  94008. // Indices
  94009. var indices = [];
  94010. indices.push(0);
  94011. indices.push(1);
  94012. indices.push(2);
  94013. indices.push(0);
  94014. indices.push(2);
  94015. indices.push(3);
  94016. this._indexBuffer = engine.createIndexBuffer(indices);
  94017. };
  94018. Layer.prototype._rebuild = function () {
  94019. var vb = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  94020. if (vb) {
  94021. vb._rebuild();
  94022. }
  94023. this._createIndexBuffer();
  94024. };
  94025. Layer.prototype.render = function () {
  94026. var currentEffect = this.alphaTest ? this._alphaTestEffect : this._effect;
  94027. // Check
  94028. if (!currentEffect.isReady() || !this.texture || !this.texture.isReady())
  94029. return;
  94030. var engine = this._scene.getEngine();
  94031. this.onBeforeRenderObservable.notifyObservers(this);
  94032. // Render
  94033. engine.enableEffect(currentEffect);
  94034. engine.setState(false);
  94035. // Texture
  94036. currentEffect.setTexture("textureSampler", this.texture);
  94037. currentEffect.setMatrix("textureMatrix", this.texture.getTextureMatrix());
  94038. // Color
  94039. currentEffect.setFloat4("color", this.color.r, this.color.g, this.color.b, this.color.a);
  94040. // Scale / offset
  94041. currentEffect.setVector2("offset", this.offset);
  94042. currentEffect.setVector2("scale", this.scale);
  94043. // VBOs
  94044. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, currentEffect);
  94045. // Draw order
  94046. if (!this.alphaTest) {
  94047. engine.setAlphaMode(this.alphaBlendingMode);
  94048. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  94049. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  94050. }
  94051. else {
  94052. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  94053. }
  94054. this.onAfterRenderObservable.notifyObservers(this);
  94055. };
  94056. Layer.prototype.dispose = function () {
  94057. var vertexBuffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  94058. if (vertexBuffer) {
  94059. vertexBuffer.dispose();
  94060. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  94061. }
  94062. if (this._indexBuffer) {
  94063. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  94064. this._indexBuffer = null;
  94065. }
  94066. if (this.texture) {
  94067. this.texture.dispose();
  94068. this.texture = null;
  94069. }
  94070. // Remove from scene
  94071. var index = this._scene.layers.indexOf(this);
  94072. this._scene.layers.splice(index, 1);
  94073. // Callback
  94074. this.onDisposeObservable.notifyObservers(this);
  94075. this.onDisposeObservable.clear();
  94076. this.onAfterRenderObservable.clear();
  94077. this.onBeforeRenderObservable.clear();
  94078. };
  94079. return Layer;
  94080. }());
  94081. BABYLON.Layer = Layer;
  94082. })(BABYLON || (BABYLON = {}));
  94083. //# sourceMappingURL=babylon.layer.js.map
  94084. var BABYLON;
  94085. (function (BABYLON) {
  94086. var TextureTools = /** @class */ (function () {
  94087. function TextureTools() {
  94088. }
  94089. /**
  94090. * Uses the GPU to create a copy texture rescaled at a given size
  94091. * @param texture Texture to copy from
  94092. * @param width Desired width
  94093. * @param height Desired height
  94094. * @return Generated texture
  94095. */
  94096. TextureTools.CreateResizedCopy = function (texture, width, height, useBilinearMode) {
  94097. if (useBilinearMode === void 0) { useBilinearMode = true; }
  94098. var scene = texture.getScene();
  94099. var engine = scene.getEngine();
  94100. var rtt = new BABYLON.RenderTargetTexture('resized' + texture.name, { width: width, height: height }, scene, !texture.noMipmap, true, texture._texture.type, false, texture._samplingMode, false);
  94101. rtt.wrapU = texture.wrapU;
  94102. rtt.wrapV = texture.wrapV;
  94103. rtt.uOffset = texture.uOffset;
  94104. rtt.vOffset = texture.vOffset;
  94105. rtt.uScale = texture.uScale;
  94106. rtt.vScale = texture.vScale;
  94107. rtt.uAng = texture.uAng;
  94108. rtt.vAng = texture.vAng;
  94109. rtt.wAng = texture.wAng;
  94110. rtt.coordinatesIndex = texture.coordinatesIndex;
  94111. rtt.level = texture.level;
  94112. rtt.anisotropicFilteringLevel = texture.anisotropicFilteringLevel;
  94113. rtt._texture.isReady = false;
  94114. texture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  94115. texture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  94116. var passPostProcess = new BABYLON.PassPostProcess("pass", 1, null, useBilinearMode ? BABYLON.Texture.BILINEAR_SAMPLINGMODE : BABYLON.Texture.NEAREST_SAMPLINGMODE, engine, false, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  94117. passPostProcess.getEffect().executeWhenCompiled(function () {
  94118. passPostProcess.onApply = function (effect) {
  94119. effect.setTexture("textureSampler", texture);
  94120. };
  94121. var internalTexture = rtt.getInternalTexture();
  94122. if (internalTexture) {
  94123. scene.postProcessManager.directRender([passPostProcess], internalTexture);
  94124. engine.unBindFramebuffer(internalTexture);
  94125. rtt.disposeFramebufferObjects();
  94126. passPostProcess.dispose();
  94127. internalTexture.isReady = true;
  94128. }
  94129. });
  94130. return rtt;
  94131. };
  94132. TextureTools.GetEnvironmentBRDFTexture = function (scene) {
  94133. if (!scene._environmentBRDFTexture) {
  94134. var texture = BABYLON.Texture.CreateFromBase64String(this._environmentBRDFBase64Texture, "EnvironmentBRDFTexture", scene, true, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  94135. texture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  94136. texture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  94137. scene._environmentBRDFTexture = texture;
  94138. }
  94139. return scene._environmentBRDFTexture;
  94140. };
  94141. 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=";
  94142. return TextureTools;
  94143. }());
  94144. BABYLON.TextureTools = TextureTools;
  94145. })(BABYLON || (BABYLON = {}));
  94146. //# sourceMappingURL=babylon.textureTools.js.map
  94147. var BABYLON;
  94148. (function (BABYLON) {
  94149. var FramingBehavior = /** @class */ (function () {
  94150. function FramingBehavior() {
  94151. this._mode = FramingBehavior.FitFrustumSidesMode;
  94152. this._radiusScale = 1.0;
  94153. this._positionScale = 0.5;
  94154. this._defaultElevation = 0.3;
  94155. this._elevationReturnTime = 1500;
  94156. this._elevationReturnWaitTime = 1000;
  94157. this._zoomStopsAnimation = false;
  94158. this._framingTime = 1500;
  94159. this._isPointerDown = false;
  94160. this._lastInteractionTime = -Infinity;
  94161. // Framing control
  94162. this._animatables = new Array();
  94163. this._betaIsAnimating = false;
  94164. }
  94165. Object.defineProperty(FramingBehavior.prototype, "name", {
  94166. get: function () {
  94167. return "Framing";
  94168. },
  94169. enumerable: true,
  94170. configurable: true
  94171. });
  94172. Object.defineProperty(FramingBehavior.prototype, "mode", {
  94173. /**
  94174. * Gets current mode used by the behavior.
  94175. */
  94176. get: function () {
  94177. return this._mode;
  94178. },
  94179. /**
  94180. * Sets the current mode used by the behavior
  94181. */
  94182. set: function (mode) {
  94183. this._mode = mode;
  94184. },
  94185. enumerable: true,
  94186. configurable: true
  94187. });
  94188. Object.defineProperty(FramingBehavior.prototype, "radiusScale", {
  94189. /**
  94190. * Gets the scale applied to the radius
  94191. */
  94192. get: function () {
  94193. return this._radiusScale;
  94194. },
  94195. /**
  94196. * Sets the scale applied to the radius (1 by default)
  94197. */
  94198. set: function (radius) {
  94199. this._radiusScale = radius;
  94200. },
  94201. enumerable: true,
  94202. configurable: true
  94203. });
  94204. Object.defineProperty(FramingBehavior.prototype, "positionScale", {
  94205. /**
  94206. * Gets the scale to apply on Y axis to position camera focus. 0.5 by default which means the center of the bounding box.
  94207. */
  94208. get: function () {
  94209. return this._positionScale;
  94210. },
  94211. /**
  94212. * Sets the scale to apply on Y axis to position camera focus. 0.5 by default which means the center of the bounding box.
  94213. */
  94214. set: function (scale) {
  94215. this._positionScale = scale;
  94216. },
  94217. enumerable: true,
  94218. configurable: true
  94219. });
  94220. Object.defineProperty(FramingBehavior.prototype, "defaultElevation", {
  94221. /**
  94222. * Gets the angle above/below the horizontal plane to return to when the return to default elevation idle
  94223. * behaviour is triggered, in radians.
  94224. */
  94225. get: function () {
  94226. return this._defaultElevation;
  94227. },
  94228. /**
  94229. * Sets the angle above/below the horizontal plane to return to when the return to default elevation idle
  94230. * behaviour is triggered, in radians.
  94231. */
  94232. set: function (elevation) {
  94233. this._defaultElevation = elevation;
  94234. },
  94235. enumerable: true,
  94236. configurable: true
  94237. });
  94238. Object.defineProperty(FramingBehavior.prototype, "elevationReturnTime", {
  94239. /**
  94240. * Gets the time (in milliseconds) taken to return to the default beta position.
  94241. * Negative value indicates camera should not return to default.
  94242. */
  94243. get: function () {
  94244. return this._elevationReturnTime;
  94245. },
  94246. /**
  94247. * Sets the time (in milliseconds) taken to return to the default beta position.
  94248. * Negative value indicates camera should not return to default.
  94249. */
  94250. set: function (speed) {
  94251. this._elevationReturnTime = speed;
  94252. },
  94253. enumerable: true,
  94254. configurable: true
  94255. });
  94256. Object.defineProperty(FramingBehavior.prototype, "elevationReturnWaitTime", {
  94257. /**
  94258. * Gets the delay (in milliseconds) taken before the camera returns to the default beta position.
  94259. */
  94260. get: function () {
  94261. return this._elevationReturnWaitTime;
  94262. },
  94263. /**
  94264. * Sets the delay (in milliseconds) taken before the camera returns to the default beta position.
  94265. */
  94266. set: function (time) {
  94267. this._elevationReturnWaitTime = time;
  94268. },
  94269. enumerable: true,
  94270. configurable: true
  94271. });
  94272. Object.defineProperty(FramingBehavior.prototype, "zoomStopsAnimation", {
  94273. /**
  94274. * Gets the flag that indicates if user zooming should stop animation.
  94275. */
  94276. get: function () {
  94277. return this._zoomStopsAnimation;
  94278. },
  94279. /**
  94280. * Sets the flag that indicates if user zooming should stop animation.
  94281. */
  94282. set: function (flag) {
  94283. this._zoomStopsAnimation = flag;
  94284. },
  94285. enumerable: true,
  94286. configurable: true
  94287. });
  94288. Object.defineProperty(FramingBehavior.prototype, "framingTime", {
  94289. /**
  94290. * Gets the transition time when framing the mesh, in milliseconds
  94291. */
  94292. get: function () {
  94293. return this._framingTime;
  94294. },
  94295. /**
  94296. * Sets the transition time when framing the mesh, in milliseconds
  94297. */
  94298. set: function (time) {
  94299. this._framingTime = time;
  94300. },
  94301. enumerable: true,
  94302. configurable: true
  94303. });
  94304. FramingBehavior.prototype.init = function () {
  94305. // Do notihng
  94306. };
  94307. FramingBehavior.prototype.attach = function (camera) {
  94308. var _this = this;
  94309. this._attachedCamera = camera;
  94310. var scene = this._attachedCamera.getScene();
  94311. FramingBehavior.EasingFunction.setEasingMode(FramingBehavior.EasingMode);
  94312. this._onPrePointerObservableObserver = scene.onPrePointerObservable.add(function (pointerInfoPre) {
  94313. if (pointerInfoPre.type === BABYLON.PointerEventTypes.POINTERDOWN) {
  94314. _this._isPointerDown = true;
  94315. return;
  94316. }
  94317. if (pointerInfoPre.type === BABYLON.PointerEventTypes.POINTERUP) {
  94318. _this._isPointerDown = false;
  94319. }
  94320. });
  94321. this._onMeshTargetChangedObserver = camera.onMeshTargetChangedObservable.add(function (mesh) {
  94322. if (mesh) {
  94323. _this.zoomOnMesh(mesh);
  94324. }
  94325. });
  94326. this._onAfterCheckInputsObserver = camera.onAfterCheckInputsObservable.add(function () {
  94327. // Stop the animation if there is user interaction and the animation should stop for this interaction
  94328. _this._applyUserInteraction();
  94329. // Maintain the camera above the ground. If the user pulls the camera beneath the ground plane, lift it
  94330. // back to the default position after a given timeout
  94331. _this._maintainCameraAboveGround();
  94332. });
  94333. };
  94334. FramingBehavior.prototype.detach = function () {
  94335. if (!this._attachedCamera) {
  94336. return;
  94337. }
  94338. var scene = this._attachedCamera.getScene();
  94339. if (this._onPrePointerObservableObserver) {
  94340. scene.onPrePointerObservable.remove(this._onPrePointerObservableObserver);
  94341. }
  94342. if (this._onAfterCheckInputsObserver) {
  94343. this._attachedCamera.onAfterCheckInputsObservable.remove(this._onAfterCheckInputsObserver);
  94344. }
  94345. if (this._onMeshTargetChangedObserver) {
  94346. this._attachedCamera.onMeshTargetChangedObservable.remove(this._onMeshTargetChangedObserver);
  94347. }
  94348. this._attachedCamera = null;
  94349. };
  94350. /**
  94351. * Targets the given mesh and updates zoom level accordingly.
  94352. * @param mesh The mesh to target.
  94353. * @param radius Optional. If a cached radius position already exists, overrides default.
  94354. * @param framingPositionY Position on mesh to center camera focus where 0 corresponds bottom of its bounding box and 1, the top
  94355. * @param focusOnOriginXZ Determines if the camera should focus on 0 in the X and Z axis instead of the mesh
  94356. * @param onAnimationEnd Callback triggered at the end of the framing animation
  94357. */
  94358. FramingBehavior.prototype.zoomOnMesh = function (mesh, focusOnOriginXZ, onAnimationEnd) {
  94359. if (focusOnOriginXZ === void 0) { focusOnOriginXZ = false; }
  94360. if (onAnimationEnd === void 0) { onAnimationEnd = null; }
  94361. mesh.computeWorldMatrix(true);
  94362. var boundingBox = mesh.getBoundingInfo().boundingBox;
  94363. this.zoomOnBoundingInfo(boundingBox.minimumWorld, boundingBox.maximumWorld, focusOnOriginXZ, onAnimationEnd);
  94364. };
  94365. /**
  94366. * Targets the given mesh with its children and updates zoom level accordingly.
  94367. * @param mesh The mesh to target.
  94368. * @param radius Optional. If a cached radius position already exists, overrides default.
  94369. * @param framingPositionY Position on mesh to center camera focus where 0 corresponds bottom of its bounding box and 1, the top
  94370. * @param focusOnOriginXZ Determines if the camera should focus on 0 in the X and Z axis instead of the mesh
  94371. * @param onAnimationEnd Callback triggered at the end of the framing animation
  94372. */
  94373. FramingBehavior.prototype.zoomOnMeshHierarchy = function (mesh, focusOnOriginXZ, onAnimationEnd) {
  94374. if (focusOnOriginXZ === void 0) { focusOnOriginXZ = false; }
  94375. if (onAnimationEnd === void 0) { onAnimationEnd = null; }
  94376. mesh.computeWorldMatrix(true);
  94377. var boundingBox = mesh.getHierarchyBoundingVectors(true);
  94378. this.zoomOnBoundingInfo(boundingBox.min, boundingBox.max, focusOnOriginXZ, onAnimationEnd);
  94379. };
  94380. /**
  94381. * Targets the given meshes with their children and updates zoom level accordingly.
  94382. * @param meshes The mesh to target.
  94383. * @param radius Optional. If a cached radius position already exists, overrides default.
  94384. * @param framingPositionY Position on mesh to center camera focus where 0 corresponds bottom of its bounding box and 1, the top
  94385. * @param focusOnOriginXZ Determines if the camera should focus on 0 in the X and Z axis instead of the mesh
  94386. * @param onAnimationEnd Callback triggered at the end of the framing animation
  94387. */
  94388. FramingBehavior.prototype.zoomOnMeshesHierarchy = function (meshes, focusOnOriginXZ, onAnimationEnd) {
  94389. if (focusOnOriginXZ === void 0) { focusOnOriginXZ = false; }
  94390. if (onAnimationEnd === void 0) { onAnimationEnd = null; }
  94391. var min = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  94392. var max = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  94393. for (var i = 0; i < meshes.length; i++) {
  94394. var boundingInfo = meshes[i].getHierarchyBoundingVectors(true);
  94395. BABYLON.Tools.CheckExtends(boundingInfo.min, min, max);
  94396. BABYLON.Tools.CheckExtends(boundingInfo.max, min, max);
  94397. }
  94398. this.zoomOnBoundingInfo(min, max, focusOnOriginXZ, onAnimationEnd);
  94399. };
  94400. /**
  94401. * Targets the given mesh and updates zoom level accordingly.
  94402. * @param mesh The mesh to target.
  94403. * @param radius Optional. If a cached radius position already exists, overrides default.
  94404. * @param framingPositionY Position on mesh to center camera focus where 0 corresponds bottom of its bounding box and 1, the top
  94405. * @param focusOnOriginXZ Determines if the camera should focus on 0 in the X and Z axis instead of the mesh
  94406. * @param onAnimationEnd Callback triggered at the end of the framing animation
  94407. */
  94408. FramingBehavior.prototype.zoomOnBoundingInfo = function (minimumWorld, maximumWorld, focusOnOriginXZ, onAnimationEnd) {
  94409. var _this = this;
  94410. if (focusOnOriginXZ === void 0) { focusOnOriginXZ = false; }
  94411. if (onAnimationEnd === void 0) { onAnimationEnd = null; }
  94412. var zoomTarget;
  94413. if (!this._attachedCamera) {
  94414. return;
  94415. }
  94416. // Find target by interpolating from bottom of bounding box in world-space to top via framingPositionY
  94417. var bottom = minimumWorld.y;
  94418. var top = maximumWorld.y;
  94419. var zoomTargetY = bottom + (top - bottom) * this._positionScale;
  94420. var radiusWorld = maximumWorld.subtract(minimumWorld).scale(0.5);
  94421. if (focusOnOriginXZ) {
  94422. zoomTarget = new BABYLON.Vector3(0, zoomTargetY, 0);
  94423. }
  94424. else {
  94425. var centerWorld = minimumWorld.add(radiusWorld);
  94426. zoomTarget = new BABYLON.Vector3(centerWorld.x, zoomTargetY, centerWorld.z);
  94427. }
  94428. if (!this._vectorTransition) {
  94429. this._vectorTransition = BABYLON.Animation.CreateAnimation("target", BABYLON.Animation.ANIMATIONTYPE_VECTOR3, 60, FramingBehavior.EasingFunction);
  94430. }
  94431. this._betaIsAnimating = true;
  94432. var animatable = BABYLON.Animation.TransitionTo("target", zoomTarget, this._attachedCamera, this._attachedCamera.getScene(), 60, this._vectorTransition, this._framingTime);
  94433. if (animatable) {
  94434. this._animatables.push(animatable);
  94435. }
  94436. // sets the radius and lower radius bounds
  94437. // Small delta ensures camera is not always at lower zoom limit.
  94438. var radius = 0;
  94439. if (this._mode === FramingBehavior.FitFrustumSidesMode) {
  94440. var position = this._calculateLowerRadiusFromModelBoundingSphere(minimumWorld, maximumWorld);
  94441. this._attachedCamera.lowerRadiusLimit = radiusWorld.length() + this._attachedCamera.minZ;
  94442. radius = position;
  94443. }
  94444. else if (this._mode === FramingBehavior.IgnoreBoundsSizeMode) {
  94445. radius = this._calculateLowerRadiusFromModelBoundingSphere(minimumWorld, maximumWorld);
  94446. if (this._attachedCamera.lowerRadiusLimit === null) {
  94447. this._attachedCamera.lowerRadiusLimit = this._attachedCamera.minZ;
  94448. }
  94449. }
  94450. // Set sensibilities
  94451. var extend = maximumWorld.subtract(minimumWorld).length();
  94452. this._attachedCamera.panningSensibility = 5000 / extend;
  94453. this._attachedCamera.wheelPrecision = 100 / radius;
  94454. // transition to new radius
  94455. if (!this._radiusTransition) {
  94456. this._radiusTransition = BABYLON.Animation.CreateAnimation("radius", BABYLON.Animation.ANIMATIONTYPE_FLOAT, 60, FramingBehavior.EasingFunction);
  94457. }
  94458. animatable = BABYLON.Animation.TransitionTo("radius", radius, this._attachedCamera, this._attachedCamera.getScene(), 60, this._radiusTransition, this._framingTime, function () {
  94459. _this.stopAllAnimations();
  94460. if (onAnimationEnd) {
  94461. onAnimationEnd();
  94462. }
  94463. if (_this._attachedCamera) {
  94464. _this._attachedCamera.storeState();
  94465. }
  94466. });
  94467. if (animatable) {
  94468. this._animatables.push(animatable);
  94469. }
  94470. };
  94471. /**
  94472. * Calculates the lowest radius for the camera based on the bounding box of the mesh.
  94473. * @param mesh The mesh on which to base the calculation. mesh boundingInfo used to estimate necessary
  94474. * frustum width.
  94475. * @return The minimum distance from the primary mesh's center point at which the camera must be kept in order
  94476. * to fully enclose the mesh in the viewing frustum.
  94477. */
  94478. FramingBehavior.prototype._calculateLowerRadiusFromModelBoundingSphere = function (minimumWorld, maximumWorld) {
  94479. var size = maximumWorld.subtract(minimumWorld);
  94480. var boxVectorGlobalDiagonal = size.length();
  94481. var frustumSlope = this._getFrustumSlope();
  94482. // Formula for setting distance
  94483. // (Good explanation: http://stackoverflow.com/questions/2866350/move-camera-to-fit-3d-scene)
  94484. var radiusWithoutFraming = boxVectorGlobalDiagonal * 0.5;
  94485. // Horizon distance
  94486. var radius = radiusWithoutFraming * this._radiusScale;
  94487. var distanceForHorizontalFrustum = radius * Math.sqrt(1.0 + 1.0 / (frustumSlope.x * frustumSlope.x));
  94488. var distanceForVerticalFrustum = radius * Math.sqrt(1.0 + 1.0 / (frustumSlope.y * frustumSlope.y));
  94489. var distance = Math.max(distanceForHorizontalFrustum, distanceForVerticalFrustum);
  94490. var camera = this._attachedCamera;
  94491. if (!camera) {
  94492. return 0;
  94493. }
  94494. if (camera.lowerRadiusLimit && this._mode === FramingBehavior.IgnoreBoundsSizeMode) {
  94495. // Don't exceed the requested limit
  94496. distance = distance < camera.lowerRadiusLimit ? camera.lowerRadiusLimit : distance;
  94497. }
  94498. // Don't exceed the upper radius limit
  94499. if (camera.upperRadiusLimit) {
  94500. distance = distance > camera.upperRadiusLimit ? camera.upperRadiusLimit : distance;
  94501. }
  94502. return distance;
  94503. };
  94504. /**
  94505. * Keeps the camera above the ground plane. If the user pulls the camera below the ground plane, the camera
  94506. * is automatically returned to its default position (expected to be above ground plane).
  94507. */
  94508. FramingBehavior.prototype._maintainCameraAboveGround = function () {
  94509. var _this = this;
  94510. if (this._elevationReturnTime < 0) {
  94511. return;
  94512. }
  94513. var timeSinceInteraction = BABYLON.Tools.Now - this._lastInteractionTime;
  94514. var defaultBeta = Math.PI * 0.5 - this._defaultElevation;
  94515. var limitBeta = Math.PI * 0.5;
  94516. // Bring the camera back up if below the ground plane
  94517. if (this._attachedCamera && !this._betaIsAnimating && this._attachedCamera.beta > limitBeta && timeSinceInteraction >= this._elevationReturnWaitTime) {
  94518. this._betaIsAnimating = true;
  94519. //Transition to new position
  94520. this.stopAllAnimations();
  94521. if (!this._betaTransition) {
  94522. this._betaTransition = BABYLON.Animation.CreateAnimation("beta", BABYLON.Animation.ANIMATIONTYPE_FLOAT, 60, FramingBehavior.EasingFunction);
  94523. }
  94524. var animatabe = BABYLON.Animation.TransitionTo("beta", defaultBeta, this._attachedCamera, this._attachedCamera.getScene(), 60, this._betaTransition, this._elevationReturnTime, function () {
  94525. _this._clearAnimationLocks();
  94526. _this.stopAllAnimations();
  94527. });
  94528. if (animatabe) {
  94529. this._animatables.push(animatabe);
  94530. }
  94531. }
  94532. };
  94533. /**
  94534. * Returns the frustum slope based on the canvas ratio and camera FOV
  94535. * @returns The frustum slope represented as a Vector2 with X and Y slopes
  94536. */
  94537. FramingBehavior.prototype._getFrustumSlope = function () {
  94538. // Calculate the viewport ratio
  94539. // Aspect Ratio is Height/Width.
  94540. var camera = this._attachedCamera;
  94541. if (!camera) {
  94542. return BABYLON.Vector2.Zero();
  94543. }
  94544. var engine = camera.getScene().getEngine();
  94545. var aspectRatio = engine.getAspectRatio(camera);
  94546. // Camera FOV is the vertical field of view (top-bottom) in radians.
  94547. // Slope of the frustum top/bottom planes in view space, relative to the forward vector.
  94548. var frustumSlopeY = Math.tan(camera.fov / 2);
  94549. // Slope of the frustum left/right planes in view space, relative to the forward vector.
  94550. // Provides the amount that one side (e.g. left) of the frustum gets wider for every unit
  94551. // along the forward vector.
  94552. var frustumSlopeX = frustumSlopeY * aspectRatio;
  94553. return new BABYLON.Vector2(frustumSlopeX, frustumSlopeY);
  94554. };
  94555. /**
  94556. * Removes all animation locks. Allows new animations to be added to any of the arcCamera properties.
  94557. */
  94558. FramingBehavior.prototype._clearAnimationLocks = function () {
  94559. this._betaIsAnimating = false;
  94560. };
  94561. /**
  94562. * Applies any current user interaction to the camera. Takes into account maximum alpha rotation.
  94563. */
  94564. FramingBehavior.prototype._applyUserInteraction = function () {
  94565. if (this.isUserIsMoving) {
  94566. this._lastInteractionTime = BABYLON.Tools.Now;
  94567. this.stopAllAnimations();
  94568. this._clearAnimationLocks();
  94569. }
  94570. };
  94571. /**
  94572. * Stops and removes all animations that have been applied to the camera
  94573. */
  94574. FramingBehavior.prototype.stopAllAnimations = function () {
  94575. if (this._attachedCamera) {
  94576. this._attachedCamera.animations = [];
  94577. }
  94578. while (this._animatables.length) {
  94579. if (this._animatables[0]) {
  94580. this._animatables[0].onAnimationEnd = null;
  94581. this._animatables[0].stop();
  94582. }
  94583. this._animatables.shift();
  94584. }
  94585. };
  94586. Object.defineProperty(FramingBehavior.prototype, "isUserIsMoving", {
  94587. /**
  94588. * Gets a value indicating if the user is moving the camera
  94589. */
  94590. get: function () {
  94591. if (!this._attachedCamera) {
  94592. return false;
  94593. }
  94594. return this._attachedCamera.inertialAlphaOffset !== 0 ||
  94595. this._attachedCamera.inertialBetaOffset !== 0 ||
  94596. this._attachedCamera.inertialRadiusOffset !== 0 ||
  94597. this._attachedCamera.inertialPanningX !== 0 ||
  94598. this._attachedCamera.inertialPanningY !== 0 ||
  94599. this._isPointerDown;
  94600. },
  94601. enumerable: true,
  94602. configurable: true
  94603. });
  94604. /**
  94605. * The easing function used by animations
  94606. */
  94607. FramingBehavior.EasingFunction = new BABYLON.ExponentialEase();
  94608. /**
  94609. * The easing mode used by animations
  94610. */
  94611. FramingBehavior.EasingMode = BABYLON.EasingFunction.EASINGMODE_EASEINOUT;
  94612. // Statics
  94613. /**
  94614. * The camera can move all the way towards the mesh.
  94615. */
  94616. FramingBehavior.IgnoreBoundsSizeMode = 0;
  94617. /**
  94618. * The camera is not allowed to zoom closer to the mesh than the point at which the adjusted bounding sphere touches the frustum sides
  94619. */
  94620. FramingBehavior.FitFrustumSidesMode = 1;
  94621. return FramingBehavior;
  94622. }());
  94623. BABYLON.FramingBehavior = FramingBehavior;
  94624. })(BABYLON || (BABYLON = {}));
  94625. //# sourceMappingURL=babylon.framingBehavior.js.map
  94626. var BABYLON;
  94627. (function (BABYLON) {
  94628. /**
  94629. * Add a bouncing effect to an ArcRotateCamera when reaching a specified minimum and maximum radius
  94630. */
  94631. var BouncingBehavior = /** @class */ (function () {
  94632. function BouncingBehavior() {
  94633. /**
  94634. * The duration of the animation, in milliseconds
  94635. */
  94636. this.transitionDuration = 450;
  94637. /**
  94638. * Length of the distance animated by the transition when lower radius is reached
  94639. */
  94640. this.lowerRadiusTransitionRange = 2;
  94641. /**
  94642. * Length of the distance animated by the transition when upper radius is reached
  94643. */
  94644. this.upperRadiusTransitionRange = -2;
  94645. this._autoTransitionRange = false;
  94646. // Animations
  94647. this._radiusIsAnimating = false;
  94648. this._radiusBounceTransition = null;
  94649. this._animatables = new Array();
  94650. }
  94651. Object.defineProperty(BouncingBehavior.prototype, "name", {
  94652. get: function () {
  94653. return "Bouncing";
  94654. },
  94655. enumerable: true,
  94656. configurable: true
  94657. });
  94658. Object.defineProperty(BouncingBehavior.prototype, "autoTransitionRange", {
  94659. /**
  94660. * Gets a value indicating if the lowerRadiusTransitionRange and upperRadiusTransitionRange are defined automatically
  94661. */
  94662. get: function () {
  94663. return this._autoTransitionRange;
  94664. },
  94665. /**
  94666. * Sets a value indicating if the lowerRadiusTransitionRange and upperRadiusTransitionRange are defined automatically
  94667. * Transition ranges will be set to 5% of the bounding box diagonal in world space
  94668. */
  94669. set: function (value) {
  94670. var _this = this;
  94671. if (this._autoTransitionRange === value) {
  94672. return;
  94673. }
  94674. this._autoTransitionRange = value;
  94675. var camera = this._attachedCamera;
  94676. if (!camera) {
  94677. return;
  94678. }
  94679. if (value) {
  94680. this._onMeshTargetChangedObserver = camera.onMeshTargetChangedObservable.add(function (mesh) {
  94681. if (!mesh) {
  94682. return;
  94683. }
  94684. mesh.computeWorldMatrix(true);
  94685. var diagonal = mesh.getBoundingInfo().diagonalLength;
  94686. _this.lowerRadiusTransitionRange = diagonal * 0.05;
  94687. _this.upperRadiusTransitionRange = diagonal * 0.05;
  94688. });
  94689. }
  94690. else if (this._onMeshTargetChangedObserver) {
  94691. camera.onMeshTargetChangedObservable.remove(this._onMeshTargetChangedObserver);
  94692. }
  94693. },
  94694. enumerable: true,
  94695. configurable: true
  94696. });
  94697. BouncingBehavior.prototype.init = function () {
  94698. // Do notihng
  94699. };
  94700. BouncingBehavior.prototype.attach = function (camera) {
  94701. var _this = this;
  94702. this._attachedCamera = camera;
  94703. this._onAfterCheckInputsObserver = camera.onAfterCheckInputsObservable.add(function () {
  94704. if (!_this._attachedCamera) {
  94705. return;
  94706. }
  94707. // Add the bounce animation to the lower radius limit
  94708. if (_this._isRadiusAtLimit(_this._attachedCamera.lowerRadiusLimit)) {
  94709. _this._applyBoundRadiusAnimation(_this.lowerRadiusTransitionRange);
  94710. }
  94711. // Add the bounce animation to the upper radius limit
  94712. if (_this._isRadiusAtLimit(_this._attachedCamera.upperRadiusLimit)) {
  94713. _this._applyBoundRadiusAnimation(_this.upperRadiusTransitionRange);
  94714. }
  94715. });
  94716. };
  94717. BouncingBehavior.prototype.detach = function () {
  94718. if (!this._attachedCamera) {
  94719. return;
  94720. }
  94721. if (this._onAfterCheckInputsObserver) {
  94722. this._attachedCamera.onAfterCheckInputsObservable.remove(this._onAfterCheckInputsObserver);
  94723. }
  94724. if (this._onMeshTargetChangedObserver) {
  94725. this._attachedCamera.onMeshTargetChangedObservable.remove(this._onMeshTargetChangedObserver);
  94726. }
  94727. this._attachedCamera = null;
  94728. };
  94729. /**
  94730. * Checks if the camera radius is at the specified limit. Takes into account animation locks.
  94731. * @param radiusLimit The limit to check against.
  94732. * @return Bool to indicate if at limit.
  94733. */
  94734. BouncingBehavior.prototype._isRadiusAtLimit = function (radiusLimit) {
  94735. if (!this._attachedCamera) {
  94736. return false;
  94737. }
  94738. if (this._attachedCamera.radius === radiusLimit && !this._radiusIsAnimating) {
  94739. return true;
  94740. }
  94741. return false;
  94742. };
  94743. /**
  94744. * Applies an animation to the radius of the camera, extending by the radiusDelta.
  94745. * @param radiusDelta The delta by which to animate to. Can be negative.
  94746. */
  94747. BouncingBehavior.prototype._applyBoundRadiusAnimation = function (radiusDelta) {
  94748. var _this = this;
  94749. if (!this._attachedCamera) {
  94750. return;
  94751. }
  94752. if (!this._radiusBounceTransition) {
  94753. BouncingBehavior.EasingFunction.setEasingMode(BouncingBehavior.EasingMode);
  94754. this._radiusBounceTransition = BABYLON.Animation.CreateAnimation("radius", BABYLON.Animation.ANIMATIONTYPE_FLOAT, 60, BouncingBehavior.EasingFunction);
  94755. }
  94756. // Prevent zoom until bounce has completed
  94757. this._cachedWheelPrecision = this._attachedCamera.wheelPrecision;
  94758. this._attachedCamera.wheelPrecision = Infinity;
  94759. this._attachedCamera.inertialRadiusOffset = 0;
  94760. // Animate to the radius limit
  94761. this.stopAllAnimations();
  94762. this._radiusIsAnimating = true;
  94763. var animatable = BABYLON.Animation.TransitionTo("radius", this._attachedCamera.radius + radiusDelta, this._attachedCamera, this._attachedCamera.getScene(), 60, this._radiusBounceTransition, this.transitionDuration, function () { return _this._clearAnimationLocks(); });
  94764. if (animatable) {
  94765. this._animatables.push(animatable);
  94766. }
  94767. };
  94768. /**
  94769. * Removes all animation locks. Allows new animations to be added to any of the camera properties.
  94770. */
  94771. BouncingBehavior.prototype._clearAnimationLocks = function () {
  94772. this._radiusIsAnimating = false;
  94773. if (this._attachedCamera) {
  94774. this._attachedCamera.wheelPrecision = this._cachedWheelPrecision;
  94775. }
  94776. };
  94777. /**
  94778. * Stops and removes all animations that have been applied to the camera
  94779. */
  94780. BouncingBehavior.prototype.stopAllAnimations = function () {
  94781. if (this._attachedCamera) {
  94782. this._attachedCamera.animations = [];
  94783. }
  94784. while (this._animatables.length) {
  94785. this._animatables[0].onAnimationEnd = null;
  94786. this._animatables[0].stop();
  94787. this._animatables.shift();
  94788. }
  94789. };
  94790. /**
  94791. * The easing function used by animations
  94792. */
  94793. BouncingBehavior.EasingFunction = new BABYLON.BackEase(0.3);
  94794. /**
  94795. * The easing mode used by animations
  94796. */
  94797. BouncingBehavior.EasingMode = BABYLON.EasingFunction.EASINGMODE_EASEOUT;
  94798. return BouncingBehavior;
  94799. }());
  94800. BABYLON.BouncingBehavior = BouncingBehavior;
  94801. })(BABYLON || (BABYLON = {}));
  94802. //# sourceMappingURL=babylon.bouncingBehavior.js.map
  94803. var BABYLON;
  94804. (function (BABYLON) {
  94805. var AutoRotationBehavior = /** @class */ (function () {
  94806. function AutoRotationBehavior() {
  94807. this._zoomStopsAnimation = false;
  94808. this._idleRotationSpeed = 0.05;
  94809. this._idleRotationWaitTime = 2000;
  94810. this._idleRotationSpinupTime = 2000;
  94811. this._isPointerDown = false;
  94812. this._lastFrameTime = null;
  94813. this._lastInteractionTime = -Infinity;
  94814. this._cameraRotationSpeed = 0;
  94815. this._lastFrameRadius = 0;
  94816. }
  94817. Object.defineProperty(AutoRotationBehavior.prototype, "name", {
  94818. get: function () {
  94819. return "AutoRotation";
  94820. },
  94821. enumerable: true,
  94822. configurable: true
  94823. });
  94824. Object.defineProperty(AutoRotationBehavior.prototype, "zoomStopsAnimation", {
  94825. /**
  94826. * Gets the flag that indicates if user zooming should stop animation.
  94827. */
  94828. get: function () {
  94829. return this._zoomStopsAnimation;
  94830. },
  94831. /**
  94832. * Sets the flag that indicates if user zooming should stop animation.
  94833. */
  94834. set: function (flag) {
  94835. this._zoomStopsAnimation = flag;
  94836. },
  94837. enumerable: true,
  94838. configurable: true
  94839. });
  94840. Object.defineProperty(AutoRotationBehavior.prototype, "idleRotationSpeed", {
  94841. /**
  94842. * Gets the default speed at which the camera rotates around the model.
  94843. */
  94844. get: function () {
  94845. return this._idleRotationSpeed;
  94846. },
  94847. /**
  94848. * Sets the default speed at which the camera rotates around the model.
  94849. */
  94850. set: function (speed) {
  94851. this._idleRotationSpeed = speed;
  94852. },
  94853. enumerable: true,
  94854. configurable: true
  94855. });
  94856. Object.defineProperty(AutoRotationBehavior.prototype, "idleRotationWaitTime", {
  94857. /**
  94858. * Gets the time (milliseconds) to wait after user interaction before the camera starts rotating.
  94859. */
  94860. get: function () {
  94861. return this._idleRotationWaitTime;
  94862. },
  94863. /**
  94864. * Sets the time (in milliseconds) to wait after user interaction before the camera starts rotating.
  94865. */
  94866. set: function (time) {
  94867. this._idleRotationWaitTime = time;
  94868. },
  94869. enumerable: true,
  94870. configurable: true
  94871. });
  94872. Object.defineProperty(AutoRotationBehavior.prototype, "idleRotationSpinupTime", {
  94873. /**
  94874. * Gets the time (milliseconds) to take to spin up to the full idle rotation speed.
  94875. */
  94876. get: function () {
  94877. return this._idleRotationSpinupTime;
  94878. },
  94879. /**
  94880. * Sets the time (milliseconds) to take to spin up to the full idle rotation speed.
  94881. */
  94882. set: function (time) {
  94883. this._idleRotationSpinupTime = time;
  94884. },
  94885. enumerable: true,
  94886. configurable: true
  94887. });
  94888. Object.defineProperty(AutoRotationBehavior.prototype, "rotationInProgress", {
  94889. /**
  94890. * Gets a value indicating if the camera is currently rotating because of this behavior
  94891. */
  94892. get: function () {
  94893. return Math.abs(this._cameraRotationSpeed) > 0;
  94894. },
  94895. enumerable: true,
  94896. configurable: true
  94897. });
  94898. AutoRotationBehavior.prototype.init = function () {
  94899. // Do notihng
  94900. };
  94901. AutoRotationBehavior.prototype.attach = function (camera) {
  94902. var _this = this;
  94903. this._attachedCamera = camera;
  94904. var scene = this._attachedCamera.getScene();
  94905. this._onPrePointerObservableObserver = scene.onPrePointerObservable.add(function (pointerInfoPre) {
  94906. if (pointerInfoPre.type === BABYLON.PointerEventTypes.POINTERDOWN) {
  94907. _this._isPointerDown = true;
  94908. return;
  94909. }
  94910. if (pointerInfoPre.type === BABYLON.PointerEventTypes.POINTERUP) {
  94911. _this._isPointerDown = false;
  94912. }
  94913. });
  94914. this._onAfterCheckInputsObserver = camera.onAfterCheckInputsObservable.add(function () {
  94915. var now = BABYLON.Tools.Now;
  94916. var dt = 0;
  94917. if (_this._lastFrameTime != null) {
  94918. dt = now - _this._lastFrameTime;
  94919. }
  94920. _this._lastFrameTime = now;
  94921. // Stop the animation if there is user interaction and the animation should stop for this interaction
  94922. _this._applyUserInteraction();
  94923. var timeToRotation = now - _this._lastInteractionTime - _this._idleRotationWaitTime;
  94924. var scale = Math.max(Math.min(timeToRotation / (_this._idleRotationSpinupTime), 1), 0);
  94925. _this._cameraRotationSpeed = _this._idleRotationSpeed * scale;
  94926. // Step camera rotation by rotation speed
  94927. if (_this._attachedCamera) {
  94928. _this._attachedCamera.alpha -= _this._cameraRotationSpeed * (dt / 1000);
  94929. }
  94930. });
  94931. };
  94932. AutoRotationBehavior.prototype.detach = function () {
  94933. if (!this._attachedCamera) {
  94934. return;
  94935. }
  94936. var scene = this._attachedCamera.getScene();
  94937. if (this._onPrePointerObservableObserver) {
  94938. scene.onPrePointerObservable.remove(this._onPrePointerObservableObserver);
  94939. }
  94940. this._attachedCamera.onAfterCheckInputsObservable.remove(this._onAfterCheckInputsObserver);
  94941. this._attachedCamera = null;
  94942. };
  94943. /**
  94944. * Returns true if user is scrolling.
  94945. * @return true if user is scrolling.
  94946. */
  94947. AutoRotationBehavior.prototype._userIsZooming = function () {
  94948. if (!this._attachedCamera) {
  94949. return false;
  94950. }
  94951. return this._attachedCamera.inertialRadiusOffset !== 0;
  94952. };
  94953. AutoRotationBehavior.prototype._shouldAnimationStopForInteraction = function () {
  94954. if (!this._attachedCamera) {
  94955. return false;
  94956. }
  94957. var zoomHasHitLimit = false;
  94958. if (this._lastFrameRadius === this._attachedCamera.radius && this._attachedCamera.inertialRadiusOffset !== 0) {
  94959. zoomHasHitLimit = true;
  94960. }
  94961. // Update the record of previous radius - works as an approx. indicator of hitting radius limits
  94962. this._lastFrameRadius = this._attachedCamera.radius;
  94963. return this._zoomStopsAnimation ? zoomHasHitLimit : this._userIsZooming();
  94964. };
  94965. /**
  94966. * Applies any current user interaction to the camera. Takes into account maximum alpha rotation.
  94967. */
  94968. AutoRotationBehavior.prototype._applyUserInteraction = function () {
  94969. if (this._userIsMoving() && !this._shouldAnimationStopForInteraction()) {
  94970. this._lastInteractionTime = BABYLON.Tools.Now;
  94971. }
  94972. };
  94973. // Tools
  94974. AutoRotationBehavior.prototype._userIsMoving = function () {
  94975. if (!this._attachedCamera) {
  94976. return false;
  94977. }
  94978. return this._attachedCamera.inertialAlphaOffset !== 0 ||
  94979. this._attachedCamera.inertialBetaOffset !== 0 ||
  94980. this._attachedCamera.inertialRadiusOffset !== 0 ||
  94981. this._attachedCamera.inertialPanningX !== 0 ||
  94982. this._attachedCamera.inertialPanningY !== 0 ||
  94983. this._isPointerDown;
  94984. };
  94985. return AutoRotationBehavior;
  94986. }());
  94987. BABYLON.AutoRotationBehavior = AutoRotationBehavior;
  94988. })(BABYLON || (BABYLON = {}));
  94989. //# sourceMappingURL=babylon.autoRotationBehavior.js.map
  94990. var BABYLON;
  94991. (function (BABYLON) {
  94992. var NullEngineOptions = /** @class */ (function () {
  94993. function NullEngineOptions() {
  94994. this.renderWidth = 512;
  94995. this.renderHeight = 256;
  94996. this.textureSize = 512;
  94997. this.deterministicLockstep = false;
  94998. this.lockstepMaxSteps = 4;
  94999. }
  95000. return NullEngineOptions;
  95001. }());
  95002. BABYLON.NullEngineOptions = NullEngineOptions;
  95003. /**
  95004. * The null engine class provides support for headless version of babylon.js.
  95005. * This can be used in server side scenario or for testing purposes
  95006. */
  95007. var NullEngine = /** @class */ (function (_super) {
  95008. __extends(NullEngine, _super);
  95009. function NullEngine(options) {
  95010. if (options === void 0) { options = new NullEngineOptions(); }
  95011. var _this = _super.call(this, null) || this;
  95012. if (options.deterministicLockstep === undefined) {
  95013. options.deterministicLockstep = false;
  95014. }
  95015. if (options.lockstepMaxSteps === undefined) {
  95016. options.lockstepMaxSteps = 4;
  95017. }
  95018. _this._options = options;
  95019. // Init caps
  95020. // We consider we are on a webgl1 capable device
  95021. _this._caps = new BABYLON.EngineCapabilities();
  95022. _this._caps.maxTexturesImageUnits = 16;
  95023. _this._caps.maxVertexTextureImageUnits = 16;
  95024. _this._caps.maxTextureSize = 512;
  95025. _this._caps.maxCubemapTextureSize = 512;
  95026. _this._caps.maxRenderTextureSize = 512;
  95027. _this._caps.maxVertexAttribs = 16;
  95028. _this._caps.maxVaryingVectors = 16;
  95029. _this._caps.maxFragmentUniformVectors = 16;
  95030. _this._caps.maxVertexUniformVectors = 16;
  95031. // Extensions
  95032. _this._caps.standardDerivatives = false;
  95033. _this._caps.astc = null;
  95034. _this._caps.s3tc = null;
  95035. _this._caps.pvrtc = null;
  95036. _this._caps.etc1 = null;
  95037. _this._caps.etc2 = null;
  95038. _this._caps.textureAnisotropicFilterExtension = null;
  95039. _this._caps.maxAnisotropy = 0;
  95040. _this._caps.uintIndices = false;
  95041. _this._caps.fragmentDepthSupported = false;
  95042. _this._caps.highPrecisionShaderSupported = true;
  95043. _this._caps.colorBufferFloat = false;
  95044. _this._caps.textureFloat = false;
  95045. _this._caps.textureFloatLinearFiltering = false;
  95046. _this._caps.textureFloatRender = false;
  95047. _this._caps.textureHalfFloat = false;
  95048. _this._caps.textureHalfFloatLinearFiltering = false;
  95049. _this._caps.textureHalfFloatRender = false;
  95050. _this._caps.textureLOD = false;
  95051. _this._caps.drawBuffersExtension = false;
  95052. _this._caps.depthTextureExtension = false;
  95053. _this._caps.vertexArrayObject = false;
  95054. _this._caps.instancedArrays = false;
  95055. BABYLON.Tools.Log("Babylon.js null engine (v" + BABYLON.Engine.Version + ") launched");
  95056. // Wrappers
  95057. if (typeof URL === "undefined") {
  95058. URL = {
  95059. createObjectURL: function () { },
  95060. revokeObjectURL: function () { }
  95061. };
  95062. }
  95063. if (typeof Blob === "undefined") {
  95064. Blob = function () { };
  95065. }
  95066. return _this;
  95067. }
  95068. NullEngine.prototype.isDeterministicLockStep = function () {
  95069. return this._options.deterministicLockstep;
  95070. };
  95071. NullEngine.prototype.getLockstepMaxSteps = function () {
  95072. return this._options.lockstepMaxSteps;
  95073. };
  95074. NullEngine.prototype.getHardwareScalingLevel = function () {
  95075. return 1.0;
  95076. };
  95077. NullEngine.prototype.createVertexBuffer = function (vertices) {
  95078. return {
  95079. capacity: 0,
  95080. references: 1,
  95081. is32Bits: false
  95082. };
  95083. };
  95084. NullEngine.prototype.createIndexBuffer = function (indices) {
  95085. return {
  95086. capacity: 0,
  95087. references: 1,
  95088. is32Bits: false
  95089. };
  95090. };
  95091. NullEngine.prototype.clear = function (color, backBuffer, depth, stencil) {
  95092. if (stencil === void 0) { stencil = false; }
  95093. };
  95094. NullEngine.prototype.getRenderWidth = function (useScreen) {
  95095. if (useScreen === void 0) { useScreen = false; }
  95096. if (!useScreen && this._currentRenderTarget) {
  95097. return this._currentRenderTarget.width;
  95098. }
  95099. return this._options.renderWidth;
  95100. };
  95101. NullEngine.prototype.getRenderHeight = function (useScreen) {
  95102. if (useScreen === void 0) { useScreen = false; }
  95103. if (!useScreen && this._currentRenderTarget) {
  95104. return this._currentRenderTarget.height;
  95105. }
  95106. return this._options.renderHeight;
  95107. };
  95108. NullEngine.prototype.setViewport = function (viewport, requiredWidth, requiredHeight) {
  95109. this._cachedViewport = viewport;
  95110. };
  95111. NullEngine.prototype.createShaderProgram = function (vertexCode, fragmentCode, defines, context) {
  95112. return {
  95113. transformFeedback: null,
  95114. __SPECTOR_rebuildProgram: null
  95115. };
  95116. };
  95117. NullEngine.prototype.getUniforms = function (shaderProgram, uniformsNames) {
  95118. return [];
  95119. };
  95120. NullEngine.prototype.getAttributes = function (shaderProgram, attributesNames) {
  95121. return [];
  95122. };
  95123. NullEngine.prototype.bindSamplers = function (effect) {
  95124. this._currentEffect = null;
  95125. };
  95126. NullEngine.prototype.enableEffect = function (effect) {
  95127. this._currentEffect = effect;
  95128. if (effect.onBind) {
  95129. effect.onBind(effect);
  95130. }
  95131. effect.onBindObservable.notifyObservers(effect);
  95132. };
  95133. NullEngine.prototype.setState = function (culling, zOffset, force, reverseSide) {
  95134. if (zOffset === void 0) { zOffset = 0; }
  95135. if (reverseSide === void 0) { reverseSide = false; }
  95136. };
  95137. NullEngine.prototype.setIntArray = function (uniform, array) {
  95138. };
  95139. NullEngine.prototype.setIntArray2 = function (uniform, array) {
  95140. };
  95141. NullEngine.prototype.setIntArray3 = function (uniform, array) {
  95142. };
  95143. NullEngine.prototype.setIntArray4 = function (uniform, array) {
  95144. };
  95145. NullEngine.prototype.setFloatArray = function (uniform, array) {
  95146. };
  95147. NullEngine.prototype.setFloatArray2 = function (uniform, array) {
  95148. };
  95149. NullEngine.prototype.setFloatArray3 = function (uniform, array) {
  95150. };
  95151. NullEngine.prototype.setFloatArray4 = function (uniform, array) {
  95152. };
  95153. NullEngine.prototype.setArray = function (uniform, array) {
  95154. };
  95155. NullEngine.prototype.setArray2 = function (uniform, array) {
  95156. };
  95157. NullEngine.prototype.setArray3 = function (uniform, array) {
  95158. };
  95159. NullEngine.prototype.setArray4 = function (uniform, array) {
  95160. };
  95161. NullEngine.prototype.setMatrices = function (uniform, matrices) {
  95162. };
  95163. NullEngine.prototype.setMatrix = function (uniform, matrix) {
  95164. };
  95165. NullEngine.prototype.setMatrix3x3 = function (uniform, matrix) {
  95166. };
  95167. NullEngine.prototype.setMatrix2x2 = function (uniform, matrix) {
  95168. };
  95169. NullEngine.prototype.setFloat = function (uniform, value) {
  95170. };
  95171. NullEngine.prototype.setFloat2 = function (uniform, x, y) {
  95172. };
  95173. NullEngine.prototype.setFloat3 = function (uniform, x, y, z) {
  95174. };
  95175. NullEngine.prototype.setBool = function (uniform, bool) {
  95176. };
  95177. NullEngine.prototype.setFloat4 = function (uniform, x, y, z, w) {
  95178. };
  95179. NullEngine.prototype.setColor3 = function (uniform, color3) {
  95180. };
  95181. NullEngine.prototype.setColor4 = function (uniform, color3, alpha) {
  95182. };
  95183. NullEngine.prototype.setAlphaMode = function (mode, noDepthWriteChange) {
  95184. if (noDepthWriteChange === void 0) { noDepthWriteChange = false; }
  95185. if (this._alphaMode === mode) {
  95186. return;
  95187. }
  95188. this._alphaState.alphaBlend = (mode !== BABYLON.Engine.ALPHA_DISABLE);
  95189. if (!noDepthWriteChange) {
  95190. this.setDepthWrite(mode === BABYLON.Engine.ALPHA_DISABLE);
  95191. }
  95192. this._alphaMode = mode;
  95193. };
  95194. NullEngine.prototype.bindBuffers = function (vertexBuffers, indexBuffer, effect) {
  95195. };
  95196. NullEngine.prototype.wipeCaches = function (bruteForce) {
  95197. if (this.preventCacheWipeBetweenFrames) {
  95198. return;
  95199. }
  95200. this.resetTextureCache();
  95201. this._currentEffect = null;
  95202. if (bruteForce) {
  95203. this._currentProgram = null;
  95204. this._stencilState.reset();
  95205. this._depthCullingState.reset();
  95206. this._alphaState.reset();
  95207. }
  95208. this._cachedVertexBuffers = null;
  95209. this._cachedIndexBuffer = null;
  95210. this._cachedEffectForVertexBuffers = null;
  95211. };
  95212. NullEngine.prototype.draw = function (useTriangles, indexStart, indexCount, instancesCount) {
  95213. };
  95214. NullEngine.prototype.drawElementsType = function (fillMode, indexStart, indexCount, instancesCount) {
  95215. };
  95216. NullEngine.prototype.drawArraysType = function (fillMode, verticesStart, verticesCount, instancesCount) {
  95217. };
  95218. NullEngine.prototype._createTexture = function () {
  95219. return {};
  95220. };
  95221. NullEngine.prototype._releaseTexture = function (texture) {
  95222. };
  95223. NullEngine.prototype.createTexture = function (urlArg, noMipmap, invertY, scene, samplingMode, onLoad, onError, buffer, fallBack, format) {
  95224. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  95225. if (onLoad === void 0) { onLoad = null; }
  95226. if (onError === void 0) { onError = null; }
  95227. if (buffer === void 0) { buffer = null; }
  95228. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_URL);
  95229. var url = String(urlArg);
  95230. texture.url = url;
  95231. texture.generateMipMaps = !noMipmap;
  95232. texture.samplingMode = samplingMode;
  95233. texture.invertY = invertY;
  95234. texture.baseWidth = this._options.textureSize;
  95235. texture.baseHeight = this._options.textureSize;
  95236. texture.width = this._options.textureSize;
  95237. texture.height = this._options.textureSize;
  95238. if (format) {
  95239. texture.format = format;
  95240. }
  95241. texture.isReady = true;
  95242. if (onLoad) {
  95243. onLoad();
  95244. }
  95245. return texture;
  95246. };
  95247. NullEngine.prototype.createRenderTargetTexture = function (size, options) {
  95248. var fullOptions = new BABYLON.RenderTargetCreationOptions();
  95249. if (options !== undefined && typeof options === "object") {
  95250. fullOptions.generateMipMaps = options.generateMipMaps;
  95251. fullOptions.generateDepthBuffer = options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  95252. fullOptions.generateStencilBuffer = fullOptions.generateDepthBuffer && options.generateStencilBuffer;
  95253. fullOptions.type = options.type === undefined ? BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT : options.type;
  95254. fullOptions.samplingMode = options.samplingMode === undefined ? BABYLON.Texture.TRILINEAR_SAMPLINGMODE : options.samplingMode;
  95255. }
  95256. else {
  95257. fullOptions.generateMipMaps = options;
  95258. fullOptions.generateDepthBuffer = true;
  95259. fullOptions.generateStencilBuffer = false;
  95260. fullOptions.type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  95261. fullOptions.samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE;
  95262. }
  95263. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_RENDERTARGET);
  95264. var width = size.width || size;
  95265. var height = size.height || size;
  95266. texture._depthStencilBuffer = {};
  95267. texture._framebuffer = {};
  95268. texture.baseWidth = width;
  95269. texture.baseHeight = height;
  95270. texture.width = width;
  95271. texture.height = height;
  95272. texture.isReady = true;
  95273. texture.samples = 1;
  95274. texture.generateMipMaps = fullOptions.generateMipMaps ? true : false;
  95275. texture.samplingMode = fullOptions.samplingMode;
  95276. texture.type = fullOptions.type;
  95277. texture._generateDepthBuffer = fullOptions.generateDepthBuffer;
  95278. texture._generateStencilBuffer = fullOptions.generateStencilBuffer ? true : false;
  95279. return texture;
  95280. };
  95281. NullEngine.prototype.updateTextureSamplingMode = function (samplingMode, texture) {
  95282. texture.samplingMode = samplingMode;
  95283. };
  95284. NullEngine.prototype.bindFramebuffer = function (texture, faceIndex, requiredWidth, requiredHeight, forceFullscreenViewport) {
  95285. if (this._currentRenderTarget) {
  95286. this.unBindFramebuffer(this._currentRenderTarget);
  95287. }
  95288. this._currentRenderTarget = texture;
  95289. this._currentFramebuffer = texture._MSAAFramebuffer ? texture._MSAAFramebuffer : texture._framebuffer;
  95290. if (this._cachedViewport && !forceFullscreenViewport) {
  95291. this.setViewport(this._cachedViewport, requiredWidth, requiredHeight);
  95292. }
  95293. };
  95294. NullEngine.prototype.unBindFramebuffer = function (texture, disableGenerateMipMaps, onBeforeUnbind) {
  95295. if (disableGenerateMipMaps === void 0) { disableGenerateMipMaps = false; }
  95296. this._currentRenderTarget = null;
  95297. if (onBeforeUnbind) {
  95298. if (texture._MSAAFramebuffer) {
  95299. this._currentFramebuffer = texture._framebuffer;
  95300. }
  95301. onBeforeUnbind();
  95302. }
  95303. this._currentFramebuffer = null;
  95304. };
  95305. NullEngine.prototype.createDynamicVertexBuffer = function (vertices) {
  95306. var vbo = {
  95307. capacity: 1,
  95308. references: 1,
  95309. is32Bits: false
  95310. };
  95311. return vbo;
  95312. };
  95313. NullEngine.prototype.updateDynamicIndexBuffer = function (indexBuffer, indices, offset) {
  95314. if (offset === void 0) { offset = 0; }
  95315. };
  95316. /**
  95317. * Updates a dynamic vertex buffer.
  95318. * @param vertexBuffer the vertex buffer to update
  95319. * @param data the data used to update the vertex buffer
  95320. * @param byteOffset the byte offset of the data (optional)
  95321. * @param byteLength the byte length of the data (optional)
  95322. */
  95323. NullEngine.prototype.updateDynamicVertexBuffer = function (vertexBuffer, vertices, byteOffset, byteLength) {
  95324. };
  95325. NullEngine.prototype._bindTextureDirectly = function (target, texture) {
  95326. if (this._boundTexturesCache[this._activeChannel] !== texture) {
  95327. this._boundTexturesCache[this._activeChannel] = texture;
  95328. }
  95329. };
  95330. NullEngine.prototype._bindTexture = function (channel, texture) {
  95331. if (channel < 0) {
  95332. return;
  95333. }
  95334. this._bindTextureDirectly(0, texture);
  95335. };
  95336. NullEngine.prototype._releaseBuffer = function (buffer) {
  95337. buffer.references--;
  95338. if (buffer.references === 0) {
  95339. return true;
  95340. }
  95341. return false;
  95342. };
  95343. return NullEngine;
  95344. }(BABYLON.Engine));
  95345. BABYLON.NullEngine = NullEngine;
  95346. })(BABYLON || (BABYLON = {}));
  95347. //# sourceMappingURL=babylon.nullEngine.js.map
  95348. var BABYLON;
  95349. (function (BABYLON) {
  95350. /**
  95351. * This class can be used to get instrumentation data from a Babylon engine
  95352. */
  95353. var EngineInstrumentation = /** @class */ (function () {
  95354. function EngineInstrumentation(engine) {
  95355. this.engine = engine;
  95356. this._captureGPUFrameTime = false;
  95357. this._gpuFrameTime = new BABYLON.PerfCounter();
  95358. this._captureShaderCompilationTime = false;
  95359. this._shaderCompilationTime = new BABYLON.PerfCounter();
  95360. // Observers
  95361. this._onBeginFrameObserver = null;
  95362. this._onEndFrameObserver = null;
  95363. this._onBeforeShaderCompilationObserver = null;
  95364. this._onAfterShaderCompilationObserver = null;
  95365. }
  95366. Object.defineProperty(EngineInstrumentation.prototype, "gpuFrameTimeCounter", {
  95367. // Properties
  95368. /**
  95369. * Gets the perf counter used for GPU frame time
  95370. */
  95371. get: function () {
  95372. return this._gpuFrameTime;
  95373. },
  95374. enumerable: true,
  95375. configurable: true
  95376. });
  95377. Object.defineProperty(EngineInstrumentation.prototype, "captureGPUFrameTime", {
  95378. /**
  95379. * Gets the GPU frame time capture status
  95380. */
  95381. get: function () {
  95382. return this._captureGPUFrameTime;
  95383. },
  95384. /**
  95385. * Enable or disable the GPU frame time capture
  95386. */
  95387. set: function (value) {
  95388. var _this = this;
  95389. if (value === this._captureGPUFrameTime) {
  95390. return;
  95391. }
  95392. this._captureGPUFrameTime = value;
  95393. if (value) {
  95394. this._onBeginFrameObserver = this.engine.onBeginFrameObservable.add(function () {
  95395. if (!_this._gpuFrameTimeToken) {
  95396. _this._gpuFrameTimeToken = _this.engine.startTimeQuery();
  95397. }
  95398. });
  95399. this._onEndFrameObserver = this.engine.onEndFrameObservable.add(function () {
  95400. if (!_this._gpuFrameTimeToken) {
  95401. return;
  95402. }
  95403. var time = _this.engine.endTimeQuery(_this._gpuFrameTimeToken);
  95404. if (time > -1) {
  95405. _this._gpuFrameTimeToken = null;
  95406. _this._gpuFrameTime.fetchNewFrame();
  95407. _this._gpuFrameTime.addCount(time, true);
  95408. }
  95409. });
  95410. }
  95411. else {
  95412. this.engine.onBeginFrameObservable.remove(this._onBeginFrameObserver);
  95413. this._onBeginFrameObserver = null;
  95414. this.engine.onEndFrameObservable.remove(this._onEndFrameObserver);
  95415. this._onEndFrameObserver = null;
  95416. }
  95417. },
  95418. enumerable: true,
  95419. configurable: true
  95420. });
  95421. Object.defineProperty(EngineInstrumentation.prototype, "shaderCompilationTimeCounter", {
  95422. /**
  95423. * Gets the perf counter used for shader compilation time
  95424. */
  95425. get: function () {
  95426. return this._shaderCompilationTime;
  95427. },
  95428. enumerable: true,
  95429. configurable: true
  95430. });
  95431. Object.defineProperty(EngineInstrumentation.prototype, "captureShaderCompilationTime", {
  95432. /**
  95433. * Gets the shader compilation time capture status
  95434. */
  95435. get: function () {
  95436. return this._captureShaderCompilationTime;
  95437. },
  95438. /**
  95439. * Enable or disable the shader compilation time capture
  95440. */
  95441. set: function (value) {
  95442. var _this = this;
  95443. if (value === this._captureShaderCompilationTime) {
  95444. return;
  95445. }
  95446. this._captureShaderCompilationTime = value;
  95447. if (value) {
  95448. this._onBeforeShaderCompilationObserver = this.engine.onBeforeShaderCompilationObservable.add(function () {
  95449. _this._shaderCompilationTime.fetchNewFrame();
  95450. _this._shaderCompilationTime.beginMonitoring();
  95451. });
  95452. this._onAfterShaderCompilationObserver = this.engine.onAfterShaderCompilationObservable.add(function () {
  95453. _this._shaderCompilationTime.endMonitoring();
  95454. });
  95455. }
  95456. else {
  95457. this.engine.onBeforeShaderCompilationObservable.remove(this._onBeforeShaderCompilationObserver);
  95458. this._onBeforeShaderCompilationObserver = null;
  95459. this.engine.onAfterShaderCompilationObservable.remove(this._onAfterShaderCompilationObserver);
  95460. this._onAfterShaderCompilationObserver = null;
  95461. }
  95462. },
  95463. enumerable: true,
  95464. configurable: true
  95465. });
  95466. EngineInstrumentation.prototype.dispose = function () {
  95467. this.engine.onBeginFrameObservable.remove(this._onBeginFrameObserver);
  95468. this._onBeginFrameObserver = null;
  95469. this.engine.onEndFrameObservable.remove(this._onEndFrameObserver);
  95470. this._onEndFrameObserver = null;
  95471. this.engine.onBeforeShaderCompilationObservable.remove(this._onBeforeShaderCompilationObserver);
  95472. this._onBeforeShaderCompilationObserver = null;
  95473. this.engine.onAfterShaderCompilationObservable.remove(this._onAfterShaderCompilationObserver);
  95474. this._onAfterShaderCompilationObserver = null;
  95475. this.engine = null;
  95476. };
  95477. return EngineInstrumentation;
  95478. }());
  95479. BABYLON.EngineInstrumentation = EngineInstrumentation;
  95480. })(BABYLON || (BABYLON = {}));
  95481. //# sourceMappingURL=babylon.engineInstrumentation.js.map
  95482. var BABYLON;
  95483. (function (BABYLON) {
  95484. /**
  95485. * This class can be used to get instrumentation data from a Babylon engine
  95486. */
  95487. var SceneInstrumentation = /** @class */ (function () {
  95488. function SceneInstrumentation(scene) {
  95489. var _this = this;
  95490. this.scene = scene;
  95491. this._captureActiveMeshesEvaluationTime = false;
  95492. this._activeMeshesEvaluationTime = new BABYLON.PerfCounter();
  95493. this._captureRenderTargetsRenderTime = false;
  95494. this._renderTargetsRenderTime = new BABYLON.PerfCounter();
  95495. this._captureFrameTime = false;
  95496. this._frameTime = new BABYLON.PerfCounter();
  95497. this._captureRenderTime = false;
  95498. this._renderTime = new BABYLON.PerfCounter();
  95499. this._captureInterFrameTime = false;
  95500. this._interFrameTime = new BABYLON.PerfCounter();
  95501. this._captureParticlesRenderTime = false;
  95502. this._particlesRenderTime = new BABYLON.PerfCounter();
  95503. this._captureSpritesRenderTime = false;
  95504. this._spritesRenderTime = new BABYLON.PerfCounter();
  95505. this._capturePhysicsTime = false;
  95506. this._physicsTime = new BABYLON.PerfCounter();
  95507. this._captureAnimationsTime = false;
  95508. this._animationsTime = new BABYLON.PerfCounter();
  95509. // Observers
  95510. this._onBeforeActiveMeshesEvaluationObserver = null;
  95511. this._onAfterActiveMeshesEvaluationObserver = null;
  95512. this._onBeforeRenderTargetsRenderObserver = null;
  95513. this._onAfterRenderTargetsRenderObserver = null;
  95514. this._onAfterRenderObserver = null;
  95515. this._onBeforeDrawPhaseObserver = null;
  95516. this._onAfterDrawPhaseObserver = null;
  95517. this._onBeforeAnimationsObserver = null;
  95518. this._onBeforeParticlesRenderingObserver = null;
  95519. this._onAfterParticlesRenderingObserver = null;
  95520. this._onBeforeSpritesRenderingObserver = null;
  95521. this._onAfterSpritesRenderingObserver = null;
  95522. this._onBeforePhysicsObserver = null;
  95523. this._onAfterPhysicsObserver = null;
  95524. this._onAfterAnimationsObserver = null;
  95525. // Before render
  95526. this._onBeforeAnimationsObserver = scene.onBeforeAnimationsObservable.add(function () {
  95527. if (_this._captureActiveMeshesEvaluationTime) {
  95528. _this._activeMeshesEvaluationTime.fetchNewFrame();
  95529. }
  95530. if (_this._captureRenderTargetsRenderTime) {
  95531. _this._renderTargetsRenderTime.fetchNewFrame();
  95532. }
  95533. if (_this._captureFrameTime) {
  95534. BABYLON.Tools.StartPerformanceCounter("Scene rendering");
  95535. _this._frameTime.beginMonitoring();
  95536. }
  95537. if (_this._captureInterFrameTime) {
  95538. _this._interFrameTime.endMonitoring();
  95539. }
  95540. if (_this._captureParticlesRenderTime) {
  95541. _this._particlesRenderTime.fetchNewFrame();
  95542. }
  95543. if (_this._captureSpritesRenderTime) {
  95544. _this._spritesRenderTime.fetchNewFrame();
  95545. }
  95546. if (_this._captureAnimationsTime) {
  95547. _this._animationsTime.beginMonitoring();
  95548. }
  95549. _this.scene.getEngine()._drawCalls.fetchNewFrame();
  95550. _this.scene.getEngine()._textureCollisions.fetchNewFrame();
  95551. });
  95552. // After render
  95553. this._onAfterRenderObserver = scene.onAfterRenderObservable.add(function () {
  95554. if (_this._captureFrameTime) {
  95555. BABYLON.Tools.EndPerformanceCounter("Scene rendering");
  95556. _this._frameTime.endMonitoring();
  95557. }
  95558. if (_this._captureRenderTime) {
  95559. _this._renderTime.endMonitoring(false);
  95560. }
  95561. if (_this._captureInterFrameTime) {
  95562. _this._interFrameTime.beginMonitoring();
  95563. }
  95564. });
  95565. }
  95566. Object.defineProperty(SceneInstrumentation.prototype, "activeMeshesEvaluationTimeCounter", {
  95567. // Properties
  95568. /**
  95569. * Gets the perf counter used for active meshes evaluation time
  95570. */
  95571. get: function () {
  95572. return this._activeMeshesEvaluationTime;
  95573. },
  95574. enumerable: true,
  95575. configurable: true
  95576. });
  95577. Object.defineProperty(SceneInstrumentation.prototype, "captureActiveMeshesEvaluationTime", {
  95578. /**
  95579. * Gets the active meshes evaluation time capture status
  95580. */
  95581. get: function () {
  95582. return this._captureActiveMeshesEvaluationTime;
  95583. },
  95584. /**
  95585. * Enable or disable the active meshes evaluation time capture
  95586. */
  95587. set: function (value) {
  95588. var _this = this;
  95589. if (value === this._captureActiveMeshesEvaluationTime) {
  95590. return;
  95591. }
  95592. this._captureActiveMeshesEvaluationTime = value;
  95593. if (value) {
  95594. this._onBeforeActiveMeshesEvaluationObserver = this.scene.onBeforeActiveMeshesEvaluationObservable.add(function () {
  95595. BABYLON.Tools.StartPerformanceCounter("Active meshes evaluation");
  95596. _this._activeMeshesEvaluationTime.beginMonitoring();
  95597. });
  95598. this._onAfterActiveMeshesEvaluationObserver = this.scene.onAfterActiveMeshesEvaluationObservable.add(function () {
  95599. BABYLON.Tools.EndPerformanceCounter("Active meshes evaluation");
  95600. _this._activeMeshesEvaluationTime.endMonitoring();
  95601. });
  95602. }
  95603. else {
  95604. this.scene.onBeforeActiveMeshesEvaluationObservable.remove(this._onBeforeActiveMeshesEvaluationObserver);
  95605. this._onBeforeActiveMeshesEvaluationObserver = null;
  95606. this.scene.onAfterActiveMeshesEvaluationObservable.remove(this._onAfterActiveMeshesEvaluationObserver);
  95607. this._onAfterActiveMeshesEvaluationObserver = null;
  95608. }
  95609. },
  95610. enumerable: true,
  95611. configurable: true
  95612. });
  95613. Object.defineProperty(SceneInstrumentation.prototype, "renderTargetsRenderTimeCounter", {
  95614. /**
  95615. * Gets the perf counter used for render targets render time
  95616. */
  95617. get: function () {
  95618. return this._renderTargetsRenderTime;
  95619. },
  95620. enumerable: true,
  95621. configurable: true
  95622. });
  95623. Object.defineProperty(SceneInstrumentation.prototype, "captureRenderTargetsRenderTime", {
  95624. /**
  95625. * Gets the render targets render time capture status
  95626. */
  95627. get: function () {
  95628. return this._captureRenderTargetsRenderTime;
  95629. },
  95630. /**
  95631. * Enable or disable the render targets render time capture
  95632. */
  95633. set: function (value) {
  95634. var _this = this;
  95635. if (value === this._captureRenderTargetsRenderTime) {
  95636. return;
  95637. }
  95638. this._captureRenderTargetsRenderTime = value;
  95639. if (value) {
  95640. this._onBeforeRenderTargetsRenderObserver = this.scene.onBeforeRenderTargetsRenderObservable.add(function () {
  95641. BABYLON.Tools.StartPerformanceCounter("Render targets rendering");
  95642. _this._renderTargetsRenderTime.beginMonitoring();
  95643. });
  95644. this._onAfterRenderTargetsRenderObserver = this.scene.onAfterRenderTargetsRenderObservable.add(function () {
  95645. BABYLON.Tools.EndPerformanceCounter("Render targets rendering");
  95646. _this._renderTargetsRenderTime.endMonitoring(false);
  95647. });
  95648. }
  95649. else {
  95650. this.scene.onBeforeRenderTargetsRenderObservable.remove(this._onBeforeRenderTargetsRenderObserver);
  95651. this._onBeforeRenderTargetsRenderObserver = null;
  95652. this.scene.onAfterRenderTargetsRenderObservable.remove(this._onAfterRenderTargetsRenderObserver);
  95653. this._onAfterRenderTargetsRenderObserver = null;
  95654. }
  95655. },
  95656. enumerable: true,
  95657. configurable: true
  95658. });
  95659. Object.defineProperty(SceneInstrumentation.prototype, "particlesRenderTimeCounter", {
  95660. /**
  95661. * Gets the perf counter used for particles render time
  95662. */
  95663. get: function () {
  95664. return this._particlesRenderTime;
  95665. },
  95666. enumerable: true,
  95667. configurable: true
  95668. });
  95669. Object.defineProperty(SceneInstrumentation.prototype, "captureParticlesRenderTime", {
  95670. /**
  95671. * Gets the particles render time capture status
  95672. */
  95673. get: function () {
  95674. return this._captureParticlesRenderTime;
  95675. },
  95676. /**
  95677. * Enable or disable the particles render time capture
  95678. */
  95679. set: function (value) {
  95680. var _this = this;
  95681. if (value === this._captureParticlesRenderTime) {
  95682. return;
  95683. }
  95684. this._captureParticlesRenderTime = value;
  95685. if (value) {
  95686. this._onBeforeParticlesRenderingObserver = this.scene.onBeforeParticlesRenderingObservable.add(function () {
  95687. BABYLON.Tools.StartPerformanceCounter("Particles");
  95688. _this._particlesRenderTime.beginMonitoring();
  95689. });
  95690. this._onAfterParticlesRenderingObserver = this.scene.onAfterParticlesRenderingObservable.add(function () {
  95691. BABYLON.Tools.EndPerformanceCounter("Particles");
  95692. _this._particlesRenderTime.endMonitoring(false);
  95693. });
  95694. }
  95695. else {
  95696. this.scene.onBeforeParticlesRenderingObservable.remove(this._onBeforeParticlesRenderingObserver);
  95697. this._onBeforeParticlesRenderingObserver = null;
  95698. this.scene.onAfterParticlesRenderingObservable.remove(this._onAfterParticlesRenderingObserver);
  95699. this._onAfterParticlesRenderingObserver = null;
  95700. }
  95701. },
  95702. enumerable: true,
  95703. configurable: true
  95704. });
  95705. Object.defineProperty(SceneInstrumentation.prototype, "spritesRenderTimeCounter", {
  95706. /**
  95707. * Gets the perf counter used for sprites render time
  95708. */
  95709. get: function () {
  95710. return this._spritesRenderTime;
  95711. },
  95712. enumerable: true,
  95713. configurable: true
  95714. });
  95715. Object.defineProperty(SceneInstrumentation.prototype, "captureSpritesRenderTime", {
  95716. /**
  95717. * Gets the sprites render time capture status
  95718. */
  95719. get: function () {
  95720. return this._captureSpritesRenderTime;
  95721. },
  95722. /**
  95723. * Enable or disable the sprites render time capture
  95724. */
  95725. set: function (value) {
  95726. var _this = this;
  95727. if (value === this._captureSpritesRenderTime) {
  95728. return;
  95729. }
  95730. this._captureSpritesRenderTime = value;
  95731. if (value) {
  95732. this._onBeforeSpritesRenderingObserver = this.scene.onBeforeSpritesRenderingObservable.add(function () {
  95733. BABYLON.Tools.StartPerformanceCounter("Sprites");
  95734. _this._spritesRenderTime.beginMonitoring();
  95735. });
  95736. this._onAfterSpritesRenderingObserver = this.scene.onAfterSpritesRenderingObservable.add(function () {
  95737. BABYLON.Tools.EndPerformanceCounter("Sprites");
  95738. _this._spritesRenderTime.endMonitoring(false);
  95739. });
  95740. }
  95741. else {
  95742. this.scene.onBeforeSpritesRenderingObservable.remove(this._onBeforeSpritesRenderingObserver);
  95743. this._onBeforeSpritesRenderingObserver = null;
  95744. this.scene.onAfterSpritesRenderingObservable.remove(this._onAfterSpritesRenderingObserver);
  95745. this._onAfterSpritesRenderingObserver = null;
  95746. }
  95747. },
  95748. enumerable: true,
  95749. configurable: true
  95750. });
  95751. Object.defineProperty(SceneInstrumentation.prototype, "physicsTimeCounter", {
  95752. /**
  95753. * Gets the perf counter used for physics time
  95754. */
  95755. get: function () {
  95756. return this._physicsTime;
  95757. },
  95758. enumerable: true,
  95759. configurable: true
  95760. });
  95761. Object.defineProperty(SceneInstrumentation.prototype, "capturePhysicsTime", {
  95762. /**
  95763. * Gets the physics time capture status
  95764. */
  95765. get: function () {
  95766. return this._capturePhysicsTime;
  95767. },
  95768. /**
  95769. * Enable or disable the physics time capture
  95770. */
  95771. set: function (value) {
  95772. var _this = this;
  95773. if (value === this._capturePhysicsTime) {
  95774. return;
  95775. }
  95776. this._capturePhysicsTime = value;
  95777. if (value) {
  95778. this._onBeforePhysicsObserver = this.scene.onBeforePhysicsObservable.add(function () {
  95779. BABYLON.Tools.StartPerformanceCounter("Physics");
  95780. _this._physicsTime.beginMonitoring();
  95781. });
  95782. this._onAfterPhysicsObserver = this.scene.onAfterPhysicsObservable.add(function () {
  95783. BABYLON.Tools.EndPerformanceCounter("Physics");
  95784. _this._physicsTime.endMonitoring();
  95785. });
  95786. }
  95787. else {
  95788. this.scene.onBeforePhysicsObservable.remove(this._onBeforePhysicsObserver);
  95789. this._onBeforePhysicsObserver = null;
  95790. this.scene.onAfterPhysicsObservable.remove(this._onAfterPhysicsObserver);
  95791. this._onAfterPhysicsObserver = null;
  95792. }
  95793. },
  95794. enumerable: true,
  95795. configurable: true
  95796. });
  95797. Object.defineProperty(SceneInstrumentation.prototype, "animationsTimeCounter", {
  95798. /**
  95799. * Gets the perf counter used for animations time
  95800. */
  95801. get: function () {
  95802. return this._animationsTime;
  95803. },
  95804. enumerable: true,
  95805. configurable: true
  95806. });
  95807. Object.defineProperty(SceneInstrumentation.prototype, "captureAnimationsTime", {
  95808. /**
  95809. * Gets the animations time capture status
  95810. */
  95811. get: function () {
  95812. return this._captureAnimationsTime;
  95813. },
  95814. /**
  95815. * Enable or disable the animations time capture
  95816. */
  95817. set: function (value) {
  95818. var _this = this;
  95819. if (value === this._captureAnimationsTime) {
  95820. return;
  95821. }
  95822. this._captureAnimationsTime = value;
  95823. if (value) {
  95824. this._onAfterAnimationsObserver = this.scene.onAfterAnimationsObservable.add(function () {
  95825. _this._animationsTime.endMonitoring();
  95826. });
  95827. }
  95828. else {
  95829. this.scene.onAfterAnimationsObservable.remove(this._onAfterAnimationsObserver);
  95830. this._onAfterAnimationsObserver = null;
  95831. }
  95832. },
  95833. enumerable: true,
  95834. configurable: true
  95835. });
  95836. Object.defineProperty(SceneInstrumentation.prototype, "frameTimeCounter", {
  95837. /**
  95838. * Gets the perf counter used for frame time capture
  95839. */
  95840. get: function () {
  95841. return this._frameTime;
  95842. },
  95843. enumerable: true,
  95844. configurable: true
  95845. });
  95846. Object.defineProperty(SceneInstrumentation.prototype, "captureFrameTime", {
  95847. /**
  95848. * Gets the frame time capture status
  95849. */
  95850. get: function () {
  95851. return this._captureFrameTime;
  95852. },
  95853. /**
  95854. * Enable or disable the frame time capture
  95855. */
  95856. set: function (value) {
  95857. this._captureFrameTime = value;
  95858. },
  95859. enumerable: true,
  95860. configurable: true
  95861. });
  95862. Object.defineProperty(SceneInstrumentation.prototype, "interFrameTimeCounter", {
  95863. /**
  95864. * Gets the perf counter used for inter-frames time capture
  95865. */
  95866. get: function () {
  95867. return this._interFrameTime;
  95868. },
  95869. enumerable: true,
  95870. configurable: true
  95871. });
  95872. Object.defineProperty(SceneInstrumentation.prototype, "captureInterFrameTime", {
  95873. /**
  95874. * Gets the inter-frames time capture status
  95875. */
  95876. get: function () {
  95877. return this._captureInterFrameTime;
  95878. },
  95879. /**
  95880. * Enable or disable the inter-frames time capture
  95881. */
  95882. set: function (value) {
  95883. this._captureInterFrameTime = value;
  95884. },
  95885. enumerable: true,
  95886. configurable: true
  95887. });
  95888. Object.defineProperty(SceneInstrumentation.prototype, "renderTimeCounter", {
  95889. /**
  95890. * Gets the perf counter used for render time capture
  95891. */
  95892. get: function () {
  95893. return this._renderTime;
  95894. },
  95895. enumerable: true,
  95896. configurable: true
  95897. });
  95898. Object.defineProperty(SceneInstrumentation.prototype, "captureRenderTime", {
  95899. /**
  95900. * Gets the render time capture status
  95901. */
  95902. get: function () {
  95903. return this._captureRenderTime;
  95904. },
  95905. /**
  95906. * Enable or disable the render time capture
  95907. */
  95908. set: function (value) {
  95909. var _this = this;
  95910. if (value === this._captureRenderTime) {
  95911. return;
  95912. }
  95913. this._captureRenderTime = value;
  95914. if (value) {
  95915. this._onBeforeDrawPhaseObserver = this.scene.onBeforeDrawPhaseObservable.add(function () {
  95916. _this._renderTime.beginMonitoring();
  95917. BABYLON.Tools.StartPerformanceCounter("Main render");
  95918. });
  95919. this._onAfterDrawPhaseObserver = this.scene.onAfterDrawPhaseObservable.add(function () {
  95920. _this._renderTime.endMonitoring(false);
  95921. BABYLON.Tools.EndPerformanceCounter("Main render");
  95922. });
  95923. }
  95924. else {
  95925. this.scene.onBeforeDrawPhaseObservable.remove(this._onBeforeDrawPhaseObserver);
  95926. this._onBeforeDrawPhaseObserver = null;
  95927. this.scene.onAfterDrawPhaseObservable.remove(this._onAfterDrawPhaseObserver);
  95928. this._onAfterDrawPhaseObserver = null;
  95929. }
  95930. },
  95931. enumerable: true,
  95932. configurable: true
  95933. });
  95934. Object.defineProperty(SceneInstrumentation.prototype, "drawCallsCounter", {
  95935. /**
  95936. * Gets the perf counter used for draw calls
  95937. */
  95938. get: function () {
  95939. return this.scene.getEngine()._drawCalls;
  95940. },
  95941. enumerable: true,
  95942. configurable: true
  95943. });
  95944. Object.defineProperty(SceneInstrumentation.prototype, "textureCollisionsCounter", {
  95945. /**
  95946. * Gets the perf counter used for texture collisions
  95947. */
  95948. get: function () {
  95949. return this.scene.getEngine()._textureCollisions;
  95950. },
  95951. enumerable: true,
  95952. configurable: true
  95953. });
  95954. SceneInstrumentation.prototype.dispose = function () {
  95955. this.scene.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  95956. this._onAfterRenderObserver = null;
  95957. this.scene.onBeforeActiveMeshesEvaluationObservable.remove(this._onBeforeActiveMeshesEvaluationObserver);
  95958. this._onBeforeActiveMeshesEvaluationObserver = null;
  95959. this.scene.onAfterActiveMeshesEvaluationObservable.remove(this._onAfterActiveMeshesEvaluationObserver);
  95960. this._onAfterActiveMeshesEvaluationObserver = null;
  95961. this.scene.onBeforeRenderTargetsRenderObservable.remove(this._onBeforeRenderTargetsRenderObserver);
  95962. this._onBeforeRenderTargetsRenderObserver = null;
  95963. this.scene.onAfterRenderTargetsRenderObservable.remove(this._onAfterRenderTargetsRenderObserver);
  95964. this._onAfterRenderTargetsRenderObserver = null;
  95965. this.scene.onBeforeAnimationsObservable.remove(this._onBeforeAnimationsObserver);
  95966. this._onBeforeAnimationsObserver = null;
  95967. this.scene.onBeforeParticlesRenderingObservable.remove(this._onBeforeParticlesRenderingObserver);
  95968. this._onBeforeParticlesRenderingObserver = null;
  95969. this.scene.onAfterParticlesRenderingObservable.remove(this._onAfterParticlesRenderingObserver);
  95970. this._onAfterParticlesRenderingObserver = null;
  95971. this.scene.onBeforeSpritesRenderingObservable.remove(this._onBeforeSpritesRenderingObserver);
  95972. this._onBeforeSpritesRenderingObserver = null;
  95973. this.scene.onAfterSpritesRenderingObservable.remove(this._onAfterSpritesRenderingObserver);
  95974. this._onAfterSpritesRenderingObserver = null;
  95975. this.scene.onBeforeDrawPhaseObservable.remove(this._onBeforeDrawPhaseObserver);
  95976. this._onBeforeDrawPhaseObserver = null;
  95977. this.scene.onAfterDrawPhaseObservable.remove(this._onAfterDrawPhaseObserver);
  95978. this._onAfterDrawPhaseObserver = null;
  95979. this.scene.onBeforePhysicsObservable.remove(this._onBeforePhysicsObserver);
  95980. this._onBeforePhysicsObserver = null;
  95981. this.scene.onAfterPhysicsObservable.remove(this._onAfterPhysicsObserver);
  95982. this._onAfterPhysicsObserver = null;
  95983. this.scene.onAfterAnimationsObservable.remove(this._onAfterAnimationsObserver);
  95984. this._onAfterAnimationsObserver = null;
  95985. this.scene = null;
  95986. };
  95987. return SceneInstrumentation;
  95988. }());
  95989. BABYLON.SceneInstrumentation = SceneInstrumentation;
  95990. })(BABYLON || (BABYLON = {}));
  95991. //# sourceMappingURL=babylon.sceneInstrumentation.js.map
  95992. var BABYLON;
  95993. (function (BABYLON) {
  95994. /**
  95995. * @hidden
  95996. **/
  95997. var _TimeToken = /** @class */ (function () {
  95998. function _TimeToken() {
  95999. this._timeElapsedQueryEnded = false;
  96000. }
  96001. return _TimeToken;
  96002. }());
  96003. BABYLON._TimeToken = _TimeToken;
  96004. })(BABYLON || (BABYLON = {}));
  96005. //# sourceMappingURL=babylon.timeToken.js.map
  96006. var BABYLON;
  96007. (function (BABYLON) {
  96008. /**
  96009. * Background material defines definition.
  96010. * @hidden Mainly internal Use
  96011. */
  96012. var BackgroundMaterialDefines = /** @class */ (function (_super) {
  96013. __extends(BackgroundMaterialDefines, _super);
  96014. /**
  96015. * Constructor of the defines.
  96016. */
  96017. function BackgroundMaterialDefines() {
  96018. var _this = _super.call(this) || this;
  96019. /**
  96020. * True if the diffuse texture is in use.
  96021. */
  96022. _this.DIFFUSE = false;
  96023. /**
  96024. * The direct UV channel to use.
  96025. */
  96026. _this.DIFFUSEDIRECTUV = 0;
  96027. /**
  96028. * True if the diffuse texture is in gamma space.
  96029. */
  96030. _this.GAMMADIFFUSE = false;
  96031. /**
  96032. * True if the diffuse texture has opacity in the alpha channel.
  96033. */
  96034. _this.DIFFUSEHASALPHA = false;
  96035. /**
  96036. * True if you want the material to fade to transparent at grazing angle.
  96037. */
  96038. _this.OPACITYFRESNEL = false;
  96039. /**
  96040. * True if an extra blur needs to be added in the reflection.
  96041. */
  96042. _this.REFLECTIONBLUR = false;
  96043. /**
  96044. * True if you want the material to fade to reflection at grazing angle.
  96045. */
  96046. _this.REFLECTIONFRESNEL = false;
  96047. /**
  96048. * True if you want the material to falloff as far as you move away from the scene center.
  96049. */
  96050. _this.REFLECTIONFALLOFF = false;
  96051. /**
  96052. * False if the current Webgl implementation does not support the texture lod extension.
  96053. */
  96054. _this.TEXTURELODSUPPORT = false;
  96055. /**
  96056. * True to ensure the data are premultiplied.
  96057. */
  96058. _this.PREMULTIPLYALPHA = false;
  96059. /**
  96060. * True if the texture contains cooked RGB values and not gray scaled multipliers.
  96061. */
  96062. _this.USERGBCOLOR = false;
  96063. /**
  96064. * True if highlight and shadow levels have been specified. It can help ensuring the main perceived color
  96065. * stays aligned with the desired configuration.
  96066. */
  96067. _this.USEHIGHLIGHTANDSHADOWCOLORS = false;
  96068. /**
  96069. * True to add noise in order to reduce the banding effect.
  96070. */
  96071. _this.NOISE = false;
  96072. /**
  96073. * is the reflection texture in BGR color scheme?
  96074. * Mainly used to solve a bug in ios10 video tag
  96075. */
  96076. _this.REFLECTIONBGR = false;
  96077. _this.IMAGEPROCESSING = false;
  96078. _this.VIGNETTE = false;
  96079. _this.VIGNETTEBLENDMODEMULTIPLY = false;
  96080. _this.VIGNETTEBLENDMODEOPAQUE = false;
  96081. _this.TONEMAPPING = false;
  96082. _this.CONTRAST = false;
  96083. _this.COLORCURVES = false;
  96084. _this.COLORGRADING = false;
  96085. _this.COLORGRADING3D = false;
  96086. _this.SAMPLER3DGREENDEPTH = false;
  96087. _this.SAMPLER3DBGRMAP = false;
  96088. _this.IMAGEPROCESSINGPOSTPROCESS = false;
  96089. _this.EXPOSURE = false;
  96090. // Reflection.
  96091. _this.REFLECTION = false;
  96092. _this.REFLECTIONMAP_3D = false;
  96093. _this.REFLECTIONMAP_SPHERICAL = false;
  96094. _this.REFLECTIONMAP_PLANAR = false;
  96095. _this.REFLECTIONMAP_CUBIC = false;
  96096. _this.REFLECTIONMAP_PROJECTION = false;
  96097. _this.REFLECTIONMAP_SKYBOX = false;
  96098. _this.REFLECTIONMAP_EXPLICIT = false;
  96099. _this.REFLECTIONMAP_EQUIRECTANGULAR = false;
  96100. _this.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  96101. _this.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false;
  96102. _this.INVERTCUBICMAP = false;
  96103. _this.REFLECTIONMAP_OPPOSITEZ = false;
  96104. _this.LODINREFLECTIONALPHA = false;
  96105. _this.GAMMAREFLECTION = false;
  96106. _this.EQUIRECTANGULAR_RELFECTION_FOV = false;
  96107. // Default BJS.
  96108. _this.MAINUV1 = false;
  96109. _this.MAINUV2 = false;
  96110. _this.UV1 = false;
  96111. _this.UV2 = false;
  96112. _this.CLIPPLANE = false;
  96113. _this.POINTSIZE = false;
  96114. _this.FOG = false;
  96115. _this.NORMAL = false;
  96116. _this.NUM_BONE_INFLUENCERS = 0;
  96117. _this.BonesPerMesh = 0;
  96118. _this.INSTANCES = false;
  96119. _this.SHADOWFLOAT = false;
  96120. _this.rebuild();
  96121. return _this;
  96122. }
  96123. return BackgroundMaterialDefines;
  96124. }(BABYLON.MaterialDefines));
  96125. /**
  96126. * Background material used to create an efficient environement around your scene.
  96127. */
  96128. var BackgroundMaterial = /** @class */ (function (_super) {
  96129. __extends(BackgroundMaterial, _super);
  96130. /**
  96131. * Instantiates a Background Material in the given scene
  96132. * @param name The friendly name of the material
  96133. * @param scene The scene to add the material to
  96134. */
  96135. function BackgroundMaterial(name, scene) {
  96136. var _this = _super.call(this, name, scene) || this;
  96137. /**
  96138. * Key light Color (multiply against the environement texture)
  96139. */
  96140. _this.primaryColor = BABYLON.Color3.White();
  96141. _this._primaryColorShadowLevel = 0;
  96142. _this._primaryColorHighlightLevel = 0;
  96143. /**
  96144. * Reflection Texture used in the material.
  96145. * Should be author in a specific way for the best result (refer to the documentation).
  96146. */
  96147. _this.reflectionTexture = null;
  96148. /**
  96149. * Reflection Texture level of blur.
  96150. *
  96151. * Can be use to reuse an existing HDR Texture and target a specific LOD to prevent authoring the
  96152. * texture twice.
  96153. */
  96154. _this.reflectionBlur = 0;
  96155. /**
  96156. * Diffuse Texture used in the material.
  96157. * Should be author in a specific way for the best result (refer to the documentation).
  96158. */
  96159. _this.diffuseTexture = null;
  96160. _this._shadowLights = null;
  96161. /**
  96162. * Specify the list of lights casting shadow on the material.
  96163. * All scene shadow lights will be included if null.
  96164. */
  96165. _this.shadowLights = null;
  96166. /**
  96167. * Helps adjusting the shadow to a softer level if required.
  96168. * 0 means black shadows and 1 means no shadows.
  96169. */
  96170. _this.shadowLevel = 0;
  96171. /**
  96172. * In case of opacity Fresnel or reflection falloff, this is use as a scene center.
  96173. * It is usually zero but might be interesting to modify according to your setup.
  96174. */
  96175. _this.sceneCenter = BABYLON.Vector3.Zero();
  96176. /**
  96177. * This helps specifying that the material is falling off to the sky box at grazing angle.
  96178. * This helps ensuring a nice transition when the camera goes under the ground.
  96179. */
  96180. _this.opacityFresnel = true;
  96181. /**
  96182. * This helps specifying that the material is falling off from diffuse to the reflection texture at grazing angle.
  96183. * This helps adding a mirror texture on the ground.
  96184. */
  96185. _this.reflectionFresnel = false;
  96186. /**
  96187. * This helps specifying the falloff radius off the reflection texture from the sceneCenter.
  96188. * This helps adding a nice falloff effect to the reflection if used as a mirror for instance.
  96189. */
  96190. _this.reflectionFalloffDistance = 0.0;
  96191. /**
  96192. * This specifies the weight of the reflection against the background in case of reflection Fresnel.
  96193. */
  96194. _this.reflectionAmount = 1.0;
  96195. /**
  96196. * This specifies the weight of the reflection at grazing angle.
  96197. */
  96198. _this.reflectionReflectance0 = 0.05;
  96199. /**
  96200. * This specifies the weight of the reflection at a perpendicular point of view.
  96201. */
  96202. _this.reflectionReflectance90 = 0.5;
  96203. /**
  96204. * Helps to directly use the maps channels instead of their level.
  96205. */
  96206. _this.useRGBColor = true;
  96207. /**
  96208. * This helps reducing the banding effect that could occur on the background.
  96209. */
  96210. _this.enableNoise = false;
  96211. _this._fovMultiplier = 1.0;
  96212. /**
  96213. * Enable the FOV adjustment feature controlled by fovMultiplier.
  96214. */
  96215. _this.useEquirectangularFOV = false;
  96216. _this._maxSimultaneousLights = 4;
  96217. /**
  96218. * Number of Simultaneous lights allowed on the material.
  96219. */
  96220. _this.maxSimultaneousLights = 4;
  96221. /**
  96222. * Keep track of the image processing observer to allow dispose and replace.
  96223. */
  96224. _this._imageProcessingObserver = null;
  96225. /**
  96226. * Due to a bug in iOS10, video tags (which are using the background material) are in BGR and not RGB.
  96227. * Setting this flag to true (not done automatically!) will convert it back to RGB.
  96228. */
  96229. _this.switchToBGR = false;
  96230. // Temp values kept as cache in the material.
  96231. _this._renderTargets = new BABYLON.SmartArray(16);
  96232. _this._reflectionControls = BABYLON.Vector4.Zero();
  96233. _this._white = BABYLON.Color3.White();
  96234. _this._primaryShadowColor = BABYLON.Color3.Black();
  96235. _this._primaryHighlightColor = BABYLON.Color3.Black();
  96236. // Setup the default processing configuration to the scene.
  96237. _this._attachImageProcessingConfiguration(null);
  96238. _this.getRenderTargetTextures = function () {
  96239. _this._renderTargets.reset();
  96240. if (_this._diffuseTexture && _this._diffuseTexture.isRenderTarget) {
  96241. _this._renderTargets.push(_this._diffuseTexture);
  96242. }
  96243. if (_this._reflectionTexture && _this._reflectionTexture.isRenderTarget) {
  96244. _this._renderTargets.push(_this._reflectionTexture);
  96245. }
  96246. return _this._renderTargets;
  96247. };
  96248. return _this;
  96249. }
  96250. Object.defineProperty(BackgroundMaterial.prototype, "_perceptualColor", {
  96251. /**
  96252. * Experimental Internal Use Only.
  96253. *
  96254. * Key light Color in "perceptual value" meaning the color you would like to see on screen.
  96255. * This acts as a helper to set the primary color to a more "human friendly" value.
  96256. * Conversion to linear space as well as exposure and tone mapping correction will be applied to keep the
  96257. * output color as close as possible from the chosen value.
  96258. * (This does not account for contrast color grading and color curves as they are considered post effect and not directly
  96259. * part of lighting setup.)
  96260. */
  96261. get: function () {
  96262. return this.__perceptualColor;
  96263. },
  96264. set: function (value) {
  96265. this.__perceptualColor = value;
  96266. this._computePrimaryColorFromPerceptualColor();
  96267. this._markAllSubMeshesAsLightsDirty();
  96268. },
  96269. enumerable: true,
  96270. configurable: true
  96271. });
  96272. Object.defineProperty(BackgroundMaterial.prototype, "primaryColorShadowLevel", {
  96273. /**
  96274. * Defines the level of the shadows (dark area of the reflection map) in order to help scaling the colors.
  96275. * The color opposite to the primary color is used at the level chosen to define what the black area would look.
  96276. */
  96277. get: function () {
  96278. return this._primaryColorShadowLevel;
  96279. },
  96280. set: function (value) {
  96281. this._primaryColorShadowLevel = value;
  96282. this._computePrimaryColors();
  96283. this._markAllSubMeshesAsLightsDirty();
  96284. },
  96285. enumerable: true,
  96286. configurable: true
  96287. });
  96288. Object.defineProperty(BackgroundMaterial.prototype, "primaryColorHighlightLevel", {
  96289. /**
  96290. * Defines the level of the highliights (highlight area of the reflection map) in order to help scaling the colors.
  96291. * The primary color is used at the level chosen to define what the white area would look.
  96292. */
  96293. get: function () {
  96294. return this._primaryColorHighlightLevel;
  96295. },
  96296. set: function (value) {
  96297. this._primaryColorHighlightLevel = value;
  96298. this._computePrimaryColors();
  96299. this._markAllSubMeshesAsLightsDirty();
  96300. },
  96301. enumerable: true,
  96302. configurable: true
  96303. });
  96304. Object.defineProperty(BackgroundMaterial.prototype, "reflectionStandardFresnelWeight", {
  96305. /**
  96306. * Sets the reflection reflectance fresnel values according to the default standard
  96307. * empirically know to work well :-)
  96308. */
  96309. set: function (value) {
  96310. var reflectionWeight = value;
  96311. if (reflectionWeight < 0.5) {
  96312. reflectionWeight = reflectionWeight * 2.0;
  96313. this.reflectionReflectance0 = BackgroundMaterial.StandardReflectance0 * reflectionWeight;
  96314. this.reflectionReflectance90 = BackgroundMaterial.StandardReflectance90 * reflectionWeight;
  96315. }
  96316. else {
  96317. reflectionWeight = reflectionWeight * 2.0 - 1.0;
  96318. this.reflectionReflectance0 = BackgroundMaterial.StandardReflectance0 + (1.0 - BackgroundMaterial.StandardReflectance0) * reflectionWeight;
  96319. this.reflectionReflectance90 = BackgroundMaterial.StandardReflectance90 + (1.0 - BackgroundMaterial.StandardReflectance90) * reflectionWeight;
  96320. }
  96321. },
  96322. enumerable: true,
  96323. configurable: true
  96324. });
  96325. Object.defineProperty(BackgroundMaterial.prototype, "fovMultiplier", {
  96326. /**
  96327. * The current fov(field of view) multiplier, 0.0 - 2.0. Defaults to 1.0. Lower values "zoom in" and higher values "zoom out".
  96328. * Best used when trying to implement visual zoom effects like fish-eye or binoculars while not adjusting camera fov.
  96329. * Recommended to be keep at 1.0 except for special cases.
  96330. */
  96331. get: function () {
  96332. return this._fovMultiplier;
  96333. },
  96334. set: function (value) {
  96335. if (isNaN(value)) {
  96336. value = 1.0;
  96337. }
  96338. this._fovMultiplier = Math.max(0.0, Math.min(2.0, value));
  96339. },
  96340. enumerable: true,
  96341. configurable: true
  96342. });
  96343. /**
  96344. * Attaches a new image processing configuration to the PBR Material.
  96345. * @param configuration (if null the scene configuration will be use)
  96346. */
  96347. BackgroundMaterial.prototype._attachImageProcessingConfiguration = function (configuration) {
  96348. var _this = this;
  96349. if (configuration === this._imageProcessingConfiguration) {
  96350. return;
  96351. }
  96352. // Detaches observer.
  96353. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  96354. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  96355. }
  96356. // Pick the scene configuration if needed.
  96357. if (!configuration) {
  96358. this._imageProcessingConfiguration = this.getScene().imageProcessingConfiguration;
  96359. }
  96360. else {
  96361. this._imageProcessingConfiguration = configuration;
  96362. }
  96363. // Attaches observer.
  96364. this._imageProcessingObserver = this._imageProcessingConfiguration.onUpdateParameters.add(function (conf) {
  96365. _this._computePrimaryColorFromPerceptualColor();
  96366. _this._markAllSubMeshesAsImageProcessingDirty();
  96367. });
  96368. };
  96369. Object.defineProperty(BackgroundMaterial.prototype, "imageProcessingConfiguration", {
  96370. /**
  96371. * Gets the image processing configuration used either in this material.
  96372. */
  96373. get: function () {
  96374. return this._imageProcessingConfiguration;
  96375. },
  96376. /**
  96377. * Sets the Default image processing configuration used either in the this material.
  96378. *
  96379. * If sets to null, the scene one is in use.
  96380. */
  96381. set: function (value) {
  96382. this._attachImageProcessingConfiguration(value);
  96383. // Ensure the effect will be rebuilt.
  96384. this._markAllSubMeshesAsTexturesDirty();
  96385. },
  96386. enumerable: true,
  96387. configurable: true
  96388. });
  96389. Object.defineProperty(BackgroundMaterial.prototype, "cameraColorCurvesEnabled", {
  96390. /**
  96391. * Gets wether the color curves effect is enabled.
  96392. */
  96393. get: function () {
  96394. return this.imageProcessingConfiguration.colorCurvesEnabled;
  96395. },
  96396. /**
  96397. * Sets wether the color curves effect is enabled.
  96398. */
  96399. set: function (value) {
  96400. this.imageProcessingConfiguration.colorCurvesEnabled = value;
  96401. },
  96402. enumerable: true,
  96403. configurable: true
  96404. });
  96405. Object.defineProperty(BackgroundMaterial.prototype, "cameraColorGradingEnabled", {
  96406. /**
  96407. * Gets wether the color grading effect is enabled.
  96408. */
  96409. get: function () {
  96410. return this.imageProcessingConfiguration.colorGradingEnabled;
  96411. },
  96412. /**
  96413. * Gets wether the color grading effect is enabled.
  96414. */
  96415. set: function (value) {
  96416. this.imageProcessingConfiguration.colorGradingEnabled = value;
  96417. },
  96418. enumerable: true,
  96419. configurable: true
  96420. });
  96421. Object.defineProperty(BackgroundMaterial.prototype, "cameraToneMappingEnabled", {
  96422. /**
  96423. * Gets wether tonemapping is enabled or not.
  96424. */
  96425. get: function () {
  96426. return this._imageProcessingConfiguration.toneMappingEnabled;
  96427. },
  96428. /**
  96429. * Sets wether tonemapping is enabled or not
  96430. */
  96431. set: function (value) {
  96432. this._imageProcessingConfiguration.toneMappingEnabled = value;
  96433. },
  96434. enumerable: true,
  96435. configurable: true
  96436. });
  96437. ;
  96438. ;
  96439. Object.defineProperty(BackgroundMaterial.prototype, "cameraExposure", {
  96440. /**
  96441. * The camera exposure used on this material.
  96442. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  96443. * This corresponds to a photographic exposure.
  96444. */
  96445. get: function () {
  96446. return this._imageProcessingConfiguration.exposure;
  96447. },
  96448. /**
  96449. * The camera exposure used on this material.
  96450. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  96451. * This corresponds to a photographic exposure.
  96452. */
  96453. set: function (value) {
  96454. this._imageProcessingConfiguration.exposure = value;
  96455. },
  96456. enumerable: true,
  96457. configurable: true
  96458. });
  96459. ;
  96460. ;
  96461. Object.defineProperty(BackgroundMaterial.prototype, "cameraContrast", {
  96462. /**
  96463. * Gets The camera contrast used on this material.
  96464. */
  96465. get: function () {
  96466. return this._imageProcessingConfiguration.contrast;
  96467. },
  96468. /**
  96469. * Sets The camera contrast used on this material.
  96470. */
  96471. set: function (value) {
  96472. this._imageProcessingConfiguration.contrast = value;
  96473. },
  96474. enumerable: true,
  96475. configurable: true
  96476. });
  96477. Object.defineProperty(BackgroundMaterial.prototype, "cameraColorGradingTexture", {
  96478. /**
  96479. * Gets the Color Grading 2D Lookup Texture.
  96480. */
  96481. get: function () {
  96482. return this._imageProcessingConfiguration.colorGradingTexture;
  96483. },
  96484. /**
  96485. * Sets the Color Grading 2D Lookup Texture.
  96486. */
  96487. set: function (value) {
  96488. this.imageProcessingConfiguration.colorGradingTexture = value;
  96489. },
  96490. enumerable: true,
  96491. configurable: true
  96492. });
  96493. Object.defineProperty(BackgroundMaterial.prototype, "cameraColorCurves", {
  96494. /**
  96495. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  96496. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  96497. * 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;
  96498. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  96499. */
  96500. get: function () {
  96501. return this.imageProcessingConfiguration.colorCurves;
  96502. },
  96503. /**
  96504. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  96505. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  96506. * 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;
  96507. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  96508. */
  96509. set: function (value) {
  96510. this.imageProcessingConfiguration.colorCurves = value;
  96511. },
  96512. enumerable: true,
  96513. configurable: true
  96514. });
  96515. /**
  96516. * The entire material has been created in order to prevent overdraw.
  96517. * @returns false
  96518. */
  96519. BackgroundMaterial.prototype.needAlphaTesting = function () {
  96520. return true;
  96521. };
  96522. /**
  96523. * The entire material has been created in order to prevent overdraw.
  96524. * @returns true if blending is enable
  96525. */
  96526. BackgroundMaterial.prototype.needAlphaBlending = function () {
  96527. return ((this.alpha < 0) || (this._diffuseTexture != null && this._diffuseTexture.hasAlpha));
  96528. };
  96529. /**
  96530. * Checks wether the material is ready to be rendered for a given mesh.
  96531. * @param mesh The mesh to render
  96532. * @param subMesh The submesh to check against
  96533. * @param useInstances Specify wether or not the material is used with instances
  96534. * @returns true if all the dependencies are ready (Textures, Effects...)
  96535. */
  96536. BackgroundMaterial.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  96537. var _this = this;
  96538. if (useInstances === void 0) { useInstances = false; }
  96539. if (subMesh.effect && this.isFrozen) {
  96540. if (this._wasPreviouslyReady) {
  96541. return true;
  96542. }
  96543. }
  96544. if (!subMesh._materialDefines) {
  96545. subMesh._materialDefines = new BackgroundMaterialDefines();
  96546. }
  96547. var scene = this.getScene();
  96548. var defines = subMesh._materialDefines;
  96549. if (!this.checkReadyOnEveryCall && subMesh.effect) {
  96550. if (defines._renderId === scene.getRenderId()) {
  96551. return true;
  96552. }
  96553. }
  96554. var engine = scene.getEngine();
  96555. // Lights
  96556. BABYLON.MaterialHelper.PrepareDefinesForLights(scene, mesh, defines, false, this._maxSimultaneousLights);
  96557. defines._needNormals = true;
  96558. // Textures
  96559. if (defines._areTexturesDirty) {
  96560. defines._needUVs = false;
  96561. if (scene.texturesEnabled) {
  96562. if (scene.getEngine().getCaps().textureLOD) {
  96563. defines.TEXTURELODSUPPORT = true;
  96564. }
  96565. if (this._diffuseTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  96566. if (!this._diffuseTexture.isReadyOrNotBlocking()) {
  96567. return false;
  96568. }
  96569. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._diffuseTexture, defines, "DIFFUSE");
  96570. defines.DIFFUSEHASALPHA = this._diffuseTexture.hasAlpha;
  96571. defines.GAMMADIFFUSE = this._diffuseTexture.gammaSpace;
  96572. defines.OPACITYFRESNEL = this._opacityFresnel;
  96573. }
  96574. else {
  96575. defines.DIFFUSE = false;
  96576. defines.DIFFUSEHASALPHA = false;
  96577. defines.GAMMADIFFUSE = false;
  96578. defines.OPACITYFRESNEL = false;
  96579. }
  96580. var reflectionTexture = this._reflectionTexture;
  96581. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  96582. if (!reflectionTexture.isReadyOrNotBlocking()) {
  96583. return false;
  96584. }
  96585. defines.REFLECTION = true;
  96586. defines.GAMMAREFLECTION = reflectionTexture.gammaSpace;
  96587. defines.REFLECTIONBLUR = this._reflectionBlur > 0;
  96588. defines.REFLECTIONMAP_OPPOSITEZ = this.getScene().useRightHandedSystem ? !reflectionTexture.invertZ : reflectionTexture.invertZ;
  96589. defines.LODINREFLECTIONALPHA = reflectionTexture.lodLevelInAlpha;
  96590. defines.EQUIRECTANGULAR_RELFECTION_FOV = this.useEquirectangularFOV;
  96591. defines.REFLECTIONBGR = this.switchToBGR;
  96592. if (reflectionTexture.coordinatesMode === BABYLON.Texture.INVCUBIC_MODE) {
  96593. defines.INVERTCUBICMAP = true;
  96594. }
  96595. defines.REFLECTIONMAP_3D = reflectionTexture.isCube;
  96596. switch (reflectionTexture.coordinatesMode) {
  96597. case BABYLON.Texture.CUBIC_MODE:
  96598. case BABYLON.Texture.INVCUBIC_MODE:
  96599. defines.REFLECTIONMAP_CUBIC = true;
  96600. break;
  96601. case BABYLON.Texture.EXPLICIT_MODE:
  96602. defines.REFLECTIONMAP_EXPLICIT = true;
  96603. break;
  96604. case BABYLON.Texture.PLANAR_MODE:
  96605. defines.REFLECTIONMAP_PLANAR = true;
  96606. break;
  96607. case BABYLON.Texture.PROJECTION_MODE:
  96608. defines.REFLECTIONMAP_PROJECTION = true;
  96609. break;
  96610. case BABYLON.Texture.SKYBOX_MODE:
  96611. defines.REFLECTIONMAP_SKYBOX = true;
  96612. break;
  96613. case BABYLON.Texture.SPHERICAL_MODE:
  96614. defines.REFLECTIONMAP_SPHERICAL = true;
  96615. break;
  96616. case BABYLON.Texture.EQUIRECTANGULAR_MODE:
  96617. defines.REFLECTIONMAP_EQUIRECTANGULAR = true;
  96618. break;
  96619. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MODE:
  96620. defines.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = true;
  96621. break;
  96622. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE:
  96623. defines.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = true;
  96624. break;
  96625. }
  96626. if (this.reflectionFresnel) {
  96627. defines.REFLECTIONFRESNEL = true;
  96628. defines.REFLECTIONFALLOFF = this.reflectionFalloffDistance > 0;
  96629. this._reflectionControls.x = this.reflectionAmount;
  96630. this._reflectionControls.y = this.reflectionReflectance0;
  96631. this._reflectionControls.z = this.reflectionReflectance90;
  96632. this._reflectionControls.w = 1 / this.reflectionFalloffDistance;
  96633. }
  96634. else {
  96635. defines.REFLECTIONFRESNEL = false;
  96636. defines.REFLECTIONFALLOFF = false;
  96637. }
  96638. }
  96639. else {
  96640. defines.REFLECTION = false;
  96641. defines.REFLECTIONFRESNEL = false;
  96642. defines.REFLECTIONFALLOFF = false;
  96643. defines.REFLECTIONBLUR = false;
  96644. defines.REFLECTIONMAP_3D = false;
  96645. defines.REFLECTIONMAP_SPHERICAL = false;
  96646. defines.REFLECTIONMAP_PLANAR = false;
  96647. defines.REFLECTIONMAP_CUBIC = false;
  96648. defines.REFLECTIONMAP_PROJECTION = false;
  96649. defines.REFLECTIONMAP_SKYBOX = false;
  96650. defines.REFLECTIONMAP_EXPLICIT = false;
  96651. defines.REFLECTIONMAP_EQUIRECTANGULAR = false;
  96652. defines.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  96653. defines.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false;
  96654. defines.INVERTCUBICMAP = false;
  96655. defines.REFLECTIONMAP_OPPOSITEZ = false;
  96656. defines.LODINREFLECTIONALPHA = false;
  96657. defines.GAMMAREFLECTION = false;
  96658. }
  96659. }
  96660. defines.PREMULTIPLYALPHA = (this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED || this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED_PORTERDUFF);
  96661. defines.USERGBCOLOR = this._useRGBColor;
  96662. defines.NOISE = this._enableNoise;
  96663. }
  96664. if (defines._areLightsDirty) {
  96665. defines.USEHIGHLIGHTANDSHADOWCOLORS = !this._useRGBColor && (this._primaryColorShadowLevel !== 0 || this._primaryColorHighlightLevel !== 0);
  96666. }
  96667. if (defines._areImageProcessingDirty) {
  96668. if (!this._imageProcessingConfiguration.isReady()) {
  96669. return false;
  96670. }
  96671. this._imageProcessingConfiguration.prepareDefines(defines);
  96672. }
  96673. // Misc.
  96674. BABYLON.MaterialHelper.PrepareDefinesForMisc(mesh, scene, false, this.pointsCloud, this.fogEnabled, this._shouldTurnAlphaTestOn(mesh), defines);
  96675. // Values that need to be evaluated on every frame
  96676. BABYLON.MaterialHelper.PrepareDefinesForFrameBoundValues(scene, engine, defines, useInstances);
  96677. // Attribs
  96678. if (BABYLON.MaterialHelper.PrepareDefinesForAttributes(mesh, defines, false, true, false)) {
  96679. if (mesh) {
  96680. if (!scene.getEngine().getCaps().standardDerivatives && !mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  96681. mesh.createNormals(true);
  96682. BABYLON.Tools.Warn("BackgroundMaterial: Normals have been created for the mesh: " + mesh.name);
  96683. }
  96684. }
  96685. }
  96686. // Get correct effect
  96687. if (defines.isDirty) {
  96688. defines.markAsProcessed();
  96689. scene.resetCachedMaterial();
  96690. // Fallbacks
  96691. var fallbacks = new BABYLON.EffectFallbacks();
  96692. if (defines.FOG) {
  96693. fallbacks.addFallback(0, "FOG");
  96694. }
  96695. if (defines.POINTSIZE) {
  96696. fallbacks.addFallback(1, "POINTSIZE");
  96697. }
  96698. BABYLON.MaterialHelper.HandleFallbacksForShadows(defines, fallbacks, this._maxSimultaneousLights);
  96699. if (defines.NUM_BONE_INFLUENCERS > 0) {
  96700. fallbacks.addCPUSkinningFallback(0, mesh);
  96701. }
  96702. //Attributes
  96703. var attribs = [BABYLON.VertexBuffer.PositionKind];
  96704. if (defines.NORMAL) {
  96705. attribs.push(BABYLON.VertexBuffer.NormalKind);
  96706. }
  96707. if (defines.UV1) {
  96708. attribs.push(BABYLON.VertexBuffer.UVKind);
  96709. }
  96710. if (defines.UV2) {
  96711. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  96712. }
  96713. BABYLON.MaterialHelper.PrepareAttributesForBones(attribs, mesh, defines, fallbacks);
  96714. BABYLON.MaterialHelper.PrepareAttributesForInstances(attribs, defines);
  96715. var uniforms = ["world", "view", "viewProjection", "vEyePosition", "vLightsType",
  96716. "vFogInfos", "vFogColor", "pointSize",
  96717. "vClipPlane", "mBones",
  96718. "vPrimaryColor", "vPrimaryColorShadow",
  96719. "vReflectionInfos", "reflectionMatrix", "vReflectionMicrosurfaceInfos", "fFovMultiplier",
  96720. "shadowLevel", "alpha",
  96721. "vBackgroundCenter", "vReflectionControl",
  96722. "vDiffuseInfos", "diffuseMatrix",
  96723. ];
  96724. var samplers = ["diffuseSampler", "reflectionSampler", "reflectionSamplerLow", "reflectionSamplerHigh"];
  96725. var uniformBuffers = ["Material", "Scene"];
  96726. BABYLON.ImageProcessingConfiguration.PrepareUniforms(uniforms, defines);
  96727. BABYLON.ImageProcessingConfiguration.PrepareSamplers(samplers, defines);
  96728. BABYLON.MaterialHelper.PrepareUniformsAndSamplersList({
  96729. uniformsNames: uniforms,
  96730. uniformBuffersNames: uniformBuffers,
  96731. samplers: samplers,
  96732. defines: defines,
  96733. maxSimultaneousLights: this._maxSimultaneousLights
  96734. });
  96735. var onCompiled = function (effect) {
  96736. if (_this.onCompiled) {
  96737. _this.onCompiled(effect);
  96738. }
  96739. _this.bindSceneUniformBuffer(effect, scene.getSceneUniformBuffer());
  96740. };
  96741. var join = defines.toString();
  96742. subMesh.setEffect(scene.getEngine().createEffect("background", {
  96743. attributes: attribs,
  96744. uniformsNames: uniforms,
  96745. uniformBuffersNames: uniformBuffers,
  96746. samplers: samplers,
  96747. defines: join,
  96748. fallbacks: fallbacks,
  96749. onCompiled: onCompiled,
  96750. onError: this.onError,
  96751. indexParameters: { maxSimultaneousLights: this._maxSimultaneousLights }
  96752. }, engine), defines);
  96753. this.buildUniformLayout();
  96754. }
  96755. if (!subMesh.effect || !subMesh.effect.isReady()) {
  96756. return false;
  96757. }
  96758. defines._renderId = scene.getRenderId();
  96759. this._wasPreviouslyReady = true;
  96760. return true;
  96761. };
  96762. /**
  96763. * Compute the primary color according to the chosen perceptual color.
  96764. */
  96765. BackgroundMaterial.prototype._computePrimaryColorFromPerceptualColor = function () {
  96766. if (!this.__perceptualColor) {
  96767. return;
  96768. }
  96769. this._primaryColor.copyFrom(this.__perceptualColor);
  96770. // Revert gamma space.
  96771. this._primaryColor.toLinearSpaceToRef(this._primaryColor);
  96772. // Revert image processing configuration.
  96773. if (this._imageProcessingConfiguration) {
  96774. // Revert Exposure.
  96775. this._primaryColor.scaleToRef(1 / this._imageProcessingConfiguration.exposure, this._primaryColor);
  96776. }
  96777. this._computePrimaryColors();
  96778. };
  96779. /**
  96780. * Compute the highlights and shadow colors according to their chosen levels.
  96781. */
  96782. BackgroundMaterial.prototype._computePrimaryColors = function () {
  96783. if (this._primaryColorShadowLevel === 0 && this._primaryColorHighlightLevel === 0) {
  96784. return;
  96785. }
  96786. // Find the highlight color based on the configuration.
  96787. this._primaryColor.scaleToRef(this._primaryColorShadowLevel, this._primaryShadowColor);
  96788. this._primaryColor.subtractToRef(this._primaryShadowColor, this._primaryShadowColor);
  96789. // Find the shadow color based on the configuration.
  96790. this._white.subtractToRef(this._primaryColor, this._primaryHighlightColor);
  96791. this._primaryHighlightColor.scaleToRef(this._primaryColorHighlightLevel, this._primaryHighlightColor);
  96792. this._primaryColor.addToRef(this._primaryHighlightColor, this._primaryHighlightColor);
  96793. };
  96794. /**
  96795. * Build the uniform buffer used in the material.
  96796. */
  96797. BackgroundMaterial.prototype.buildUniformLayout = function () {
  96798. // Order is important !
  96799. this._uniformBuffer.addUniform("vPrimaryColor", 4);
  96800. this._uniformBuffer.addUniform("vPrimaryColorShadow", 4);
  96801. this._uniformBuffer.addUniform("vDiffuseInfos", 2);
  96802. this._uniformBuffer.addUniform("vReflectionInfos", 2);
  96803. this._uniformBuffer.addUniform("diffuseMatrix", 16);
  96804. this._uniformBuffer.addUniform("reflectionMatrix", 16);
  96805. this._uniformBuffer.addUniform("vReflectionMicrosurfaceInfos", 3);
  96806. this._uniformBuffer.addUniform("fFovMultiplier", 1);
  96807. this._uniformBuffer.addUniform("pointSize", 1);
  96808. this._uniformBuffer.addUniform("shadowLevel", 1);
  96809. this._uniformBuffer.addUniform("alpha", 1);
  96810. this._uniformBuffer.addUniform("vBackgroundCenter", 3);
  96811. this._uniformBuffer.addUniform("vReflectionControl", 4);
  96812. this._uniformBuffer.create();
  96813. };
  96814. /**
  96815. * Unbind the material.
  96816. */
  96817. BackgroundMaterial.prototype.unbind = function () {
  96818. if (this._diffuseTexture && this._diffuseTexture.isRenderTarget) {
  96819. this._uniformBuffer.setTexture("diffuseSampler", null);
  96820. }
  96821. if (this._reflectionTexture && this._reflectionTexture.isRenderTarget) {
  96822. this._uniformBuffer.setTexture("reflectionSampler", null);
  96823. }
  96824. _super.prototype.unbind.call(this);
  96825. };
  96826. /**
  96827. * Bind only the world matrix to the material.
  96828. * @param world The world matrix to bind.
  96829. */
  96830. BackgroundMaterial.prototype.bindOnlyWorldMatrix = function (world) {
  96831. this._activeEffect.setMatrix("world", world);
  96832. };
  96833. /**
  96834. * Bind the material for a dedicated submeh (every used meshes will be considered opaque).
  96835. * @param world The world matrix to bind.
  96836. * @param subMesh The submesh to bind for.
  96837. */
  96838. BackgroundMaterial.prototype.bindForSubMesh = function (world, mesh, subMesh) {
  96839. var scene = this.getScene();
  96840. var defines = subMesh._materialDefines;
  96841. if (!defines) {
  96842. return;
  96843. }
  96844. var effect = subMesh.effect;
  96845. if (!effect) {
  96846. return;
  96847. }
  96848. this._activeEffect = effect;
  96849. // Matrices
  96850. this.bindOnlyWorldMatrix(world);
  96851. // Bones
  96852. BABYLON.MaterialHelper.BindBonesParameters(mesh, this._activeEffect);
  96853. var mustRebind = this._mustRebind(scene, effect, mesh.visibility);
  96854. if (mustRebind) {
  96855. this._uniformBuffer.bindToEffect(effect, "Material");
  96856. this.bindViewProjection(effect);
  96857. var reflectionTexture = this._reflectionTexture;
  96858. if (!this._uniformBuffer.useUbo || !this.isFrozen || !this._uniformBuffer.isSync) {
  96859. // Texture uniforms
  96860. if (scene.texturesEnabled) {
  96861. if (this._diffuseTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  96862. this._uniformBuffer.updateFloat2("vDiffuseInfos", this._diffuseTexture.coordinatesIndex, this._diffuseTexture.level);
  96863. BABYLON.MaterialHelper.BindTextureMatrix(this._diffuseTexture, this._uniformBuffer, "diffuse");
  96864. }
  96865. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  96866. this._uniformBuffer.updateMatrix("reflectionMatrix", reflectionTexture.getReflectionTextureMatrix());
  96867. this._uniformBuffer.updateFloat2("vReflectionInfos", reflectionTexture.level, this._reflectionBlur);
  96868. this._uniformBuffer.updateFloat3("vReflectionMicrosurfaceInfos", reflectionTexture.getSize().width, reflectionTexture.lodGenerationScale, reflectionTexture.lodGenerationOffset);
  96869. }
  96870. }
  96871. if (this.shadowLevel > 0) {
  96872. this._uniformBuffer.updateFloat("shadowLevel", this.shadowLevel);
  96873. }
  96874. this._uniformBuffer.updateFloat("alpha", this.alpha);
  96875. // Point size
  96876. if (this.pointsCloud) {
  96877. this._uniformBuffer.updateFloat("pointSize", this.pointSize);
  96878. }
  96879. if (defines.USEHIGHLIGHTANDSHADOWCOLORS) {
  96880. this._uniformBuffer.updateColor4("vPrimaryColor", this._primaryHighlightColor, 1.0);
  96881. this._uniformBuffer.updateColor4("vPrimaryColorShadow", this._primaryShadowColor, 1.0);
  96882. }
  96883. else {
  96884. this._uniformBuffer.updateColor4("vPrimaryColor", this._primaryColor, 1.0);
  96885. }
  96886. }
  96887. this._uniformBuffer.updateFloat("fFovMultiplier", this._fovMultiplier);
  96888. // Textures
  96889. if (scene.texturesEnabled) {
  96890. if (this._diffuseTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  96891. this._uniformBuffer.setTexture("diffuseSampler", this._diffuseTexture);
  96892. }
  96893. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  96894. if (defines.REFLECTIONBLUR && defines.TEXTURELODSUPPORT) {
  96895. this._uniformBuffer.setTexture("reflectionSampler", reflectionTexture);
  96896. }
  96897. else if (!defines.REFLECTIONBLUR) {
  96898. this._uniformBuffer.setTexture("reflectionSampler", reflectionTexture);
  96899. }
  96900. else {
  96901. this._uniformBuffer.setTexture("reflectionSampler", reflectionTexture._lodTextureMid || reflectionTexture);
  96902. this._uniformBuffer.setTexture("reflectionSamplerLow", reflectionTexture._lodTextureLow || reflectionTexture);
  96903. this._uniformBuffer.setTexture("reflectionSamplerHigh", reflectionTexture._lodTextureHigh || reflectionTexture);
  96904. }
  96905. if (defines.REFLECTIONFRESNEL) {
  96906. this._uniformBuffer.updateFloat3("vBackgroundCenter", this.sceneCenter.x, this.sceneCenter.y, this.sceneCenter.z);
  96907. this._uniformBuffer.updateFloat4("vReflectionControl", this._reflectionControls.x, this._reflectionControls.y, this._reflectionControls.z, this._reflectionControls.w);
  96908. }
  96909. }
  96910. }
  96911. // Clip plane
  96912. BABYLON.MaterialHelper.BindClipPlane(this._activeEffect, scene);
  96913. BABYLON.MaterialHelper.BindEyePosition(effect, scene);
  96914. }
  96915. if (mustRebind || !this.isFrozen) {
  96916. if (scene.lightsEnabled) {
  96917. BABYLON.MaterialHelper.BindLights(scene, mesh, this._activeEffect, defines, this._maxSimultaneousLights, false);
  96918. }
  96919. // View
  96920. this.bindView(effect);
  96921. // Fog
  96922. BABYLON.MaterialHelper.BindFogParameters(scene, mesh, this._activeEffect);
  96923. // image processing
  96924. this._imageProcessingConfiguration.bind(this._activeEffect);
  96925. }
  96926. this._uniformBuffer.update();
  96927. this._afterBind(mesh);
  96928. };
  96929. /**
  96930. * Dispose the material.
  96931. * @param forceDisposeEffect Force disposal of the associated effect.
  96932. * @param forceDisposeTextures Force disposal of the associated textures.
  96933. */
  96934. BackgroundMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  96935. if (forceDisposeEffect === void 0) { forceDisposeEffect = false; }
  96936. if (forceDisposeTextures === void 0) { forceDisposeTextures = false; }
  96937. if (forceDisposeTextures) {
  96938. if (this.diffuseTexture) {
  96939. this.diffuseTexture.dispose();
  96940. }
  96941. if (this.reflectionTexture) {
  96942. this.reflectionTexture.dispose();
  96943. }
  96944. }
  96945. this._renderTargets.dispose();
  96946. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  96947. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  96948. }
  96949. _super.prototype.dispose.call(this, forceDisposeEffect);
  96950. };
  96951. /**
  96952. * Clones the material.
  96953. * @param name The cloned name.
  96954. * @returns The cloned material.
  96955. */
  96956. BackgroundMaterial.prototype.clone = function (name) {
  96957. var _this = this;
  96958. return BABYLON.SerializationHelper.Clone(function () { return new BackgroundMaterial(name, _this.getScene()); }, this);
  96959. };
  96960. /**
  96961. * Serializes the current material to its JSON representation.
  96962. * @returns The JSON representation.
  96963. */
  96964. BackgroundMaterial.prototype.serialize = function () {
  96965. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  96966. serializationObject.customType = "BABYLON.BackgroundMaterial";
  96967. return serializationObject;
  96968. };
  96969. /**
  96970. * Gets the class name of the material
  96971. * @returns "BackgroundMaterial"
  96972. */
  96973. BackgroundMaterial.prototype.getClassName = function () {
  96974. return "BackgroundMaterial";
  96975. };
  96976. /**
  96977. * Parse a JSON input to create back a background material.
  96978. * @param source The JSON data to parse
  96979. * @param scene The scene to create the parsed material in
  96980. * @param rootUrl The root url of the assets the material depends upon
  96981. * @returns the instantiated BackgroundMaterial.
  96982. */
  96983. BackgroundMaterial.Parse = function (source, scene, rootUrl) {
  96984. return BABYLON.SerializationHelper.Parse(function () { return new BackgroundMaterial(source.name, scene); }, source, scene, rootUrl);
  96985. };
  96986. /**
  96987. * Standard reflectance value at parallel view angle.
  96988. */
  96989. BackgroundMaterial.StandardReflectance0 = 0.05;
  96990. /**
  96991. * Standard reflectance value at grazing angle.
  96992. */
  96993. BackgroundMaterial.StandardReflectance90 = 0.5;
  96994. __decorate([
  96995. BABYLON.serializeAsColor3()
  96996. ], BackgroundMaterial.prototype, "_primaryColor", void 0);
  96997. __decorate([
  96998. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  96999. ], BackgroundMaterial.prototype, "primaryColor", void 0);
  97000. __decorate([
  97001. BABYLON.serializeAsColor3()
  97002. ], BackgroundMaterial.prototype, "__perceptualColor", void 0);
  97003. __decorate([
  97004. BABYLON.serialize()
  97005. ], BackgroundMaterial.prototype, "_primaryColorShadowLevel", void 0);
  97006. __decorate([
  97007. BABYLON.serialize()
  97008. ], BackgroundMaterial.prototype, "_primaryColorHighlightLevel", void 0);
  97009. __decorate([
  97010. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  97011. ], BackgroundMaterial.prototype, "primaryColorHighlightLevel", null);
  97012. __decorate([
  97013. BABYLON.serializeAsTexture()
  97014. ], BackgroundMaterial.prototype, "_reflectionTexture", void 0);
  97015. __decorate([
  97016. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  97017. ], BackgroundMaterial.prototype, "reflectionTexture", void 0);
  97018. __decorate([
  97019. BABYLON.serialize()
  97020. ], BackgroundMaterial.prototype, "_reflectionBlur", void 0);
  97021. __decorate([
  97022. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  97023. ], BackgroundMaterial.prototype, "reflectionBlur", void 0);
  97024. __decorate([
  97025. BABYLON.serializeAsTexture()
  97026. ], BackgroundMaterial.prototype, "_diffuseTexture", void 0);
  97027. __decorate([
  97028. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  97029. ], BackgroundMaterial.prototype, "diffuseTexture", void 0);
  97030. __decorate([
  97031. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  97032. ], BackgroundMaterial.prototype, "shadowLights", void 0);
  97033. __decorate([
  97034. BABYLON.serialize()
  97035. ], BackgroundMaterial.prototype, "_shadowLevel", void 0);
  97036. __decorate([
  97037. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  97038. ], BackgroundMaterial.prototype, "shadowLevel", void 0);
  97039. __decorate([
  97040. BABYLON.serializeAsVector3()
  97041. ], BackgroundMaterial.prototype, "_sceneCenter", void 0);
  97042. __decorate([
  97043. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  97044. ], BackgroundMaterial.prototype, "sceneCenter", void 0);
  97045. __decorate([
  97046. BABYLON.serialize()
  97047. ], BackgroundMaterial.prototype, "_opacityFresnel", void 0);
  97048. __decorate([
  97049. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  97050. ], BackgroundMaterial.prototype, "opacityFresnel", void 0);
  97051. __decorate([
  97052. BABYLON.serialize()
  97053. ], BackgroundMaterial.prototype, "_reflectionFresnel", void 0);
  97054. __decorate([
  97055. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  97056. ], BackgroundMaterial.prototype, "reflectionFresnel", void 0);
  97057. __decorate([
  97058. BABYLON.serialize()
  97059. ], BackgroundMaterial.prototype, "_reflectionFalloffDistance", void 0);
  97060. __decorate([
  97061. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  97062. ], BackgroundMaterial.prototype, "reflectionFalloffDistance", void 0);
  97063. __decorate([
  97064. BABYLON.serialize()
  97065. ], BackgroundMaterial.prototype, "_reflectionAmount", void 0);
  97066. __decorate([
  97067. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  97068. ], BackgroundMaterial.prototype, "reflectionAmount", void 0);
  97069. __decorate([
  97070. BABYLON.serialize()
  97071. ], BackgroundMaterial.prototype, "_reflectionReflectance0", void 0);
  97072. __decorate([
  97073. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  97074. ], BackgroundMaterial.prototype, "reflectionReflectance0", void 0);
  97075. __decorate([
  97076. BABYLON.serialize()
  97077. ], BackgroundMaterial.prototype, "_reflectionReflectance90", void 0);
  97078. __decorate([
  97079. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  97080. ], BackgroundMaterial.prototype, "reflectionReflectance90", void 0);
  97081. __decorate([
  97082. BABYLON.serialize()
  97083. ], BackgroundMaterial.prototype, "_useRGBColor", void 0);
  97084. __decorate([
  97085. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  97086. ], BackgroundMaterial.prototype, "useRGBColor", void 0);
  97087. __decorate([
  97088. BABYLON.serialize()
  97089. ], BackgroundMaterial.prototype, "_enableNoise", void 0);
  97090. __decorate([
  97091. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  97092. ], BackgroundMaterial.prototype, "enableNoise", void 0);
  97093. __decorate([
  97094. BABYLON.serialize()
  97095. ], BackgroundMaterial.prototype, "_maxSimultaneousLights", void 0);
  97096. __decorate([
  97097. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  97098. ], BackgroundMaterial.prototype, "maxSimultaneousLights", void 0);
  97099. __decorate([
  97100. BABYLON.serializeAsImageProcessingConfiguration()
  97101. ], BackgroundMaterial.prototype, "_imageProcessingConfiguration", void 0);
  97102. return BackgroundMaterial;
  97103. }(BABYLON.PushMaterial));
  97104. BABYLON.BackgroundMaterial = BackgroundMaterial;
  97105. })(BABYLON || (BABYLON = {}));
  97106. //# sourceMappingURL=babylon.backgroundMaterial.js.map
  97107. var __assign = (this && this.__assign) || Object.assign || function(t) {
  97108. for (var s, i = 1, n = arguments.length; i < n; i++) {
  97109. s = arguments[i];
  97110. for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
  97111. t[p] = s[p];
  97112. }
  97113. return t;
  97114. };
  97115. var BABYLON;
  97116. (function (BABYLON) {
  97117. /**
  97118. * The Environment helper class can be used to add a fully featuread none expensive background to your scene.
  97119. * It includes by default a skybox and a ground relying on the BackgroundMaterial.
  97120. * It also helps with the default setup of your imageProcessing configuration.
  97121. */
  97122. var EnvironmentHelper = /** @class */ (function () {
  97123. /**
  97124. * constructor
  97125. * @param options
  97126. * @param scene The scene to add the material to
  97127. */
  97128. function EnvironmentHelper(options, scene) {
  97129. var _this = this;
  97130. this._errorHandler = function (message, exception) {
  97131. _this.onErrorObservable.notifyObservers({ message: message, exception: exception });
  97132. };
  97133. this._options = __assign({}, EnvironmentHelper._getDefaultOptions(), options);
  97134. this._scene = scene;
  97135. this.onErrorObservable = new BABYLON.Observable();
  97136. this._setupBackground();
  97137. this._setupImageProcessing();
  97138. }
  97139. /**
  97140. * Creates the default options for the helper.
  97141. */
  97142. EnvironmentHelper._getDefaultOptions = function () {
  97143. return {
  97144. createGround: true,
  97145. groundSize: 15,
  97146. groundTexture: this._groundTextureCDNUrl,
  97147. groundColor: new BABYLON.Color3(0.2, 0.2, 0.3).toLinearSpace().scale(3),
  97148. groundOpacity: 0.9,
  97149. enableGroundShadow: true,
  97150. groundShadowLevel: 0.5,
  97151. enableGroundMirror: false,
  97152. groundMirrorSizeRatio: 0.3,
  97153. groundMirrorBlurKernel: 64,
  97154. groundMirrorAmount: 1,
  97155. groundMirrorFresnelWeight: 1,
  97156. groundMirrorFallOffDistance: 0,
  97157. groundMirrorTextureType: BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT,
  97158. groundYBias: 0.00001,
  97159. createSkybox: true,
  97160. skyboxSize: 20,
  97161. skyboxTexture: this._skyboxTextureCDNUrl,
  97162. skyboxColor: new BABYLON.Color3(0.2, 0.2, 0.3).toLinearSpace().scale(3),
  97163. backgroundYRotation: 0,
  97164. sizeAuto: true,
  97165. rootPosition: BABYLON.Vector3.Zero(),
  97166. setupImageProcessing: true,
  97167. environmentTexture: this._environmentTextureCDNUrl,
  97168. cameraExposure: 0.8,
  97169. cameraContrast: 1.2,
  97170. toneMappingEnabled: true,
  97171. };
  97172. };
  97173. Object.defineProperty(EnvironmentHelper.prototype, "rootMesh", {
  97174. /**
  97175. * Gets the root mesh created by the helper.
  97176. */
  97177. get: function () {
  97178. return this._rootMesh;
  97179. },
  97180. enumerable: true,
  97181. configurable: true
  97182. });
  97183. Object.defineProperty(EnvironmentHelper.prototype, "skybox", {
  97184. /**
  97185. * Gets the skybox created by the helper.
  97186. */
  97187. get: function () {
  97188. return this._skybox;
  97189. },
  97190. enumerable: true,
  97191. configurable: true
  97192. });
  97193. Object.defineProperty(EnvironmentHelper.prototype, "skyboxTexture", {
  97194. /**
  97195. * Gets the skybox texture created by the helper.
  97196. */
  97197. get: function () {
  97198. return this._skyboxTexture;
  97199. },
  97200. enumerable: true,
  97201. configurable: true
  97202. });
  97203. Object.defineProperty(EnvironmentHelper.prototype, "skyboxMaterial", {
  97204. /**
  97205. * Gets the skybox material created by the helper.
  97206. */
  97207. get: function () {
  97208. return this._skyboxMaterial;
  97209. },
  97210. enumerable: true,
  97211. configurable: true
  97212. });
  97213. Object.defineProperty(EnvironmentHelper.prototype, "ground", {
  97214. /**
  97215. * Gets the ground mesh created by the helper.
  97216. */
  97217. get: function () {
  97218. return this._ground;
  97219. },
  97220. enumerable: true,
  97221. configurable: true
  97222. });
  97223. Object.defineProperty(EnvironmentHelper.prototype, "groundTexture", {
  97224. /**
  97225. * Gets the ground texture created by the helper.
  97226. */
  97227. get: function () {
  97228. return this._groundTexture;
  97229. },
  97230. enumerable: true,
  97231. configurable: true
  97232. });
  97233. Object.defineProperty(EnvironmentHelper.prototype, "groundMirror", {
  97234. /**
  97235. * Gets the ground mirror created by the helper.
  97236. */
  97237. get: function () {
  97238. return this._groundMirror;
  97239. },
  97240. enumerable: true,
  97241. configurable: true
  97242. });
  97243. Object.defineProperty(EnvironmentHelper.prototype, "groundMirrorRenderList", {
  97244. /**
  97245. * Gets the ground mirror render list to helps pushing the meshes
  97246. * you wish in the ground reflection.
  97247. */
  97248. get: function () {
  97249. if (this._groundMirror) {
  97250. return this._groundMirror.renderList;
  97251. }
  97252. return null;
  97253. },
  97254. enumerable: true,
  97255. configurable: true
  97256. });
  97257. Object.defineProperty(EnvironmentHelper.prototype, "groundMaterial", {
  97258. /**
  97259. * Gets the ground material created by the helper.
  97260. */
  97261. get: function () {
  97262. return this._groundMaterial;
  97263. },
  97264. enumerable: true,
  97265. configurable: true
  97266. });
  97267. /**
  97268. * Updates the background according to the new options
  97269. * @param options
  97270. */
  97271. EnvironmentHelper.prototype.updateOptions = function (options) {
  97272. var newOptions = __assign({}, this._options, options);
  97273. if (this._ground && !newOptions.createGround) {
  97274. this._ground.dispose();
  97275. this._ground = null;
  97276. }
  97277. if (this._groundMaterial && !newOptions.createGround) {
  97278. this._groundMaterial.dispose();
  97279. this._groundMaterial = null;
  97280. }
  97281. if (this._groundTexture) {
  97282. if (this._options.groundTexture != newOptions.groundTexture) {
  97283. this._groundTexture.dispose();
  97284. this._groundTexture = null;
  97285. }
  97286. }
  97287. if (this._skybox && !newOptions.createSkybox) {
  97288. this._skybox.dispose();
  97289. this._skybox = null;
  97290. }
  97291. if (this._skyboxMaterial && !newOptions.createSkybox) {
  97292. this._skyboxMaterial.dispose();
  97293. this._skyboxMaterial = null;
  97294. }
  97295. if (this._skyboxTexture) {
  97296. if (this._options.skyboxTexture != newOptions.skyboxTexture) {
  97297. this._skyboxTexture.dispose();
  97298. this._skyboxTexture = null;
  97299. }
  97300. }
  97301. if (this._groundMirror && !newOptions.enableGroundMirror) {
  97302. this._groundMirror.dispose();
  97303. this._groundMirror = null;
  97304. }
  97305. if (this._scene.environmentTexture) {
  97306. if (this._options.environmentTexture != newOptions.environmentTexture) {
  97307. this._scene.environmentTexture.dispose();
  97308. }
  97309. }
  97310. this._options = newOptions;
  97311. this._setupBackground();
  97312. this._setupImageProcessing();
  97313. };
  97314. /**
  97315. * Sets the primary color of all the available elements.
  97316. * @param color the main color to affect to the ground and the background
  97317. */
  97318. EnvironmentHelper.prototype.setMainColor = function (color) {
  97319. if (this.groundMaterial) {
  97320. this.groundMaterial.primaryColor = color;
  97321. }
  97322. if (this.skyboxMaterial) {
  97323. this.skyboxMaterial.primaryColor = color;
  97324. }
  97325. if (this.groundMirror) {
  97326. this.groundMirror.clearColor = new BABYLON.Color4(color.r, color.g, color.b, 1.0);
  97327. }
  97328. };
  97329. /**
  97330. * Setup the image processing according to the specified options.
  97331. */
  97332. EnvironmentHelper.prototype._setupImageProcessing = function () {
  97333. if (this._options.setupImageProcessing) {
  97334. this._scene.imageProcessingConfiguration.contrast = this._options.cameraContrast;
  97335. this._scene.imageProcessingConfiguration.exposure = this._options.cameraExposure;
  97336. this._scene.imageProcessingConfiguration.toneMappingEnabled = this._options.toneMappingEnabled;
  97337. this._setupEnvironmentTexture();
  97338. }
  97339. };
  97340. /**
  97341. * Setup the environment texture according to the specified options.
  97342. */
  97343. EnvironmentHelper.prototype._setupEnvironmentTexture = function () {
  97344. if (this._scene.environmentTexture) {
  97345. return;
  97346. }
  97347. if (this._options.environmentTexture instanceof BABYLON.BaseTexture) {
  97348. this._scene.environmentTexture = this._options.environmentTexture;
  97349. return;
  97350. }
  97351. var environmentTexture = BABYLON.CubeTexture.CreateFromPrefilteredData(this._options.environmentTexture, this._scene);
  97352. this._scene.environmentTexture = environmentTexture;
  97353. };
  97354. /**
  97355. * Setup the background according to the specified options.
  97356. */
  97357. EnvironmentHelper.prototype._setupBackground = function () {
  97358. if (!this._rootMesh) {
  97359. this._rootMesh = new BABYLON.Mesh("BackgroundHelper", this._scene);
  97360. }
  97361. this._rootMesh.rotation.y = this._options.backgroundYRotation;
  97362. var sceneSize = this._getSceneSize();
  97363. if (this._options.createGround) {
  97364. this._setupGround(sceneSize);
  97365. this._setupGroundMaterial();
  97366. this._setupGroundDiffuseTexture();
  97367. if (this._options.enableGroundMirror) {
  97368. this._setupGroundMirrorTexture(sceneSize);
  97369. }
  97370. this._setupMirrorInGroundMaterial();
  97371. }
  97372. if (this._options.createSkybox) {
  97373. this._setupSkybox(sceneSize);
  97374. this._setupSkyboxMaterial();
  97375. this._setupSkyboxReflectionTexture();
  97376. }
  97377. this._rootMesh.position.x = sceneSize.rootPosition.x;
  97378. this._rootMesh.position.z = sceneSize.rootPosition.z;
  97379. this._rootMesh.position.y = sceneSize.rootPosition.y;
  97380. };
  97381. /**
  97382. * Get the scene sizes according to the setup.
  97383. */
  97384. EnvironmentHelper.prototype._getSceneSize = function () {
  97385. var _this = this;
  97386. var groundSize = this._options.groundSize;
  97387. var skyboxSize = this._options.skyboxSize;
  97388. var rootPosition = this._options.rootPosition;
  97389. if (!this._scene.meshes || this._scene.meshes.length === 1) { // 1 only means the root of the helper.
  97390. return { groundSize: groundSize, skyboxSize: skyboxSize, rootPosition: rootPosition };
  97391. }
  97392. var sceneExtends = this._scene.getWorldExtends(function (mesh) {
  97393. return (mesh !== _this._ground && mesh !== _this._rootMesh && mesh !== _this._skybox);
  97394. });
  97395. var sceneDiagonal = sceneExtends.max.subtract(sceneExtends.min);
  97396. if (this._options.sizeAuto) {
  97397. if (this._scene.activeCamera instanceof BABYLON.ArcRotateCamera &&
  97398. this._scene.activeCamera.upperRadiusLimit) {
  97399. groundSize = this._scene.activeCamera.upperRadiusLimit * 2;
  97400. skyboxSize = groundSize;
  97401. }
  97402. var sceneDiagonalLenght = sceneDiagonal.length();
  97403. if (sceneDiagonalLenght > groundSize) {
  97404. groundSize = sceneDiagonalLenght * 2;
  97405. skyboxSize = groundSize;
  97406. }
  97407. // 10 % bigger.
  97408. groundSize *= 1.1;
  97409. skyboxSize *= 1.5;
  97410. rootPosition = sceneExtends.min.add(sceneDiagonal.scale(0.5));
  97411. rootPosition.y = sceneExtends.min.y - this._options.groundYBias;
  97412. }
  97413. return { groundSize: groundSize, skyboxSize: skyboxSize, rootPosition: rootPosition };
  97414. };
  97415. /**
  97416. * Setup the ground according to the specified options.
  97417. */
  97418. EnvironmentHelper.prototype._setupGround = function (sceneSize) {
  97419. var _this = this;
  97420. if (!this._ground) {
  97421. this._ground = BABYLON.Mesh.CreatePlane("BackgroundPlane", sceneSize.groundSize, this._scene);
  97422. this._ground.rotation.x = Math.PI / 2; // Face up by default.
  97423. this._ground.parent = this._rootMesh;
  97424. this._ground.onDisposeObservable.add(function () { _this._ground = null; });
  97425. }
  97426. this._ground.receiveShadows = this._options.enableGroundShadow;
  97427. };
  97428. /**
  97429. * Setup the ground material according to the specified options.
  97430. */
  97431. EnvironmentHelper.prototype._setupGroundMaterial = function () {
  97432. if (!this._groundMaterial) {
  97433. this._groundMaterial = new BABYLON.BackgroundMaterial("BackgroundPlaneMaterial", this._scene);
  97434. }
  97435. this._groundMaterial.alpha = this._options.groundOpacity;
  97436. this._groundMaterial.alphaMode = BABYLON.Engine.ALPHA_PREMULTIPLIED_PORTERDUFF;
  97437. this._groundMaterial.shadowLevel = this._options.groundShadowLevel;
  97438. this._groundMaterial.primaryColor = this._options.groundColor;
  97439. this._groundMaterial.useRGBColor = false;
  97440. this._groundMaterial.enableNoise = true;
  97441. if (this._ground) {
  97442. this._ground.material = this._groundMaterial;
  97443. }
  97444. };
  97445. /**
  97446. * Setup the ground diffuse texture according to the specified options.
  97447. */
  97448. EnvironmentHelper.prototype._setupGroundDiffuseTexture = function () {
  97449. if (!this._groundMaterial) {
  97450. return;
  97451. }
  97452. if (this._groundTexture) {
  97453. return;
  97454. }
  97455. if (this._options.groundTexture instanceof BABYLON.BaseTexture) {
  97456. this._groundMaterial.diffuseTexture = this._options.groundTexture;
  97457. return;
  97458. }
  97459. var diffuseTexture = new BABYLON.Texture(this._options.groundTexture, this._scene, undefined, undefined, undefined, undefined, this._errorHandler);
  97460. diffuseTexture.gammaSpace = false;
  97461. diffuseTexture.hasAlpha = true;
  97462. this._groundMaterial.diffuseTexture = diffuseTexture;
  97463. };
  97464. /**
  97465. * Setup the ground mirror texture according to the specified options.
  97466. */
  97467. EnvironmentHelper.prototype._setupGroundMirrorTexture = function (sceneSize) {
  97468. var wrapping = BABYLON.Texture.CLAMP_ADDRESSMODE;
  97469. if (!this._groundMirror) {
  97470. this._groundMirror = new BABYLON.MirrorTexture("BackgroundPlaneMirrorTexture", { ratio: this._options.groundMirrorSizeRatio }, this._scene, false, this._options.groundMirrorTextureType, BABYLON.Texture.BILINEAR_SAMPLINGMODE, true);
  97471. this._groundMirror.mirrorPlane = new BABYLON.Plane(0, -1, 0, sceneSize.rootPosition.y);
  97472. this._groundMirror.anisotropicFilteringLevel = 1;
  97473. this._groundMirror.wrapU = wrapping;
  97474. this._groundMirror.wrapV = wrapping;
  97475. this._groundMirror.gammaSpace = false;
  97476. if (this._groundMirror.renderList) {
  97477. for (var i = 0; i < this._scene.meshes.length; i++) {
  97478. var mesh = this._scene.meshes[i];
  97479. if (mesh !== this._ground &&
  97480. mesh !== this._skybox &&
  97481. mesh !== this._rootMesh) {
  97482. this._groundMirror.renderList.push(mesh);
  97483. }
  97484. }
  97485. }
  97486. }
  97487. this._groundMirror.clearColor = new BABYLON.Color4(this._options.groundColor.r, this._options.groundColor.g, this._options.groundColor.b, 1);
  97488. this._groundMirror.adaptiveBlurKernel = this._options.groundMirrorBlurKernel;
  97489. };
  97490. /**
  97491. * Setup the ground to receive the mirror texture.
  97492. */
  97493. EnvironmentHelper.prototype._setupMirrorInGroundMaterial = function () {
  97494. if (this._groundMaterial) {
  97495. this._groundMaterial.reflectionTexture = this._groundMirror;
  97496. this._groundMaterial.reflectionFresnel = true;
  97497. this._groundMaterial.reflectionAmount = this._options.groundMirrorAmount;
  97498. this._groundMaterial.reflectionStandardFresnelWeight = this._options.groundMirrorFresnelWeight;
  97499. this._groundMaterial.reflectionFalloffDistance = this._options.groundMirrorFallOffDistance;
  97500. }
  97501. };
  97502. /**
  97503. * Setup the skybox according to the specified options.
  97504. */
  97505. EnvironmentHelper.prototype._setupSkybox = function (sceneSize) {
  97506. var _this = this;
  97507. if (!this._skybox) {
  97508. this._skybox = BABYLON.Mesh.CreateBox("BackgroundSkybox", sceneSize.skyboxSize, this._scene, undefined, BABYLON.Mesh.BACKSIDE);
  97509. this._skybox.onDisposeObservable.add(function () { _this._skybox = null; });
  97510. }
  97511. this._skybox.parent = this._rootMesh;
  97512. };
  97513. /**
  97514. * Setup the skybox material according to the specified options.
  97515. */
  97516. EnvironmentHelper.prototype._setupSkyboxMaterial = function () {
  97517. if (!this._skybox) {
  97518. return;
  97519. }
  97520. if (!this._skyboxMaterial) {
  97521. this._skyboxMaterial = new BABYLON.BackgroundMaterial("BackgroundSkyboxMaterial", this._scene);
  97522. }
  97523. this._skyboxMaterial.useRGBColor = false;
  97524. this._skyboxMaterial.primaryColor = this._options.skyboxColor;
  97525. this._skyboxMaterial.enableNoise = true;
  97526. this._skybox.material = this._skyboxMaterial;
  97527. };
  97528. /**
  97529. * Setup the skybox reflection texture according to the specified options.
  97530. */
  97531. EnvironmentHelper.prototype._setupSkyboxReflectionTexture = function () {
  97532. if (!this._skyboxMaterial) {
  97533. return;
  97534. }
  97535. if (this._skyboxTexture) {
  97536. return;
  97537. }
  97538. if (this._options.skyboxTexture instanceof BABYLON.BaseTexture) {
  97539. this._skyboxMaterial.reflectionTexture = this._options.skyboxTexture;
  97540. return;
  97541. }
  97542. this._skyboxTexture = new BABYLON.CubeTexture(this._options.skyboxTexture, this._scene, undefined, undefined, undefined, undefined, this._errorHandler);
  97543. this._skyboxTexture.coordinatesMode = BABYLON.Texture.SKYBOX_MODE;
  97544. this._skyboxTexture.gammaSpace = false;
  97545. this._skyboxMaterial.reflectionTexture = this._skyboxTexture;
  97546. };
  97547. /**
  97548. * Dispose all the elements created by the Helper.
  97549. */
  97550. EnvironmentHelper.prototype.dispose = function () {
  97551. if (this._groundMaterial) {
  97552. this._groundMaterial.dispose(true, true);
  97553. }
  97554. if (this._skyboxMaterial) {
  97555. this._skyboxMaterial.dispose(true, true);
  97556. }
  97557. this._rootMesh.dispose(false);
  97558. };
  97559. /**
  97560. * Default ground texture URL.
  97561. */
  97562. EnvironmentHelper._groundTextureCDNUrl = "https://assets.babylonjs.com/environments/backgroundGround.png";
  97563. /**
  97564. * Default skybox texture URL.
  97565. */
  97566. EnvironmentHelper._skyboxTextureCDNUrl = "https://assets.babylonjs.com/environments/backgroundSkybox.dds";
  97567. /**
  97568. * Default environment texture URL.
  97569. */
  97570. EnvironmentHelper._environmentTextureCDNUrl = "https://assets.babylonjs.com/environments/environmentSpecular.dds";
  97571. return EnvironmentHelper;
  97572. }());
  97573. BABYLON.EnvironmentHelper = EnvironmentHelper;
  97574. })(BABYLON || (BABYLON = {}));
  97575. //# sourceMappingURL=babylon.environmentHelper.js.map
  97576. var BABYLON;
  97577. (function (BABYLON) {
  97578. /**
  97579. * Display a 360 degree video on an approximately spherical surface, useful for VR applications or skyboxes.
  97580. * As a subclass of Node, this allow parenting to the camera or multiple videos with different locations in the scene.
  97581. * This class achieves its effect with a VideoTexture and a correctly configured BackgroundMaterial on an inverted sphere.
  97582. * Potential additions to this helper include zoom and and non-infinite distance rendering effects.
  97583. */
  97584. var VideoDome = /** @class */ (function (_super) {
  97585. __extends(VideoDome, _super);
  97586. /**
  97587. * Create an instance of this class and pass through the parameters to the relevant classes, VideoTexture, StandardMaterial, and Mesh.
  97588. * @param name Element's name, child elements will append suffixes for their own names.
  97589. * @param urlsOrVideo
  97590. * @param options An object containing optional or exposed sub element properties:
  97591. * @param options **resolution=12** Integer, lower resolutions have more artifacts at extreme fovs
  97592. * @param options **clickToPlay=false** Add a click to play listener to the video, does not prevent autoplay.
  97593. * @param options **autoPlay=true** Automatically attempt to being playing the video.
  97594. * @param options **loop=true** Automatically loop video on end.
  97595. * @param options **size=1000** Physical radius to create the dome at, defaults to approximately half the far clip plane.
  97596. */
  97597. function VideoDome(name, urlsOrVideo, options, scene) {
  97598. var _this = _super.call(this, name, scene) || this;
  97599. // set defaults and manage values
  97600. name = name || "videoDome";
  97601. options.resolution = (Math.abs(options.resolution) | 0) || 12;
  97602. options.clickToPlay = Boolean(options.clickToPlay);
  97603. options.autoPlay = options.autoPlay === undefined ? true : Boolean(options.autoPlay);
  97604. options.loop = options.loop === undefined ? true : Boolean(options.loop);
  97605. options.size = Math.abs(options.size) || (scene.activeCamera ? scene.activeCamera.maxZ * 0.48 : 1000);
  97606. // create
  97607. var tempOptions = { loop: options.loop, autoPlay: options.autoPlay, autoUpdateTexture: true };
  97608. var material = _this._material = new BABYLON.BackgroundMaterial(name + "_material", scene);
  97609. var texture = _this._videoTexture = new BABYLON.VideoTexture(name + "_texture", urlsOrVideo, scene, false, false, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, tempOptions);
  97610. _this._mesh = BABYLON.MeshBuilder.CreateIcoSphere(name + "_mesh", {
  97611. flat: false,
  97612. radius: options.size,
  97613. subdivisions: options.resolution,
  97614. sideOrientation: BABYLON.Mesh.BACKSIDE // needs to be inside out
  97615. }, scene);
  97616. // configure material
  97617. texture.coordinatesMode = BABYLON.Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE; // matches orientation
  97618. texture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE; // always clamp the up/down
  97619. material.reflectionTexture = _this._videoTexture;
  97620. material.useEquirectangularFOV = true;
  97621. material.fovMultiplier = 1.0;
  97622. // configure mesh
  97623. _this._mesh.material = material;
  97624. _this._mesh.parent = _this;
  97625. // optional configuration
  97626. if (options.clickToPlay) {
  97627. scene.onPointerUp = function () {
  97628. _this._videoTexture.video.play();
  97629. };
  97630. }
  97631. return _this;
  97632. }
  97633. Object.defineProperty(VideoDome.prototype, "fovMultiplier", {
  97634. /**
  97635. * The current fov(field of view) multiplier, 0.0 - 2.0. Defaults to 1.0. Lower values "zoom in" and higher values "zoom out".
  97636. * Also see the options.resolution property.
  97637. */
  97638. get: function () {
  97639. return this._material.fovMultiplier;
  97640. },
  97641. set: function (value) {
  97642. this._material.fovMultiplier = value;
  97643. },
  97644. enumerable: true,
  97645. configurable: true
  97646. });
  97647. /**
  97648. * Releases resources associated with this node.
  97649. * @param doNotRecurse Set to true to not recurse into each children (recurse into each children by default)
  97650. * @param disposeMaterialAndTextures Set to true to also dispose referenced materials and textures (false by default)
  97651. */
  97652. VideoDome.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  97653. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  97654. this._videoTexture.dispose();
  97655. this._mesh.dispose();
  97656. this._material.dispose();
  97657. _super.prototype.dispose.call(this, doNotRecurse, disposeMaterialAndTextures);
  97658. };
  97659. return VideoDome;
  97660. }(BABYLON.Node));
  97661. BABYLON.VideoDome = VideoDome;
  97662. })(BABYLON || (BABYLON = {}));
  97663. //# sourceMappingURL=babylon.videoDome.js.map
  97664. BABYLON.Effect.ShadersStore={"defaultVertexShader":"#include<__decl__defaultVertex>\n\n#define CUSTOM_VERTEX_BEGIN\nattribute vec3 position;\n#ifdef NORMAL\nattribute vec3 normal;\n#endif\n#ifdef TANGENT\nattribute vec4 tangent;\n#endif\n#ifdef UV1\nattribute vec2 uv;\n#endif\n#ifdef UV2\nattribute vec2 uv2;\n#endif\n#ifdef VERTEXCOLOR\nattribute vec4 color;\n#endif\n#include<helperFunctions>\n#include<bonesDeclaration>\n\n#include<instancesDeclaration>\n#ifdef MAINUV1\nvarying vec2 vMainUV1;\n#endif\n#ifdef MAINUV2\nvarying vec2 vMainUV2;\n#endif\n#if defined(DIFFUSE) && DIFFUSEDIRECTUV == 0\nvarying vec2 vDiffuseUV;\n#endif\n#if defined(AMBIENT) && AMBIENTDIRECTUV == 0\nvarying vec2 vAmbientUV;\n#endif\n#if defined(OPACITY) && OPACITYDIRECTUV == 0\nvarying vec2 vOpacityUV;\n#endif\n#if defined(EMISSIVE) && EMISSIVEDIRECTUV == 0\nvarying vec2 vEmissiveUV;\n#endif\n#if defined(LIGHTMAP) && LIGHTMAPDIRECTUV == 0\nvarying vec2 vLightmapUV;\n#endif\n#if defined(SPECULAR) && defined(SPECULARTERM) && SPECULARDIRECTUV == 0\nvarying vec2 vSpecularUV;\n#endif\n#if defined(BUMP) && BUMPDIRECTUV == 0\nvarying vec2 vBumpUV;\n#endif\n\nvarying vec3 vPositionW;\n#ifdef NORMAL\nvarying vec3 vNormalW;\n#endif\n#ifdef VERTEXCOLOR\nvarying vec4 vColor;\n#endif\n#include<bumpVertexDeclaration>\n#include<clipPlaneVertexDeclaration>\n#include<fogVertexDeclaration>\n#include<__decl__lightFragment>[0..maxSimultaneousLights]\n#include<morphTargetsVertexGlobalDeclaration>\n#include<morphTargetsVertexDeclaration>[0..maxSimultaneousMorphTargets]\n#ifdef REFLECTIONMAP_SKYBOX\nvarying vec3 vPositionUVW;\n#endif\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvarying vec3 vDirectionW;\n#endif\n#include<logDepthDeclaration>\n#define CUSTOM_VERTEX_DEFINITIONS\nvoid main(void) {\n#define CUSTOM_VERTEX_MAIN_BEGIN\nvec3 positionUpdated=position;\n#ifdef NORMAL \nvec3 normalUpdated=normal;\n#endif\n#ifdef TANGENT\nvec4 tangentUpdated=tangent;\n#endif\n#include<morphTargetsVertex>[0..maxSimultaneousMorphTargets]\n#ifdef REFLECTIONMAP_SKYBOX\nvPositionUVW=positionUpdated;\n#endif \n#define CUSTOM_VERTEX_UPDATE_POSITION\n#define CUSTOM_VERTEX_UPDATE_NORMAL\n#include<instancesVertex>\n#include<bonesVertex>\ngl_Position=viewProjection*finalWorld*vec4(positionUpdated,1.0);\nvec4 worldPos=finalWorld*vec4(positionUpdated,1.0);\nvPositionW=vec3(worldPos);\n#ifdef NORMAL\nmat3 normalWorld=mat3(finalWorld);\n#ifdef NONUNIFORMSCALING\nnormalWorld=transposeMat3(inverseMat3(normalWorld));\n#endif\nvNormalW=normalize(normalWorld*normalUpdated);\n#endif\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvDirectionW=normalize(vec3(finalWorld*vec4(positionUpdated,0.0)));\n#endif\n\n#ifndef UV1\nvec2 uv=vec2(0.,0.);\n#endif\n#ifndef UV2\nvec2 uv2=vec2(0.,0.);\n#endif\n#ifdef MAINUV1\nvMainUV1=uv;\n#endif\n#ifdef MAINUV2\nvMainUV2=uv2;\n#endif\n#if defined(DIFFUSE) && DIFFUSEDIRECTUV == 0\nif (vDiffuseInfos.x == 0.)\n{\nvDiffuseUV=vec2(diffuseMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvDiffuseUV=vec2(diffuseMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(AMBIENT) && AMBIENTDIRECTUV == 0\nif (vAmbientInfos.x == 0.)\n{\nvAmbientUV=vec2(ambientMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvAmbientUV=vec2(ambientMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(OPACITY) && OPACITYDIRECTUV == 0\nif (vOpacityInfos.x == 0.)\n{\nvOpacityUV=vec2(opacityMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvOpacityUV=vec2(opacityMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(EMISSIVE) && EMISSIVEDIRECTUV == 0\nif (vEmissiveInfos.x == 0.)\n{\nvEmissiveUV=vec2(emissiveMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvEmissiveUV=vec2(emissiveMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(LIGHTMAP) && LIGHTMAPDIRECTUV == 0\nif (vLightmapInfos.x == 0.)\n{\nvLightmapUV=vec2(lightmapMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvLightmapUV=vec2(lightmapMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(SPECULAR) && defined(SPECULARTERM) && SPECULARDIRECTUV == 0\nif (vSpecularInfos.x == 0.)\n{\nvSpecularUV=vec2(specularMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvSpecularUV=vec2(specularMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(BUMP) && BUMPDIRECTUV == 0\nif (vBumpInfos.x == 0.)\n{\nvBumpUV=vec2(bumpMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvBumpUV=vec2(bumpMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#include<bumpVertex>\n#include<clipPlaneVertex>\n#include<fogVertex>\n#include<shadowsVertex>[0..maxSimultaneousLights]\n#ifdef VERTEXCOLOR\n\nvColor=color;\n#endif\n#include<pointCloudVertex>\n#include<logDepthVertex>\n#define CUSTOM_VERTEX_MAIN_END\n}\n","defaultPixelShader":"#include<__decl__defaultFragment>\n#if defined(BUMP) || !defined(NORMAL)\n#extension GL_OES_standard_derivatives : enable\n#endif\n#define CUSTOM_FRAGMENT_BEGIN\n#ifdef LOGARITHMICDEPTH\n#extension GL_EXT_frag_depth : enable\n#endif\n\n#define RECIPROCAL_PI2 0.15915494\nuniform vec3 vEyePosition;\nuniform vec3 vAmbientColor;\n\nvarying vec3 vPositionW;\n#ifdef NORMAL\nvarying vec3 vNormalW;\n#endif\n#ifdef VERTEXCOLOR\nvarying vec4 vColor;\n#endif\n#ifdef MAINUV1\nvarying vec2 vMainUV1;\n#endif\n#ifdef MAINUV2\nvarying vec2 vMainUV2;\n#endif\n\n#include<helperFunctions>\n\n#include<__decl__lightFragment>[0..maxSimultaneousLights]\n#include<lightsFragmentFunctions>\n#include<shadowsFragmentFunctions>\n\n#ifdef DIFFUSE\n#if DIFFUSEDIRECTUV == 1\n#define vDiffuseUV vMainUV1\n#elif DIFFUSEDIRECTUV == 2\n#define vDiffuseUV vMainUV2\n#else\nvarying vec2 vDiffuseUV;\n#endif\nuniform sampler2D diffuseSampler;\n#endif\n#ifdef AMBIENT\n#if AMBIENTDIRECTUV == 1\n#define vAmbientUV vMainUV1\n#elif AMBIENTDIRECTUV == 2\n#define vAmbientUV vMainUV2\n#else\nvarying vec2 vAmbientUV;\n#endif\nuniform sampler2D ambientSampler;\n#endif\n#ifdef OPACITY \n#if OPACITYDIRECTUV == 1\n#define vOpacityUV vMainUV1\n#elif OPACITYDIRECTUV == 2\n#define vOpacityUV vMainUV2\n#else\nvarying vec2 vOpacityUV;\n#endif\nuniform sampler2D opacitySampler;\n#endif\n#ifdef EMISSIVE\n#if EMISSIVEDIRECTUV == 1\n#define vEmissiveUV vMainUV1\n#elif EMISSIVEDIRECTUV == 2\n#define vEmissiveUV vMainUV2\n#else\nvarying vec2 vEmissiveUV;\n#endif\nuniform sampler2D emissiveSampler;\n#endif\n#ifdef LIGHTMAP\n#if LIGHTMAPDIRECTUV == 1\n#define vLightmapUV vMainUV1\n#elif LIGHTMAPDIRECTUV == 2\n#define vLightmapUV vMainUV2\n#else\nvarying vec2 vLightmapUV;\n#endif\nuniform sampler2D lightmapSampler;\n#endif\n#ifdef REFRACTION\n#ifdef REFRACTIONMAP_3D\nuniform samplerCube refractionCubeSampler;\n#else\nuniform sampler2D refraction2DSampler;\n#endif\n#endif\n#if defined(SPECULAR) && defined(SPECULARTERM)\n#if SPECULARDIRECTUV == 1\n#define vSpecularUV vMainUV1\n#elif SPECULARDIRECTUV == 2\n#define vSpecularUV vMainUV2\n#else\nvarying vec2 vSpecularUV;\n#endif\nuniform sampler2D specularSampler;\n#endif\n#ifdef ALPHATEST\nuniform float alphaCutOff;\n#endif\n\n#include<fresnelFunction>\n\n#ifdef REFLECTION\n#ifdef REFLECTIONMAP_3D\nuniform samplerCube reflectionCubeSampler;\n#else\nuniform sampler2D reflection2DSampler;\n#endif\n#ifdef REFLECTIONMAP_SKYBOX\nvarying vec3 vPositionUVW;\n#else\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvarying vec3 vDirectionW;\n#endif\n#endif\n#include<reflectionFunction>\n#endif\n#include<imageProcessingDeclaration>\n#include<imageProcessingFunctions>\n#include<bumpFragmentFunctions>\n#include<clipPlaneFragmentDeclaration>\n#include<logDepthDeclaration>\n#include<fogFragmentDeclaration>\n#define CUSTOM_FRAGMENT_DEFINITIONS\nvoid main(void) {\n#define CUSTOM_FRAGMENT_MAIN_BEGIN\n#include<clipPlaneFragment>\nvec3 viewDirectionW=normalize(vEyePosition-vPositionW);\n\nvec4 baseColor=vec4(1.,1.,1.,1.);\nvec3 diffuseColor=vDiffuseColor.rgb;\n\nfloat alpha=vDiffuseColor.a;\n\n#ifdef NORMAL\nvec3 normalW=normalize(vNormalW);\n#else\nvec3 normalW=normalize(-cross(dFdx(vPositionW),dFdy(vPositionW)));\n#endif\n#include<bumpFragment>\n#ifdef TWOSIDEDLIGHTING\nnormalW=gl_FrontFacing ? normalW : -normalW;\n#endif\n#ifdef DIFFUSE\nbaseColor=texture2D(diffuseSampler,vDiffuseUV+uvOffset);\n#ifdef ALPHATEST\nif (baseColor.a<alphaCutOff)\ndiscard;\n#endif\n#ifdef ALPHAFROMDIFFUSE\nalpha*=baseColor.a;\n#endif\n#define CUSTOM_FRAGMENT_UPDATE_ALPHA\nbaseColor.rgb*=vDiffuseInfos.y;\n#endif\n#include<depthPrePass>\n#ifdef VERTEXCOLOR\nbaseColor.rgb*=vColor.rgb;\n#endif\n#define CUSTOM_FRAGMENT_UPDATE_DIFFUSE\n\nvec3 baseAmbientColor=vec3(1.,1.,1.);\n#ifdef AMBIENT\nbaseAmbientColor=texture2D(ambientSampler,vAmbientUV+uvOffset).rgb*vAmbientInfos.y;\n#endif\n#define CUSTOM_FRAGMENT_BEFORE_LIGHTS\n\n#ifdef SPECULARTERM\nfloat glossiness=vSpecularColor.a;\nvec3 specularColor=vSpecularColor.rgb;\n#ifdef SPECULAR\nvec4 specularMapColor=texture2D(specularSampler,vSpecularUV+uvOffset);\nspecularColor=specularMapColor.rgb;\n#ifdef GLOSSINESS\nglossiness=glossiness*specularMapColor.a;\n#endif\n#endif\n#else\nfloat glossiness=0.;\n#endif\n\nvec3 diffuseBase=vec3(0.,0.,0.);\nlightingInfo info;\n#ifdef SPECULARTERM\nvec3 specularBase=vec3(0.,0.,0.);\n#endif\nfloat shadow=1.;\n#ifdef LIGHTMAP\nvec3 lightmapColor=texture2D(lightmapSampler,vLightmapUV+uvOffset).rgb*vLightmapInfos.y;\n#endif\n#include<lightFragment>[0..maxSimultaneousLights]\n\nvec3 refractionColor=vec3(0.,0.,0.);\n#ifdef REFRACTION\nvec3 refractionVector=normalize(refract(-viewDirectionW,normalW,vRefractionInfos.y));\n#ifdef REFRACTIONMAP_3D\nrefractionVector.y=refractionVector.y*vRefractionInfos.w;\nif (dot(refractionVector,viewDirectionW)<1.0) {\nrefractionColor=textureCube(refractionCubeSampler,refractionVector).rgb;\n}\n#else\nvec3 vRefractionUVW=vec3(refractionMatrix*(view*vec4(vPositionW+refractionVector*vRefractionInfos.z,1.0)));\nvec2 refractionCoords=vRefractionUVW.xy/vRefractionUVW.z;\nrefractionCoords.y=1.0-refractionCoords.y;\nrefractionColor=texture2D(refraction2DSampler,refractionCoords).rgb;\n#endif\n#ifdef IS_REFRACTION_LINEAR\nrefractionColor=toGammaSpace(refractionColor);\n#endif\nrefractionColor*=vRefractionInfos.x;\n#endif\n\nvec3 reflectionColor=vec3(0.,0.,0.);\n#ifdef REFLECTION\nvec3 vReflectionUVW=computeReflectionCoords(vec4(vPositionW,1.0),normalW);\n#ifdef REFLECTIONMAP_3D\n#ifdef ROUGHNESS\nfloat bias=vReflectionInfos.y;\n#ifdef SPECULARTERM\n#ifdef SPECULAR\n#ifdef GLOSSINESS\nbias*=(1.0-specularMapColor.a);\n#endif\n#endif\n#endif\nreflectionColor=textureCube(reflectionCubeSampler,vReflectionUVW,bias).rgb;\n#else\nreflectionColor=textureCube(reflectionCubeSampler,vReflectionUVW).rgb;\n#endif\n#else\nvec2 coords=vReflectionUVW.xy;\n#ifdef REFLECTIONMAP_PROJECTION\ncoords/=vReflectionUVW.z;\n#endif\ncoords.y=1.0-coords.y;\nreflectionColor=texture2D(reflection2DSampler,coords).rgb;\n#endif\n#ifdef IS_REFLECTION_LINEAR\nreflectionColor=toGammaSpace(reflectionColor);\n#endif\nreflectionColor*=vReflectionInfos.x;\n#ifdef REFLECTIONFRESNEL\nfloat reflectionFresnelTerm=computeFresnelTerm(viewDirectionW,normalW,reflectionRightColor.a,reflectionLeftColor.a);\n#ifdef REFLECTIONFRESNELFROMSPECULAR\n#ifdef SPECULARTERM\nreflectionColor*=specularColor.rgb*(1.0-reflectionFresnelTerm)+reflectionFresnelTerm*reflectionRightColor.rgb;\n#else\nreflectionColor*=reflectionLeftColor.rgb*(1.0-reflectionFresnelTerm)+reflectionFresnelTerm*reflectionRightColor.rgb;\n#endif\n#else\nreflectionColor*=reflectionLeftColor.rgb*(1.0-reflectionFresnelTerm)+reflectionFresnelTerm*reflectionRightColor.rgb;\n#endif\n#endif\n#endif\n#ifdef REFRACTIONFRESNEL\nfloat refractionFresnelTerm=computeFresnelTerm(viewDirectionW,normalW,refractionRightColor.a,refractionLeftColor.a);\nrefractionColor*=refractionLeftColor.rgb*(1.0-refractionFresnelTerm)+refractionFresnelTerm*refractionRightColor.rgb;\n#endif\n#ifdef OPACITY\nvec4 opacityMap=texture2D(opacitySampler,vOpacityUV+uvOffset);\n#ifdef OPACITYRGB\nopacityMap.rgb=opacityMap.rgb*vec3(0.3,0.59,0.11);\nalpha*=(opacityMap.x+opacityMap.y+opacityMap.z)* vOpacityInfos.y;\n#else\nalpha*=opacityMap.a*vOpacityInfos.y;\n#endif\n#endif\n#ifdef VERTEXALPHA\nalpha*=vColor.a;\n#endif\n#ifdef OPACITYFRESNEL\nfloat opacityFresnelTerm=computeFresnelTerm(viewDirectionW,normalW,opacityParts.z,opacityParts.w);\nalpha+=opacityParts.x*(1.0-opacityFresnelTerm)+opacityFresnelTerm*opacityParts.y;\n#endif\n\nvec3 emissiveColor=vEmissiveColor;\n#ifdef EMISSIVE\nemissiveColor+=texture2D(emissiveSampler,vEmissiveUV+uvOffset).rgb*vEmissiveInfos.y;\n#endif\n#ifdef EMISSIVEFRESNEL\nfloat emissiveFresnelTerm=computeFresnelTerm(viewDirectionW,normalW,emissiveRightColor.a,emissiveLeftColor.a);\nemissiveColor*=emissiveLeftColor.rgb*(1.0-emissiveFresnelTerm)+emissiveFresnelTerm*emissiveRightColor.rgb;\n#endif\n\n#ifdef DIFFUSEFRESNEL\nfloat diffuseFresnelTerm=computeFresnelTerm(viewDirectionW,normalW,diffuseRightColor.a,diffuseLeftColor.a);\ndiffuseBase*=diffuseLeftColor.rgb*(1.0-diffuseFresnelTerm)+diffuseFresnelTerm*diffuseRightColor.rgb;\n#endif\n\n#ifdef EMISSIVEASILLUMINATION\nvec3 finalDiffuse=clamp(diffuseBase*diffuseColor+vAmbientColor,0.0,1.0)*baseColor.rgb;\n#else\n#ifdef LINKEMISSIVEWITHDIFFUSE\nvec3 finalDiffuse=clamp((diffuseBase+emissiveColor)*diffuseColor+vAmbientColor,0.0,1.0)*baseColor.rgb;\n#else\nvec3 finalDiffuse=clamp(diffuseBase*diffuseColor+emissiveColor+vAmbientColor,0.0,1.0)*baseColor.rgb;\n#endif\n#endif\n#ifdef SPECULARTERM\nvec3 finalSpecular=specularBase*specularColor;\n#ifdef SPECULAROVERALPHA\nalpha=clamp(alpha+dot(finalSpecular,vec3(0.3,0.59,0.11)),0.,1.);\n#endif\n#else\nvec3 finalSpecular=vec3(0.0);\n#endif\n#ifdef REFLECTIONOVERALPHA\nalpha=clamp(alpha+dot(reflectionColor,vec3(0.3,0.59,0.11)),0.,1.);\n#endif\n\n#ifdef EMISSIVEASILLUMINATION\nvec4 color=vec4(clamp(finalDiffuse*baseAmbientColor+finalSpecular+reflectionColor+emissiveColor+refractionColor,0.0,1.0),alpha);\n#else\nvec4 color=vec4(finalDiffuse*baseAmbientColor+finalSpecular+reflectionColor+refractionColor,alpha);\n#endif\n\n#ifdef LIGHTMAP\n#ifndef LIGHTMAPEXCLUDED\n#ifdef USELIGHTMAPASSHADOWMAP\ncolor.rgb*=lightmapColor;\n#else\ncolor.rgb+=lightmapColor;\n#endif\n#endif\n#endif\n#define CUSTOM_FRAGMENT_BEFORE_FOG\ncolor.rgb=max(color.rgb,0.);\n#include<logDepthFragment>\n#include<fogFragment>\n\n\n#ifdef IMAGEPROCESSINGPOSTPROCESS\ncolor.rgb=toLinearSpace(color.rgb);\n#else\n#ifdef IMAGEPROCESSING\ncolor.rgb=toLinearSpace(color.rgb);\ncolor=applyImageProcessing(color);\n#endif\n#endif\n#ifdef PREMULTIPLYALPHA\n\ncolor.rgb*=color.a;\n#endif\n#define CUSTOM_FRAGMENT_BEFORE_FRAGCOLOR\ngl_FragColor=color;\n}\n","pbrVertexShader":"precision highp float;\n#include<__decl__pbrVertex>\n\nattribute vec3 position;\n#ifdef NORMAL\nattribute vec3 normal;\n#endif\n#ifdef TANGENT\nattribute vec4 tangent;\n#endif\n#ifdef UV1\nattribute vec2 uv;\n#endif\n#ifdef UV2\nattribute vec2 uv2;\n#endif\n#ifdef MAINUV1\nvarying vec2 vMainUV1;\n#endif\n#ifdef MAINUV2\nvarying vec2 vMainUV2; \n#endif \n#ifdef VERTEXCOLOR\nattribute vec4 color;\n#endif\n#include<helperFunctions>\n#include<bonesDeclaration>\n\n#include<instancesDeclaration>\n#if defined(ALBEDO) && ALBEDODIRECTUV == 0\nvarying vec2 vAlbedoUV;\n#endif\n#if defined(AMBIENT) && AMBIENTDIRECTUV == 0\nvarying vec2 vAmbientUV;\n#endif\n#if defined(OPACITY) && OPACITYDIRECTUV == 0\nvarying vec2 vOpacityUV;\n#endif\n#if defined(EMISSIVE) && EMISSIVEDIRECTUV == 0\nvarying vec2 vEmissiveUV;\n#endif\n#if defined(LIGHTMAP) && LIGHTMAPDIRECTUV == 0\nvarying vec2 vLightmapUV;\n#endif\n#if defined(REFLECTIVITY) && REFLECTIVITYDIRECTUV == 0\nvarying vec2 vReflectivityUV;\n#endif\n#if defined(MICROSURFACEMAP) && MICROSURFACEMAPDIRECTUV == 0\nvarying vec2 vMicroSurfaceSamplerUV;\n#endif\n#if defined(BUMP) && BUMPDIRECTUV == 0\nvarying vec2 vBumpUV;\n#endif\n\nvarying vec3 vPositionW;\n#ifdef NORMAL\nvarying vec3 vNormalW;\n#if defined(USESPHERICALFROMREFLECTIONMAP) && defined(USESPHERICALINVERTEX)\nvarying vec3 vEnvironmentIrradiance;\n#include<harmonicsFunctions>\n#endif\n#endif\n#ifdef VERTEXCOLOR\nvarying vec4 vColor;\n#endif\n#include<bumpVertexDeclaration>\n#include<clipPlaneVertexDeclaration>\n#include<fogVertexDeclaration>\n#include<__decl__lightFragment>[0..maxSimultaneousLights]\n#include<morphTargetsVertexGlobalDeclaration>\n#include<morphTargetsVertexDeclaration>[0..maxSimultaneousMorphTargets]\n#ifdef REFLECTIONMAP_SKYBOX\nvarying vec3 vPositionUVW;\n#endif\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvarying vec3 vDirectionW;\n#endif\n#include<logDepthDeclaration>\nvoid main(void) {\nvec3 positionUpdated=position;\n#ifdef NORMAL\nvec3 normalUpdated=normal;\n#endif\n#ifdef TANGENT\nvec4 tangentUpdated=tangent;\n#endif\n#include<morphTargetsVertex>[0..maxSimultaneousMorphTargets]\n#ifdef REFLECTIONMAP_SKYBOX\nvPositionUVW=positionUpdated;\n#endif \n#include<instancesVertex>\n#include<bonesVertex>\ngl_Position=viewProjection*finalWorld*vec4(positionUpdated,1.0);\nvec4 worldPos=finalWorld*vec4(positionUpdated,1.0);\nvPositionW=vec3(worldPos);\n#ifdef NORMAL\nmat3 normalWorld=mat3(finalWorld);\n#ifdef NONUNIFORMSCALING\nnormalWorld=transposeMat3(inverseMat3(normalWorld));\n#endif\nvNormalW=normalize(normalWorld*normalUpdated);\n#if defined(USESPHERICALFROMREFLECTIONMAP) && defined(USESPHERICALINVERTEX)\nvec3 reflectionVector=vec3(reflectionMatrix*vec4(vNormalW,0)).xyz;\n#ifdef REFLECTIONMAP_OPPOSITEZ\nreflectionVector.z*=-1.0;\n#endif\nvEnvironmentIrradiance=environmentIrradianceJones(reflectionVector);\n#endif\n#endif\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvDirectionW=normalize(vec3(finalWorld*vec4(positionUpdated,0.0)));\n#endif\n\n#ifndef UV1\nvec2 uv=vec2(0.,0.);\n#endif\n#ifndef UV2\nvec2 uv2=vec2(0.,0.);\n#endif\n#ifdef MAINUV1\nvMainUV1=uv;\n#endif \n#ifdef MAINUV2\nvMainUV2=uv2;\n#endif \n#if defined(ALBEDO) && ALBEDODIRECTUV == 0 \nif (vAlbedoInfos.x == 0.)\n{\nvAlbedoUV=vec2(albedoMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvAlbedoUV=vec2(albedoMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(AMBIENT) && AMBIENTDIRECTUV == 0 \nif (vAmbientInfos.x == 0.)\n{\nvAmbientUV=vec2(ambientMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvAmbientUV=vec2(ambientMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(OPACITY) && OPACITYDIRECTUV == 0 \nif (vOpacityInfos.x == 0.)\n{\nvOpacityUV=vec2(opacityMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvOpacityUV=vec2(opacityMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(EMISSIVE) && EMISSIVEDIRECTUV == 0 \nif (vEmissiveInfos.x == 0.)\n{\nvEmissiveUV=vec2(emissiveMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvEmissiveUV=vec2(emissiveMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(LIGHTMAP) && LIGHTMAPDIRECTUV == 0 \nif (vLightmapInfos.x == 0.)\n{\nvLightmapUV=vec2(lightmapMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvLightmapUV=vec2(lightmapMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(REFLECTIVITY) && REFLECTIVITYDIRECTUV == 0 \nif (vReflectivityInfos.x == 0.)\n{\nvReflectivityUV=vec2(reflectivityMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvReflectivityUV=vec2(reflectivityMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(MICROSURFACEMAP) && MICROSURFACEMAPDIRECTUV == 0 \nif (vMicroSurfaceSamplerInfos.x == 0.)\n{\nvMicroSurfaceSamplerUV=vec2(microSurfaceSamplerMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvMicroSurfaceSamplerUV=vec2(microSurfaceSamplerMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(BUMP) && BUMPDIRECTUV == 0 \nif (vBumpInfos.x == 0.)\n{\nvBumpUV=vec2(bumpMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvBumpUV=vec2(bumpMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n\n#include<bumpVertex>\n\n#include<clipPlaneVertex>\n\n#include<fogVertex>\n\n#include<shadowsVertex>[0..maxSimultaneousLights]\n\n#ifdef VERTEXCOLOR\nvColor=color;\n#endif\n\n#ifdef POINTSIZE\ngl_PointSize=pointSize;\n#endif\n\n#include<logDepthVertex>\n}","pbrPixelShader":"#if defined(BUMP) || !defined(NORMAL) || defined(FORCENORMALFORWARD) || defined(SPECULARAA)\n#extension GL_OES_standard_derivatives : enable\n#endif\n#ifdef LODBASEDMICROSFURACE\n#extension GL_EXT_shader_texture_lod : enable\n#endif\n#ifdef LOGARITHMICDEPTH\n#extension GL_EXT_frag_depth : enable\n#endif\nprecision highp float;\n#include<__decl__pbrFragment>\nuniform vec4 vEyePosition;\nuniform vec3 vAmbientColor;\nuniform vec4 vCameraInfos;\n\nvarying vec3 vPositionW;\n#ifdef MAINUV1\nvarying vec2 vMainUV1;\n#endif \n#ifdef MAINUV2 \nvarying vec2 vMainUV2;\n#endif \n#ifdef NORMAL\nvarying vec3 vNormalW;\n#if defined(USESPHERICALFROMREFLECTIONMAP) && defined(USESPHERICALINVERTEX)\nvarying vec3 vEnvironmentIrradiance;\n#endif\n#endif\n#ifdef VERTEXCOLOR\nvarying vec4 vColor;\n#endif\n\n#include<__decl__lightFragment>[0..maxSimultaneousLights]\n\n#ifdef ALBEDO\n#if ALBEDODIRECTUV == 1\n#define vAlbedoUV vMainUV1\n#elif ALBEDODIRECTUV == 2\n#define vAlbedoUV vMainUV2\n#else\nvarying vec2 vAlbedoUV;\n#endif\nuniform sampler2D albedoSampler;\n#endif\n#ifdef AMBIENT\n#if AMBIENTDIRECTUV == 1\n#define vAmbientUV vMainUV1\n#elif AMBIENTDIRECTUV == 2\n#define vAmbientUV vMainUV2\n#else\nvarying vec2 vAmbientUV;\n#endif\nuniform sampler2D ambientSampler;\n#endif\n#ifdef OPACITY\n#if OPACITYDIRECTUV == 1\n#define vOpacityUV vMainUV1\n#elif OPACITYDIRECTUV == 2\n#define vOpacityUV vMainUV2\n#else\nvarying vec2 vOpacityUV;\n#endif\nuniform sampler2D opacitySampler;\n#endif\n#ifdef EMISSIVE\n#if EMISSIVEDIRECTUV == 1\n#define vEmissiveUV vMainUV1\n#elif EMISSIVEDIRECTUV == 2\n#define vEmissiveUV vMainUV2\n#else\nvarying vec2 vEmissiveUV;\n#endif\nuniform sampler2D emissiveSampler;\n#endif\n#ifdef LIGHTMAP\n#if LIGHTMAPDIRECTUV == 1\n#define vLightmapUV vMainUV1\n#elif LIGHTMAPDIRECTUV == 2\n#define vLightmapUV vMainUV2\n#else\nvarying vec2 vLightmapUV;\n#endif\nuniform sampler2D lightmapSampler;\n#endif\n#ifdef REFLECTIVITY\n#if REFLECTIVITYDIRECTUV == 1\n#define vReflectivityUV vMainUV1\n#elif REFLECTIVITYDIRECTUV == 2\n#define vReflectivityUV vMainUV2\n#else\nvarying vec2 vReflectivityUV;\n#endif\nuniform sampler2D reflectivitySampler;\n#endif\n#ifdef MICROSURFACEMAP\n#if MICROSURFACEMAPDIRECTUV == 1\n#define vMicroSurfaceSamplerUV vMainUV1\n#elif MICROSURFACEMAPDIRECTUV == 2\n#define vMicroSurfaceSamplerUV vMainUV2\n#else\nvarying vec2 vMicroSurfaceSamplerUV;\n#endif\nuniform sampler2D microSurfaceSampler;\n#endif\n\n#ifdef REFRACTION\n#ifdef REFRACTIONMAP_3D\n#define sampleRefraction(s,c) textureCube(s,c)\nuniform samplerCube refractionSampler;\n#ifdef LODBASEDMICROSFURACE\n#define sampleRefractionLod(s,c,l) textureCubeLodEXT(s,c,l)\n#else\nuniform samplerCube refractionSamplerLow;\nuniform samplerCube refractionSamplerHigh;\n#endif\n#else\n#define sampleRefraction(s,c) texture2D(s,c)\nuniform sampler2D refractionSampler;\n#ifdef LODBASEDMICROSFURACE\n#define sampleRefractionLod(s,c,l) texture2DLodEXT(s,c,l)\n#else\nuniform samplerCube refractionSamplerLow;\nuniform samplerCube refractionSamplerHigh;\n#endif\n#endif\n#endif\n\n#ifdef REFLECTION\n#ifdef REFLECTIONMAP_3D\n#define sampleReflection(s,c) textureCube(s,c)\nuniform samplerCube reflectionSampler;\n#ifdef LODBASEDMICROSFURACE\n#define sampleReflectionLod(s,c,l) textureCubeLodEXT(s,c,l)\n#else\nuniform samplerCube reflectionSamplerLow;\nuniform samplerCube reflectionSamplerHigh;\n#endif\n#else\n#define sampleReflection(s,c) texture2D(s,c)\nuniform sampler2D reflectionSampler;\n#ifdef LODBASEDMICROSFURACE\n#define sampleReflectionLod(s,c,l) texture2DLodEXT(s,c,l)\n#else\nuniform samplerCube reflectionSamplerLow;\nuniform samplerCube reflectionSamplerHigh;\n#endif\n#endif\n#ifdef REFLECTIONMAP_SKYBOX\nvarying vec3 vPositionUVW;\n#else\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvarying vec3 vDirectionW;\n#endif\n#endif\n#include<reflectionFunction>\n#endif\n#ifdef ENVIRONMENTBRDF\nuniform sampler2D environmentBrdfSampler;\n#endif\n\n#ifndef FROMLINEARSPACE\n#define FROMLINEARSPACE;\n#endif\n#include<imageProcessingDeclaration>\n#include<helperFunctions>\n#include<imageProcessingFunctions>\n\n#include<shadowsFragmentFunctions>\n#include<pbrFunctions>\n#include<harmonicsFunctions>\n#include<pbrLightFunctions>\n#include<bumpFragmentFunctions>\n#include<clipPlaneFragmentDeclaration>\n#include<logDepthDeclaration>\n\n#include<fogFragmentDeclaration>\nvoid main(void) {\n#include<clipPlaneFragment>\n\n\nvec3 viewDirectionW=normalize(vEyePosition.xyz-vPositionW);\n#ifdef NORMAL\nvec3 normalW=normalize(vNormalW);\n#else\nvec3 normalW=normalize(cross(dFdx(vPositionW),dFdy(vPositionW)))*vEyePosition.w;\n#endif\n#include<bumpFragment>\n#ifdef SPECULARAA\nvec3 nDfdx=dFdx(normalW.xyz);\nvec3 nDfdy=dFdy(normalW.xyz);\nfloat slopeSquare=max(dot(nDfdx,nDfdx),dot(nDfdy,nDfdy));\n\nfloat geometricRoughnessFactor=pow(clamp(slopeSquare ,0.,1.),0.333);\n\nfloat geometricAlphaGFactor=sqrt(slopeSquare);\n#else\nfloat geometricRoughnessFactor=0.;\n#endif\n#if defined(FORCENORMALFORWARD) && defined(NORMAL)\nvec3 faceNormal=normalize(cross(dFdx(vPositionW),dFdy(vPositionW)))*vEyePosition.w;\n#if defined(TWOSIDEDLIGHTING)\nfaceNormal=gl_FrontFacing ? faceNormal : -faceNormal;\n#endif\nnormalW*=sign(dot(normalW,faceNormal));\n#endif\n#if defined(TWOSIDEDLIGHTING) && defined(NORMAL)\nnormalW=gl_FrontFacing ? normalW : -normalW;\n#endif\n\n\nvec3 surfaceAlbedo=vAlbedoColor.rgb;\n\nfloat alpha=vAlbedoColor.a;\n#ifdef ALBEDO\nvec4 albedoTexture=texture2D(albedoSampler,vAlbedoUV+uvOffset);\n#if defined(ALPHAFROMALBEDO) || defined(ALPHATEST)\nalpha*=albedoTexture.a;\n#endif\nsurfaceAlbedo*=toLinearSpace(albedoTexture.rgb);\nsurfaceAlbedo*=vAlbedoInfos.y;\n#endif\n\n#ifdef OPACITY\nvec4 opacityMap=texture2D(opacitySampler,vOpacityUV+uvOffset);\n#ifdef OPACITYRGB\nalpha=getLuminance(opacityMap.rgb);\n#else\nalpha*=opacityMap.a;\n#endif\nalpha*=vOpacityInfos.y;\n#endif\n#ifdef VERTEXALPHA\nalpha*=vColor.a;\n#endif\n#if !defined(LINKREFRACTIONTOTRANSPARENCY) && !defined(ALPHAFRESNEL)\n#ifdef ALPHATEST\nif (alpha<ALPHATESTVALUE)\ndiscard;\n#ifndef ALPHABLEND\n\nalpha=1.0;\n#endif\n#endif\n#endif\n#include<depthPrePass>\n#ifdef VERTEXCOLOR\nsurfaceAlbedo*=vColor.rgb;\n#endif\n\nvec3 ambientOcclusionColor=vec3(1.,1.,1.);\n#ifdef AMBIENT\nvec3 ambientOcclusionColorMap=texture2D(ambientSampler,vAmbientUV+uvOffset).rgb*vAmbientInfos.y;\n#ifdef AMBIENTINGRAYSCALE\nambientOcclusionColorMap=vec3(ambientOcclusionColorMap.r,ambientOcclusionColorMap.r,ambientOcclusionColorMap.r);\n#endif\nambientOcclusionColor=mix(ambientOcclusionColor,ambientOcclusionColorMap,vAmbientInfos.z);\n#endif\n#ifdef UNLIT\nvec3 diffuseBase=vec3(1.,1.,1.);\n#else\n\nfloat microSurface=vReflectivityColor.a;\nvec3 surfaceReflectivityColor=vReflectivityColor.rgb;\n#ifdef METALLICWORKFLOW\nvec2 metallicRoughness=surfaceReflectivityColor.rg;\n#ifdef REFLECTIVITY\nvec4 surfaceMetallicColorMap=texture2D(reflectivitySampler,vReflectivityUV+uvOffset);\n#ifdef AOSTOREINMETALMAPRED\nvec3 aoStoreInMetalMap=vec3(surfaceMetallicColorMap.r,surfaceMetallicColorMap.r,surfaceMetallicColorMap.r);\nambientOcclusionColor=mix(ambientOcclusionColor,aoStoreInMetalMap,vReflectivityInfos.z);\n#endif\n#ifdef METALLNESSSTOREINMETALMAPBLUE\nmetallicRoughness.r*=surfaceMetallicColorMap.b;\n#else\nmetallicRoughness.r*=surfaceMetallicColorMap.r;\n#endif\n#ifdef ROUGHNESSSTOREINMETALMAPALPHA\nmetallicRoughness.g*=surfaceMetallicColorMap.a;\n#else\n#ifdef ROUGHNESSSTOREINMETALMAPGREEN\nmetallicRoughness.g*=surfaceMetallicColorMap.g;\n#endif\n#endif\n#endif\n#ifdef MICROSURFACEMAP\nvec4 microSurfaceTexel=texture2D(microSurfaceSampler,vMicroSurfaceSamplerUV+uvOffset)*vMicroSurfaceSamplerInfos.y;\nmetallicRoughness.g*=microSurfaceTexel.r;\n#endif\n\nmicroSurface=1.0-metallicRoughness.g;\n\nvec3 baseColor=surfaceAlbedo;\n\n\nconst vec3 DefaultSpecularReflectanceDielectric=vec3(0.04,0.04,0.04);\n\nsurfaceAlbedo=mix(baseColor.rgb*(1.0-DefaultSpecularReflectanceDielectric.r),vec3(0.,0.,0.),metallicRoughness.r);\n\nsurfaceReflectivityColor=mix(DefaultSpecularReflectanceDielectric,baseColor,metallicRoughness.r);\n#else\n#ifdef REFLECTIVITY\nvec4 surfaceReflectivityColorMap=texture2D(reflectivitySampler,vReflectivityUV+uvOffset);\nsurfaceReflectivityColor*=toLinearSpace(surfaceReflectivityColorMap.rgb);\nsurfaceReflectivityColor*=vReflectivityInfos.y;\n#ifdef MICROSURFACEFROMREFLECTIVITYMAP\nmicroSurface*=surfaceReflectivityColorMap.a;\nmicroSurface*=vReflectivityInfos.z;\n#else\n#ifdef MICROSURFACEAUTOMATIC\nmicroSurface*=computeDefaultMicroSurface(microSurface,surfaceReflectivityColor);\n#endif\n#ifdef MICROSURFACEMAP\nvec4 microSurfaceTexel=texture2D(microSurfaceSampler,vMicroSurfaceSamplerUV+uvOffset)*vMicroSurfaceSamplerInfos.y;\nmicroSurface*=microSurfaceTexel.r;\n#endif\n#endif\n#endif\n#endif\n\nmicroSurface=clamp(microSurface,0.,1.);\n\nfloat roughness=1.-microSurface;\n\n#ifdef ALPHAFRESNEL\n#if defined(ALPHATEST) || defined(ALPHABLEND)\n\n\n\nfloat opacityPerceptual=alpha;\n#ifdef LINEARALPHAFRESNEL\nfloat opacity0=opacityPerceptual;\n#else\nfloat opacity0=opacityPerceptual*opacityPerceptual;\n#endif\nfloat opacity90=fresnelGrazingReflectance(opacity0);\nvec3 normalForward=faceforward(normalW,-viewDirectionW,normalW);\n\nalpha=fresnelSchlickEnvironmentGGX(clamp(dot(viewDirectionW,normalForward),0.0,1.0),vec3(opacity0),vec3(opacity90),sqrt(microSurface)).x;\n#ifdef ALPHATEST\nif (alpha<ALPHATESTVALUE)\ndiscard;\n#ifndef ALPHABLEND\n\nalpha=1.0;\n#endif\n#endif\n#endif\n#endif\n\n\nfloat NdotVUnclamped=dot(normalW,viewDirectionW);\nfloat NdotV=clamp(NdotVUnclamped,0.,1.)+0.00001;\nfloat alphaG=convertRoughnessToAverageSlope(roughness);\n#ifdef SPECULARAA\n\n\nalphaG+=(0.75*geometricAlphaGFactor);\n#endif\n\n#ifdef REFRACTION\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(-viewDirectionW,normalW);\nspecularEnvironmentReflectance*=eho;\n#endif\n#endif\n#endif\n#else\n\nvec3 specularEnvironmentReflectance=fresnelSchlickEnvironmentGGX(NdotV,specularEnvironmentR0,specularEnvironmentR90,sqrt(microSurface));\n#endif\n\n#ifdef REFRACTION\nvec3 refractance=vec3(0.0,0.0,0.0);\nvec3 transmission=vec3(1.0,1.0,1.0);\n#ifdef LINKREFRACTIONTOTRANSPARENCY\n\ntransmission*=(1.0-alpha);\n\n\nvec3 mixedAlbedo=surfaceAlbedo;\nfloat maxChannel=max(max(mixedAlbedo.r,mixedAlbedo.g),mixedAlbedo.b);\nvec3 tint=clamp(maxChannel*mixedAlbedo,0.0,1.0);\n\nsurfaceAlbedo*=alpha;\n\nenvironmentIrradiance*=alpha;\n\nenvironmentRefraction*=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"};
  97665. 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 view,vec3 normal) {\n\nvec3 reflection=reflect(view,normal);\nfloat temp=clamp( 1.0+1.1*dot(reflection,normal),0.0,1.0);\nreturn square(temp);\n}","harmonicsFunctions":"#ifdef USESPHERICALFROMREFLECTIONMAP\nuniform vec3 vSphericalX;\nuniform vec3 vSphericalY;\nuniform vec3 vSphericalZ;\nuniform vec3 vSphericalXX_ZZ;\nuniform vec3 vSphericalYY_ZZ;\nuniform vec3 vSphericalZZ;\nuniform vec3 vSphericalXY;\nuniform vec3 vSphericalYZ;\nuniform vec3 vSphericalZX;\nvec3 quaternionVectorRotation_ScaledSqrtTwo(vec4 Q,vec3 V){\nvec3 T=cross(Q.xyz,V);\nT+=Q.www*V;\nreturn cross(Q.xyz,T)+V;\n}\nvec3 environmentIrradianceJones(vec3 normal)\n{\n\n\n\n\n\n\n\n\n\nfloat Nx=normal.x;\nfloat Ny=normal.y;\nfloat Nz=normal.z;\nvec3 C1=vSphericalZZ.rgb;\nvec3 Cx=vSphericalX.rgb;\nvec3 Cy=vSphericalY.rgb;\nvec3 Cz=vSphericalZ.rgb;\nvec3 Cxx_zz=vSphericalXX_ZZ.rgb;\nvec3 Cyy_zz=vSphericalYY_ZZ.rgb;\nvec3 Cxy=vSphericalXY.rgb;\nvec3 Cyz=vSphericalYZ.rgb;\nvec3 Czx=vSphericalZX.rgb;\nvec3 a1=Cyy_zz*Ny+Cy;\nvec3 a2=Cyz*Nz+a1;\nvec3 b1=Czx*Nz+Cx;\nvec3 b2=Cxy*Ny+b1;\nvec3 b3=Cxx_zz*Nx+b2;\nvec3 t1=Cz*Nz+C1;\nvec3 t2=a2*Ny+t1;\nvec3 t3=b3*Nx+t2;\nreturn t3;\n}\n#endif","pbrLightFunctions":"\nstruct lightingInfo\n{\nvec3 diffuse;\n#ifdef SPECULARTERM\nvec3 specular;\n#endif\n};\nfloat computeDistanceLightFalloff(vec3 lightOffset,float lightDistanceSquared,float range)\n{ \n#ifdef USEPHYSICALLIGHTFALLOFF\nfloat lightDistanceFalloff=1.0/((lightDistanceSquared+0.001));\n#else\nfloat lightDistanceFalloff=max(0.,1.0-length(lightOffset)/range);\n#endif\nreturn lightDistanceFalloff;\n}\nfloat computeDirectionalLightFalloff(vec3 lightDirection,vec3 directionToLightCenterW,float cosHalfAngle,float exponent)\n{\nfloat falloff=0.0;\n#ifdef USEPHYSICALLIGHTFALLOFF\nconst float kMinusLog2ConeAngleIntensityRatio=6.64385618977; \n\n\n\n\n\nfloat concentrationKappa=kMinusLog2ConeAngleIntensityRatio/(1.0-cosHalfAngle);\n\n\nvec4 lightDirectionSpreadSG=vec4(-lightDirection*concentrationKappa,-concentrationKappa);\nfalloff=exp2(dot(vec4(directionToLightCenterW,1.0),lightDirectionSpreadSG));\n#else\nfloat cosAngle=max(0.000000000000001,dot(-lightDirection,directionToLightCenterW));\nif (cosAngle>=cosHalfAngle)\n{\nfalloff=max(0.,pow(cosAngle,exponent));\n}\n#endif\nreturn falloff;\n}\nlightingInfo computeLighting(vec3 viewDirectionW,vec3 vNormal,vec4 lightData,vec3 diffuseColor,vec3 specularColor,float rangeRadius,float roughness,float NdotV,vec3 reflectance0,vec3 reflectance90,float geometricRoughnessFactor,out float NdotL) {\nlightingInfo result;\nvec3 lightDirection;\nfloat attenuation=1.0;\nfloat lightDistance;\n\nif (lightData.w == 0.)\n{\nvec3 lightOffset=lightData.xyz-vPositionW;\nfloat lightDistanceSquared=dot(lightOffset,lightOffset);\nattenuation=computeDistanceLightFalloff(lightOffset,lightDistanceSquared,rangeRadius);\nlightDistance=sqrt(lightDistanceSquared);\nlightDirection=normalize(lightOffset);\n}\n\nelse\n{\nlightDistance=length(-lightData.xyz);\nlightDirection=normalize(-lightData.xyz);\n}\n\nroughness=adjustRoughnessFromLightProperties(roughness,rangeRadius,lightDistance);\n\nvec3 H=normalize(viewDirectionW+lightDirection);\nNdotL=clamp(dot(vNormal,lightDirection),0.00000000001,1.0);\nfloat VdotH=clamp(dot(viewDirectionW,H),0.0,1.0);\nfloat diffuseTerm=computeDiffuseTerm(NdotL,NdotV,VdotH,roughness);\nresult.diffuse=diffuseTerm*diffuseColor*attenuation;\n#ifdef SPECULARTERM\n\nfloat NdotH=clamp(dot(vNormal,H),0.000000000001,1.0);\nvec3 specTerm=computeSpecularTerm(NdotH,NdotL,NdotV,VdotH,roughness,reflectance0,reflectance90,geometricRoughnessFactor);\nresult.specular=specTerm*diffuseColor*attenuation;\n#endif\nreturn result;\n}\nlightingInfo computeSpotLighting(vec3 viewDirectionW,vec3 vNormal,vec4 lightData,vec4 lightDirection,vec3 diffuseColor,vec3 specularColor,float rangeRadius,float roughness,float NdotV,vec3 reflectance0,vec3 reflectance90,float geometricRoughnessFactor,out float NdotL) {\nlightingInfo result;\nvec3 lightOffset=lightData.xyz-vPositionW;\nvec3 directionToLightCenterW=normalize(lightOffset);\n\nfloat lightDistanceSquared=dot(lightOffset,lightOffset);\nfloat attenuation=computeDistanceLightFalloff(lightOffset,lightDistanceSquared,rangeRadius);\n\nfloat directionalAttenuation=computeDirectionalLightFalloff(lightDirection.xyz,directionToLightCenterW,lightDirection.w,lightData.w);\nattenuation*=directionalAttenuation;\n\nfloat lightDistance=sqrt(lightDistanceSquared);\nroughness=adjustRoughnessFromLightProperties(roughness,rangeRadius,lightDistance);\n\nvec3 H=normalize(viewDirectionW+directionToLightCenterW);\nNdotL=clamp(dot(vNormal,directionToLightCenterW),0.000000000001,1.0);\nfloat VdotH=clamp(dot(viewDirectionW,H),0.0,1.0);\nfloat diffuseTerm=computeDiffuseTerm(NdotL,NdotV,VdotH,roughness);\nresult.diffuse=diffuseTerm*diffuseColor*attenuation;\n#ifdef SPECULARTERM\n\nfloat NdotH=clamp(dot(vNormal,H),0.000000000001,1.0);\nvec3 specTerm=computeSpecularTerm(NdotH,NdotL,NdotV,VdotH,roughness,reflectance0,reflectance90,geometricRoughnessFactor);\nresult.specular=specTerm*diffuseColor*attenuation;\n#endif\nreturn result;\n}\nlightingInfo computeHemisphericLighting(vec3 viewDirectionW,vec3 vNormal,vec4 lightData,vec3 diffuseColor,vec3 specularColor,vec3 groundColor,float roughness,float NdotV,vec3 reflectance0,vec3 reflectance90,float geometricRoughnessFactor,out float NdotL) {\nlightingInfo result;\n\n\n\nNdotL=dot(vNormal,lightData.xyz)*0.5+0.5;\nresult.diffuse=mix(groundColor,diffuseColor,NdotL);\n#ifdef SPECULARTERM\n\nvec3 lightVectorW=normalize(lightData.xyz);\nvec3 H=normalize(viewDirectionW+lightVectorW);\nfloat NdotH=clamp(dot(vNormal,H),0.000000000001,1.0);\nNdotL=clamp(NdotL,0.000000000001,1.0);\nfloat VdotH=clamp(dot(viewDirectionW,H),0.0,1.0);\nvec3 specTerm=computeSpecularTerm(NdotH,NdotL,NdotV,VdotH,roughness,reflectance0,reflectance90,geometricRoughnessFactor);\nresult.specular=specTerm*diffuseColor;\n#endif\nreturn result;\n}\nvec3 computeProjectionTextureDiffuseLighting(sampler2D projectionLightSampler,mat4 textureProjectionMatrix){\nvec4 strq=textureProjectionMatrix*vec4(vPositionW,1.0);\nstrq/=strq.w;\nvec3 textureColor=texture2D(projectionLightSampler,strq.xy).rgb;\nreturn toLinearSpace(textureColor);\n}","kernelBlurFragment":"#ifdef DOF\nfactor=sampleCoC(sampleCoord{X}); \ncomputedWeight=KERNEL_WEIGHT{X}*factor;\nsumOfWeights+=computedWeight;\n#else\ncomputedWeight=KERNEL_WEIGHT{X};\n#endif\n#ifdef PACKEDFLOAT\nblend+=unpack(texture2D(textureSampler,sampleCoord{X}))*computedWeight;\n#else\nblend+=texture2D(textureSampler,sampleCoord{X})*computedWeight;\n#endif","kernelBlurFragment2":"#ifdef DOF\nfactor=sampleCoC(sampleCenter+delta*KERNEL_DEP_OFFSET{X});\ncomputedWeight=KERNEL_DEP_WEIGHT{X}*factor;\nsumOfWeights+=computedWeight;\n#else\ncomputedWeight=KERNEL_DEP_WEIGHT{X};\n#endif\n#ifdef PACKEDFLOAT\nblend+=unpack(texture2D(textureSampler,sampleCenter+delta*KERNEL_DEP_OFFSET{X}))*computedWeight;\n#else\nblend+=texture2D(textureSampler,sampleCenter+delta*KERNEL_DEP_OFFSET{X})*computedWeight;\n#endif","kernelBlurVaryingDeclaration":"varying vec2 sampleCoord{X};","kernelBlurVertex":"sampleCoord{X}=sampleCenter+delta*KERNEL_OFFSET{X};","mrtFragmentDeclaration":"#if __VERSION__>=200\nlayout(location=0) out vec4 glFragData[{X}];\n#endif\n","bones300Declaration":"#if NUM_BONE_INFLUENCERS>0\nuniform mat4 mBones[BonesPerMesh];\nin vec4 matricesIndices;\nin vec4 matricesWeights;\n#if NUM_BONE_INFLUENCERS>4\nin vec4 matricesIndicesExtra;\nin vec4 matricesWeightsExtra;\n#endif\n#endif","instances300Declaration":"#ifdef INSTANCES\nin vec4 world0;\nin vec4 world1;\nin vec4 world2;\nin vec4 world3;\n#else\nuniform mat4 world;\n#endif","backgroundVertexDeclaration":"uniform mat4 view;\nuniform mat4 viewProjection;\nuniform float shadowLevel;\n#ifdef DIFFUSE\nuniform mat4 diffuseMatrix;\nuniform vec2 vDiffuseInfos;\n#endif\n#ifdef REFLECTION\nuniform vec2 vReflectionInfos;\nuniform mat4 reflectionMatrix;\nuniform vec3 vReflectionMicrosurfaceInfos;\nuniform float fFovMultiplier;\n#endif\n#ifdef POINTSIZE\nuniform float pointSize;\n#endif","backgroundFragmentDeclaration":" uniform vec4 vPrimaryColor;\n#ifdef USEHIGHLIGHTANDSHADOWCOLORS\nuniform vec4 vPrimaryColorShadow;\n#endif\nuniform float shadowLevel;\nuniform float alpha;\n#ifdef DIFFUSE\nuniform vec2 vDiffuseInfos;\n#endif\n#ifdef REFLECTION\nuniform vec2 vReflectionInfos;\nuniform mat4 reflectionMatrix;\nuniform vec3 vReflectionMicrosurfaceInfos;\n#endif\n#if defined(REFLECTIONFRESNEL) || defined(OPACITYFRESNEL)\nuniform vec3 vBackgroundCenter;\n#endif\n#ifdef REFLECTIONFRESNEL\nuniform vec4 vReflectionControl;\n#endif\n#if defined(REFLECTIONMAP_SPHERICAL) || defined(REFLECTIONMAP_PROJECTION) || defined(REFRACTION)\nuniform mat4 view;\n#endif","backgroundUboDeclaration":"layout(std140,column_major) uniform;\nuniform Material\n{\nuniform vec4 vPrimaryColor;\nuniform vec4 vPrimaryColorShadow;\nuniform vec2 vDiffuseInfos;\nuniform vec2 vReflectionInfos;\nuniform mat4 diffuseMatrix;\nuniform mat4 reflectionMatrix;\nuniform vec3 vReflectionMicrosurfaceInfos;\nuniform float fFovMultiplier;\nuniform float pointSize;\nuniform float shadowLevel;\nuniform float alpha;\n#if defined(REFLECTIONFRESNEL) || defined(OPACITYFRESNEL)\nuniform vec3 vBackgroundCenter;\n#endif\n#ifdef REFLECTIONFRESNEL\nuniform vec4 vReflectionControl;\n#endif\n};\nuniform Scene {\nmat4 viewProjection;\nmat4 view;\n};"};
  97666. var globalObject = (typeof global !== 'undefined') ? global : ((typeof window !== 'undefined') ? window : this);
  97667. globalObject["BABYLON"] = BABYLON;
  97668. //backwards compatibility
  97669. if(typeof earcut !== 'undefined') {
  97670. globalObject["Earcut"] = {
  97671. earcut: earcut
  97672. };
  97673. }
  97674. return BABYLON;
  97675. });
  97676. /* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(19)))
  97677. /***/ }),
  97678. /* 1 */
  97679. /***/ (function(module, exports, __webpack_require__) {
  97680. "use strict";
  97681. Object.defineProperty(exports, "__esModule", { value: true });
  97682. var babylonjs_1 = __webpack_require__(0);
  97683. var helper_1 = __webpack_require__(3);
  97684. /**
  97685. * This is a simple HTML mapper.
  97686. * This mapper parses a single HTML element and returns the configuration from its attributes.
  97687. * it parses numbers and boolean values to the corresponding variable types.
  97688. * The following HTML element:
  97689. * <div test="1" random-flag="true" a.string.object="test"> will result in the following configuration:
  97690. *
  97691. * {
  97692. * test: 1, //a number!
  97693. * randomFlag: boolean, //camelCase and boolean
  97694. * a: {
  97695. * string: {
  97696. * object: "test" //dot-separated object levels
  97697. * }
  97698. * }
  97699. * }
  97700. */
  97701. var HTMLMapper = /** @class */ (function () {
  97702. function HTMLMapper() {
  97703. }
  97704. /**
  97705. * Map a specific element and get configuration from it
  97706. * @param element the HTML element to analyze.
  97707. */
  97708. HTMLMapper.prototype.map = function (element) {
  97709. var config = {};
  97710. var _loop_1 = function (attrIdx) {
  97711. var attr = element.attributes.item(attrIdx);
  97712. if (!attr) {
  97713. return "continue";
  97714. }
  97715. // map "object.property" to the right configuration place.
  97716. var split = attr.nodeName.split('.');
  97717. split.reduce(function (currentConfig, key, idx) {
  97718. //convert html-style to json-style
  97719. var camelKey = helper_1.kebabToCamel(key);
  97720. if (idx === split.length - 1) {
  97721. var val = attr.nodeValue; // firefox warns nodeValue is deprecated, but I found no sign of it anywhere.
  97722. if (val === "true") {
  97723. val = true;
  97724. }
  97725. else if (val === "false") {
  97726. val = false;
  97727. }
  97728. else {
  97729. var isnum = /^\d+$/.test(val);
  97730. if (isnum) {
  97731. var number = parseFloat(val);
  97732. if (!isNaN(number)) {
  97733. val = number;
  97734. }
  97735. }
  97736. }
  97737. currentConfig[camelKey] = val;
  97738. }
  97739. else {
  97740. currentConfig[camelKey] = currentConfig[camelKey] || {};
  97741. }
  97742. return currentConfig[camelKey];
  97743. }, config);
  97744. };
  97745. for (var attrIdx = 0; attrIdx < element.attributes.length; ++attrIdx) {
  97746. _loop_1(attrIdx);
  97747. }
  97748. return config;
  97749. };
  97750. return HTMLMapper;
  97751. }());
  97752. /**
  97753. * A simple string-to-JSON mapper.
  97754. * This is the main mapper, used to analyze downloaded JSON-Configuration or JSON payload
  97755. */
  97756. var JSONMapper = /** @class */ (function () {
  97757. function JSONMapper() {
  97758. }
  97759. JSONMapper.prototype.map = function (rawSource) {
  97760. return JSON.parse(rawSource);
  97761. };
  97762. return JSONMapper;
  97763. }());
  97764. /**
  97765. * The DOM Mapper will traverse an entire DOM Tree and will load the configuration from the
  97766. * DOM elements and attributes.
  97767. */
  97768. var DOMMapper = /** @class */ (function () {
  97769. function DOMMapper() {
  97770. }
  97771. /**
  97772. * The mapping function that will convert HTML data to a viewer configuration object
  97773. * @param baseElement the baseElement from which to start traversing
  97774. * @returns a ViewerCOnfiguration object from the provided HTML Element
  97775. */
  97776. DOMMapper.prototype.map = function (baseElement) {
  97777. var htmlMapper = new HTMLMapper();
  97778. var config = htmlMapper.map(baseElement);
  97779. var traverseChildren = function (element, partConfig) {
  97780. var children = element.children;
  97781. if (children.length) {
  97782. for (var i = 0; i < children.length; ++i) {
  97783. var item = children.item(i);
  97784. // use the HTML Mapper to read configuration from a single element
  97785. var configMapped = htmlMapper.map(item);
  97786. var key = helper_1.kebabToCamel(item.nodeName.toLowerCase());
  97787. if (item.attributes.getNamedItem('array') && item.attributes.getNamedItem('array').nodeValue === 'true') {
  97788. partConfig[key] = [];
  97789. }
  97790. else {
  97791. if (element.attributes.getNamedItem('array') && element.attributes.getNamedItem('array').nodeValue === 'true') {
  97792. partConfig.push(configMapped);
  97793. }
  97794. else if (partConfig[key]) {
  97795. //exists already! probably an array
  97796. element.setAttribute('array', 'true');
  97797. var oldItem = partConfig[key];
  97798. partConfig = [oldItem, configMapped];
  97799. }
  97800. else {
  97801. partConfig[key] = configMapped;
  97802. }
  97803. }
  97804. traverseChildren(item, partConfig[key] || configMapped);
  97805. }
  97806. }
  97807. return partConfig;
  97808. };
  97809. traverseChildren(baseElement, config);
  97810. return config;
  97811. };
  97812. return DOMMapper;
  97813. }());
  97814. /**
  97815. * The MapperManager manages the different implemented mappers.
  97816. * It allows the user to register new mappers as well and use them to parse their own configuration data
  97817. */
  97818. var MapperManager = /** @class */ (function () {
  97819. function MapperManager() {
  97820. this._mappers = {
  97821. "html": new HTMLMapper(),
  97822. "json": new JSONMapper(),
  97823. "dom": new DOMMapper()
  97824. };
  97825. }
  97826. /**
  97827. * Get a specific configuration mapper.
  97828. *
  97829. * @param type the name of the mapper to load
  97830. */
  97831. MapperManager.prototype.getMapper = function (type) {
  97832. if (!this._mappers[type]) {
  97833. babylonjs_1.Tools.Error("No mapper defined for " + type);
  97834. }
  97835. return this._mappers[type] || this._mappers[MapperManager.DefaultMapper];
  97836. };
  97837. /**
  97838. * Use this functio to register your own configuration mapper.
  97839. * After a mapper is registered, it can be used to parse the specific type fo configuration to the standard ViewerConfiguration.
  97840. * @param type the name of the mapper. This will be used to define the configuration type and/or to get the mapper
  97841. * @param mapper The implemented mapper
  97842. */
  97843. MapperManager.prototype.registerMapper = function (type, mapper) {
  97844. this._mappers[type] = mapper;
  97845. };
  97846. /**
  97847. * Dispose the mapper manager and all of its mappers.
  97848. */
  97849. MapperManager.prototype.dispose = function () {
  97850. this._mappers = {};
  97851. };
  97852. /**
  97853. * The default mapper is the JSON mapper.
  97854. */
  97855. MapperManager.DefaultMapper = 'json';
  97856. return MapperManager;
  97857. }());
  97858. exports.MapperManager = MapperManager;
  97859. /**
  97860. * mapperManager is a singleton of the type MapperManager.
  97861. * The mapperManager can be disposed directly with calling mapperManager.dispose()
  97862. * or indirectly with using BabylonViewer.disposeAll()
  97863. */
  97864. exports.mapperManager = new MapperManager();
  97865. /***/ }),
  97866. /* 2 */
  97867. /***/ (function(module, exports, __webpack_require__) {
  97868. (function (global, factory) {
  97869. true ? module.exports = factory() :
  97870. typeof define === 'function' && define.amd ? define(factory) :
  97871. (global.deepmerge = factory());
  97872. }(this, (function () { 'use strict';
  97873. var isMergeableObject = function isMergeableObject(value) {
  97874. return isNonNullObject(value)
  97875. && !isSpecial(value)
  97876. };
  97877. function isNonNullObject(value) {
  97878. return !!value && typeof value === 'object'
  97879. }
  97880. function isSpecial(value) {
  97881. var stringValue = Object.prototype.toString.call(value);
  97882. return stringValue === '[object RegExp]'
  97883. || stringValue === '[object Date]'
  97884. || isReactElement(value)
  97885. }
  97886. // see https://github.com/facebook/react/blob/b5ac963fb791d1298e7f396236383bc955f916c1/src/isomorphic/classic/element/ReactElement.js#L21-L25
  97887. var canUseSymbol = typeof Symbol === 'function' && Symbol.for;
  97888. var REACT_ELEMENT_TYPE = canUseSymbol ? Symbol.for('react.element') : 0xeac7;
  97889. function isReactElement(value) {
  97890. return value.$$typeof === REACT_ELEMENT_TYPE
  97891. }
  97892. function emptyTarget(val) {
  97893. return Array.isArray(val) ? [] : {}
  97894. }
  97895. function cloneUnlessOtherwiseSpecified(value, optionsArgument) {
  97896. var clone = !optionsArgument || optionsArgument.clone !== false;
  97897. return (clone && isMergeableObject(value))
  97898. ? deepmerge(emptyTarget(value), value, optionsArgument)
  97899. : value
  97900. }
  97901. function defaultArrayMerge(target, source, optionsArgument) {
  97902. return target.concat(source).map(function(element) {
  97903. return cloneUnlessOtherwiseSpecified(element, optionsArgument)
  97904. })
  97905. }
  97906. function mergeObject(target, source, optionsArgument) {
  97907. var destination = {};
  97908. if (isMergeableObject(target)) {
  97909. Object.keys(target).forEach(function(key) {
  97910. destination[key] = cloneUnlessOtherwiseSpecified(target[key], optionsArgument);
  97911. });
  97912. }
  97913. Object.keys(source).forEach(function(key) {
  97914. if (!isMergeableObject(source[key]) || !target[key]) {
  97915. destination[key] = cloneUnlessOtherwiseSpecified(source[key], optionsArgument);
  97916. } else {
  97917. destination[key] = deepmerge(target[key], source[key], optionsArgument);
  97918. }
  97919. });
  97920. return destination
  97921. }
  97922. function deepmerge(target, source, optionsArgument) {
  97923. var sourceIsArray = Array.isArray(source);
  97924. var targetIsArray = Array.isArray(target);
  97925. var options = optionsArgument || { arrayMerge: defaultArrayMerge };
  97926. var sourceAndTargetTypesMatch = sourceIsArray === targetIsArray;
  97927. if (!sourceAndTargetTypesMatch) {
  97928. return cloneUnlessOtherwiseSpecified(source, optionsArgument)
  97929. } else if (sourceIsArray) {
  97930. var arrayMerge = options.arrayMerge || defaultArrayMerge;
  97931. return arrayMerge(target, source, optionsArgument)
  97932. } else {
  97933. return mergeObject(target, source, optionsArgument)
  97934. }
  97935. }
  97936. deepmerge.all = function deepmergeAll(array, optionsArgument) {
  97937. if (!Array.isArray(array)) {
  97938. throw new Error('first argument should be an array')
  97939. }
  97940. return array.reduce(function(prev, next) {
  97941. return deepmerge(prev, next, optionsArgument)
  97942. }, {})
  97943. };
  97944. var deepmerge_1 = deepmerge;
  97945. return deepmerge_1;
  97946. })));
  97947. /***/ }),
  97948. /* 3 */
  97949. /***/ (function(module, exports, __webpack_require__) {
  97950. "use strict";
  97951. Object.defineProperty(exports, "__esModule", { value: true });
  97952. /**
  97953. * Is the provided string a URL?
  97954. *
  97955. * @param urlToCheck the url to inspect
  97956. */
  97957. function isUrl(urlToCheck) {
  97958. if (urlToCheck.indexOf('http') === 0 || urlToCheck.indexOf('/') === 0 || urlToCheck.indexOf('./') === 0 || urlToCheck.indexOf('../') === 0) {
  97959. return true;
  97960. }
  97961. return false;
  97962. }
  97963. exports.isUrl = isUrl;
  97964. /**
  97965. * Convert a string from kebab-case to camelCase
  97966. * @param s string to convert
  97967. */
  97968. function kebabToCamel(s) {
  97969. return s.replace(/(\-\w)/g, function (m) { return m[1].toUpperCase(); });
  97970. }
  97971. exports.kebabToCamel = kebabToCamel;
  97972. //https://gist.github.com/youssman/745578062609e8acac9f
  97973. /**
  97974. * Convert a string from camelCase to kebab-case
  97975. * @param str string to convert
  97976. */
  97977. function camelToKebab(str) {
  97978. return !str ? null : str.replace(/([A-Z])/g, function (g) { return '-' + g[0].toLowerCase(); });
  97979. }
  97980. exports.camelToKebab = camelToKebab;
  97981. /***/ }),
  97982. /* 4 */
  97983. /***/ (function(module, exports, __webpack_require__) {
  97984. "use strict";
  97985. Object.defineProperty(exports, "__esModule", { value: true });
  97986. var babylonjs_1 = __webpack_require__(0);
  97987. /**
  97988. * The viewer manager is the container for all viewers currently registered on this page.
  97989. * It is possible to have more than one viewer on a single page.
  97990. */
  97991. var ViewerManager = /** @class */ (function () {
  97992. function ViewerManager() {
  97993. this._viewers = {};
  97994. this.onViewerAddedObservable = new babylonjs_1.Observable();
  97995. this.onViewerRemovedObservable = new babylonjs_1.Observable();
  97996. }
  97997. /**
  97998. * Adding a new viewer to the viewer manager and start tracking it.
  97999. * @param viewer the viewer to add
  98000. */
  98001. ViewerManager.prototype.addViewer = function (viewer) {
  98002. this._viewers[viewer.getBaseId()] = viewer;
  98003. this._onViewerAdded(viewer);
  98004. };
  98005. /**
  98006. * remove a viewer from the viewer manager
  98007. * @param viewer the viewer to remove
  98008. */
  98009. ViewerManager.prototype.removeViewer = function (viewer) {
  98010. var id = viewer.getBaseId();
  98011. delete this._viewers[id];
  98012. this.onViewerRemovedObservable.notifyObservers(id);
  98013. };
  98014. /**
  98015. * 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)
  98016. * @param id the id of the HTMl element (or the viewer's, if none provided)
  98017. */
  98018. ViewerManager.prototype.getViewerById = function (id) {
  98019. return this._viewers[id];
  98020. };
  98021. /**
  98022. * Get a viewer using a container element
  98023. * @param element the HTML element to search viewers associated with
  98024. */
  98025. ViewerManager.prototype.getViewerByHTMLElement = function (element) {
  98026. for (var id in this._viewers) {
  98027. if (this._viewers[id].containerElement === element) {
  98028. return this.getViewerById(id);
  98029. }
  98030. }
  98031. };
  98032. /**
  98033. * Get a promise that will fullfil when this viewer was initialized.
  98034. * Since viewer initialization and template injection is asynchronous, using the promise will guaranty that
  98035. * you will get the viewer after everything was already configured.
  98036. * @param id the viewer id to find
  98037. */
  98038. ViewerManager.prototype.getViewerPromiseById = function (id) {
  98039. var _this = this;
  98040. return new Promise(function (resolve, reject) {
  98041. var localViewer = _this.getViewerById(id);
  98042. if (localViewer) {
  98043. return resolve(localViewer);
  98044. }
  98045. var viewerFunction = function (viewer) {
  98046. if (viewer.getBaseId() === id) {
  98047. resolve(viewer);
  98048. _this.onViewerAddedObservable.removeCallback(viewerFunction);
  98049. }
  98050. };
  98051. _this.onViewerAddedObservable.add(viewerFunction);
  98052. });
  98053. };
  98054. ViewerManager.prototype._onViewerAdded = function (viewer) {
  98055. this.onViewerAdded && this.onViewerAdded(viewer);
  98056. this.onViewerAddedObservable.notifyObservers(viewer);
  98057. };
  98058. /**
  98059. * dispose the manager and all of its associated viewers
  98060. */
  98061. ViewerManager.prototype.dispose = function () {
  98062. for (var id in this._viewers) {
  98063. this._viewers[id].dispose();
  98064. }
  98065. };
  98066. return ViewerManager;
  98067. }());
  98068. exports.ViewerManager = ViewerManager;
  98069. exports.viewerManager = new ViewerManager();
  98070. /***/ }),
  98071. /* 5 */
  98072. /***/ (function(module, exports, __webpack_require__) {
  98073. "use strict";
  98074. var __extends = (this && this.__extends) || (function () {
  98075. var extendStatics = Object.setPrototypeOf ||
  98076. ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
  98077. function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
  98078. return function (d, b) {
  98079. extendStatics(d, b);
  98080. function __() { this.constructor = d; }
  98081. d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
  98082. };
  98083. })();
  98084. Object.defineProperty(exports, "__esModule", { value: true });
  98085. var viewer_1 = __webpack_require__(6);
  98086. var babylonjs_1 = __webpack_require__(0);
  98087. /**
  98088. * The Default viewer is the default implementation of the AbstractViewer.
  98089. * It uses the templating system to render a new canvas and controls.
  98090. */
  98091. var DefaultViewer = /** @class */ (function (_super) {
  98092. __extends(DefaultViewer, _super);
  98093. /**
  98094. * Create a new default viewer
  98095. * @param containerElement the element in which the templates will be rendered
  98096. * @param initialConfiguration the initial configuration. Defaults to extending the default configuration
  98097. */
  98098. function DefaultViewer(containerElement, initialConfiguration) {
  98099. if (initialConfiguration === void 0) { initialConfiguration = { extends: 'default' }; }
  98100. var _this = _super.call(this, containerElement, initialConfiguration) || this;
  98101. _this.containerElement = containerElement;
  98102. _this._onModelLoaded = function (model) {
  98103. _this._configureTemplate(model);
  98104. // with a short timeout, making sure everything is there already.
  98105. var hideLoadingDelay = 500;
  98106. if (_this._configuration.lab && _this._configuration.lab.hideLoadingDelay !== undefined) {
  98107. hideLoadingDelay = _this._configuration.lab.hideLoadingDelay;
  98108. }
  98109. setTimeout(function () {
  98110. _this.hideLoadingScreen();
  98111. }, hideLoadingDelay);
  98112. return;
  98113. };
  98114. _this.onModelLoadedObservable.add(_this._onModelLoaded);
  98115. return _this;
  98116. }
  98117. /**
  98118. * Overriding the AbstractViewer's _initScene fcuntion
  98119. */
  98120. DefaultViewer.prototype._initScene = function () {
  98121. var _this = this;
  98122. return _super.prototype._initScene.call(this).then(function () {
  98123. _this._extendClassWithConfig(_this.scene, _this._configuration.scene);
  98124. return _this.scene;
  98125. });
  98126. };
  98127. /**
  98128. * This will be executed when the templates initialize.
  98129. */
  98130. DefaultViewer.prototype._onTemplatesLoaded = function () {
  98131. var _this = this;
  98132. this.showLoadingScreen();
  98133. // navbar
  98134. this._initNavbar();
  98135. // close overlay button
  98136. var closeButton = document.getElementById('close-button');
  98137. if (closeButton) {
  98138. closeButton.addEventListener('pointerdown', function () {
  98139. _this.hideOverlayScreen();
  98140. });
  98141. }
  98142. return _super.prototype._onTemplatesLoaded.call(this);
  98143. };
  98144. DefaultViewer.prototype._initNavbar = function () {
  98145. var navbar = this.templateManager.getTemplate('navBar');
  98146. if (navbar) {
  98147. var navbarHeight_1 = navbar.parent.clientHeight + 'px';
  98148. var navbarShown_1 = true;
  98149. var timeoutCancel_1 /*: number*/;
  98150. var triggerNavbar = function (show, evt) {
  98151. if (show === void 0) { show = false; }
  98152. // only left-click on no-button.
  98153. if (!navbar || evt.button > 0)
  98154. return;
  98155. // clear timeout
  98156. timeoutCancel_1 && clearTimeout(timeoutCancel_1);
  98157. // if state is the same, do nothing
  98158. if (show === navbarShown_1)
  98159. return;
  98160. //showing? simply show it!
  98161. if (show) {
  98162. navbar.parent.style.bottom = show ? '0px' : '-' + navbarHeight_1;
  98163. navbarShown_1 = show;
  98164. }
  98165. else {
  98166. var visibilityTimeout = 2000;
  98167. if (navbar.configuration.params && navbar.configuration.params.visibilityTimeout !== undefined) {
  98168. visibilityTimeout = navbar.configuration.params.visibilityTimeout;
  98169. }
  98170. // not showing? set timeout until it is removed.
  98171. timeoutCancel_1 = setTimeout(function () {
  98172. if (navbar) {
  98173. navbar.parent.style.bottom = '-' + navbarHeight_1;
  98174. }
  98175. navbarShown_1 = show;
  98176. }, visibilityTimeout);
  98177. }
  98178. };
  98179. this.templateManager.eventManager.registerCallback('viewer', triggerNavbar.bind(this, false), 'pointerout');
  98180. this.templateManager.eventManager.registerCallback('viewer', triggerNavbar.bind(this, true), 'pointerdown');
  98181. this.templateManager.eventManager.registerCallback('viewer', triggerNavbar.bind(this, false), 'pointerup');
  98182. this.templateManager.eventManager.registerCallback('navBar', triggerNavbar.bind(this, true), 'pointerover');
  98183. // other events
  98184. var viewerTemplate = this.templateManager.getTemplate('viewer');
  98185. var viewerElement_1 = viewerTemplate && viewerTemplate.parent;
  98186. // full screen
  98187. var triggerFullscren = function (eventData) {
  98188. if (viewerElement_1) {
  98189. var fullscreenElement = document.fullscreenElement || document.webkitFullscreenElement || document.mozFullScreenElement || document.msFullscreenElement;
  98190. if (!fullscreenElement) {
  98191. var requestFullScreen = viewerElement_1.requestFullscreen || viewerElement_1.webkitRequestFullscreen || viewerElement_1.msRequestFullscreen || viewerElement_1.mozRequestFullScreen;
  98192. requestFullScreen.call(viewerElement_1);
  98193. }
  98194. else {
  98195. var exitFullscreen = document.exitFullscreen || document.webkitExitFullscreen || document.msExitFullscreen || document.mozCancelFullScreen;
  98196. exitFullscreen.call(document);
  98197. }
  98198. }
  98199. };
  98200. this.templateManager.eventManager.registerCallback('navBar', triggerFullscren, 'pointerdown', '#fullscreen-button');
  98201. }
  98202. };
  98203. /**
  98204. * Preparing the container element to present the viewer
  98205. */
  98206. DefaultViewer.prototype._prepareContainerElement = function () {
  98207. this.containerElement.style.position = 'relative';
  98208. this.containerElement.style.display = 'flex';
  98209. };
  98210. /**
  98211. * This function will configure the templates and update them after a model was loaded
  98212. * It is mainly responsible to changing the title and subtitle etc'.
  98213. * @param model the model to be used to configure the templates by
  98214. */
  98215. DefaultViewer.prototype._configureTemplate = function (model) {
  98216. var navbar = this.templateManager.getTemplate('navBar');
  98217. if (!navbar)
  98218. return;
  98219. var modelConfiguration = model.configuration;
  98220. var metadataContainer = navbar.parent.querySelector('#model-metadata');
  98221. if (metadataContainer) {
  98222. if (modelConfiguration.title !== undefined) {
  98223. var element = metadataContainer.querySelector('span.model-title');
  98224. if (element) {
  98225. element.innerHTML = modelConfiguration.title;
  98226. }
  98227. }
  98228. if (modelConfiguration.subtitle !== undefined) {
  98229. var element = metadataContainer.querySelector('span.model-subtitle');
  98230. if (element) {
  98231. element.innerHTML = modelConfiguration.subtitle;
  98232. }
  98233. }
  98234. if (modelConfiguration.thumbnail !== undefined) {
  98235. metadataContainer.querySelector('.thumbnail').style.backgroundImage = "url('" + modelConfiguration.thumbnail + "')";
  98236. }
  98237. }
  98238. };
  98239. /**
  98240. * This will load a new model to the default viewer
  98241. * overriding the AbstractViewer's loadModel.
  98242. * The scene will automatically be cleared of the old models, if exist.
  98243. * @param model the configuration object (or URL) to load.
  98244. */
  98245. DefaultViewer.prototype.loadModel = function (model) {
  98246. var _this = this;
  98247. if (model === void 0) { model = this._configuration.model; }
  98248. this.showLoadingScreen();
  98249. return _super.prototype.loadModel.call(this, model, true).catch(function (error) {
  98250. console.log(error);
  98251. _this.hideLoadingScreen();
  98252. _this.showOverlayScreen('error');
  98253. return Promise.reject(error);
  98254. });
  98255. };
  98256. /**
  98257. * Show the overlay and the defined sub-screen.
  98258. * Mainly used for help and errors
  98259. * @param subScreen the name of the subScreen. Those can be defined in the configuration object
  98260. */
  98261. DefaultViewer.prototype.showOverlayScreen = function (subScreen) {
  98262. var _this = this;
  98263. var template = this.templateManager.getTemplate('overlay');
  98264. if (!template)
  98265. return Promise.resolve('Overlay template not found');
  98266. return template.show((function (template) {
  98267. var canvasRect = _this.containerElement.getBoundingClientRect();
  98268. var canvasPositioning = window.getComputedStyle(_this.containerElement).position;
  98269. template.parent.style.display = 'flex';
  98270. template.parent.style.width = canvasRect.width + "px";
  98271. template.parent.style.height = canvasRect.height + "px";
  98272. template.parent.style.opacity = "1";
  98273. var subTemplate = _this.templateManager.getTemplate(subScreen);
  98274. if (!subTemplate) {
  98275. return Promise.reject(subScreen + ' template not found');
  98276. }
  98277. return subTemplate.show((function (template) {
  98278. template.parent.style.display = 'flex';
  98279. return Promise.resolve(template);
  98280. }));
  98281. }));
  98282. };
  98283. /**
  98284. * Hide the overlay screen.
  98285. */
  98286. DefaultViewer.prototype.hideOverlayScreen = function () {
  98287. var template = this.templateManager.getTemplate('overlay');
  98288. if (!template)
  98289. return Promise.resolve('Overlay template not found');
  98290. return template.hide((function (template) {
  98291. template.parent.style.opacity = "0";
  98292. var onTransitionEnd = function () {
  98293. template.parent.removeEventListener("transitionend", onTransitionEnd);
  98294. template.parent.style.display = 'none';
  98295. };
  98296. template.parent.addEventListener("transitionend", onTransitionEnd);
  98297. var overlays = template.parent.querySelectorAll('.overlay');
  98298. if (overlays) {
  98299. for (var i = 0; i < overlays.length; ++i) {
  98300. var htmlElement = overlays.item(i);
  98301. htmlElement.style.display = 'none';
  98302. }
  98303. }
  98304. return Promise.resolve(template);
  98305. }));
  98306. };
  98307. /**
  98308. * Show the loading screen.
  98309. * The loading screen can be configured using the configuration object
  98310. */
  98311. DefaultViewer.prototype.showLoadingScreen = function () {
  98312. var _this = this;
  98313. var template = this.templateManager.getTemplate('loadingScreen');
  98314. if (!template)
  98315. return Promise.resolve('Loading Screen template not found');
  98316. return template.show((function (template) {
  98317. var canvasRect = _this.containerElement.getBoundingClientRect();
  98318. var canvasPositioning = window.getComputedStyle(_this.containerElement).position;
  98319. template.parent.style.display = 'flex';
  98320. template.parent.style.width = canvasRect.width + "px";
  98321. template.parent.style.height = canvasRect.height + "px";
  98322. template.parent.style.opacity = "1";
  98323. // from the configuration!!!
  98324. template.parent.style.backgroundColor = "black";
  98325. return Promise.resolve(template);
  98326. }));
  98327. };
  98328. /**
  98329. * Hide the loading screen
  98330. */
  98331. DefaultViewer.prototype.hideLoadingScreen = function () {
  98332. var template = this.templateManager.getTemplate('loadingScreen');
  98333. if (!template)
  98334. return Promise.resolve('Loading Screen template not found');
  98335. return template.hide((function (template) {
  98336. template.parent.style.opacity = "0";
  98337. var onTransitionEnd = function () {
  98338. template.parent.removeEventListener("transitionend", onTransitionEnd);
  98339. template.parent.style.display = 'none';
  98340. };
  98341. template.parent.addEventListener("transitionend", onTransitionEnd);
  98342. return Promise.resolve(template);
  98343. }));
  98344. };
  98345. /**
  98346. * An extension of the light configuration of the abstract viewer.
  98347. * @param lightsConfiguration the light configuration to use
  98348. * @param model the model that will be used to configure the lights (if the lights are model-dependant)
  98349. */
  98350. DefaultViewer.prototype._configureLights = function (lightsConfiguration, model) {
  98351. var _this = this;
  98352. if (lightsConfiguration === void 0) { lightsConfiguration = {}; }
  98353. _super.prototype._configureLights.call(this, lightsConfiguration, model);
  98354. // labs feature - flashlight
  98355. if (this._configuration.lab && this._configuration.lab.flashlight) {
  98356. var pointerPosition = babylonjs_1.Vector3.Zero();
  98357. var lightTarget_1;
  98358. var angle = 0.5;
  98359. var exponent = Math.PI / 2;
  98360. if (typeof this._configuration.lab.flashlight === "object") {
  98361. exponent = this._configuration.lab.flashlight.exponent || exponent;
  98362. angle = this._configuration.lab.flashlight.angle || angle;
  98363. }
  98364. var flashlight = new babylonjs_1.SpotLight("flashlight", babylonjs_1.Vector3.Zero(), babylonjs_1.Vector3.Zero(), exponent, angle, this.scene);
  98365. if (typeof this._configuration.lab.flashlight === "object") {
  98366. flashlight.intensity = this._configuration.lab.flashlight.intensity || flashlight.intensity;
  98367. if (this._configuration.lab.flashlight.diffuse) {
  98368. flashlight.diffuse.r = this._configuration.lab.flashlight.diffuse.r;
  98369. flashlight.diffuse.g = this._configuration.lab.flashlight.diffuse.g;
  98370. flashlight.diffuse.b = this._configuration.lab.flashlight.diffuse.b;
  98371. }
  98372. if (this._configuration.lab.flashlight.specular) {
  98373. flashlight.specular.r = this._configuration.lab.flashlight.specular.r;
  98374. flashlight.specular.g = this._configuration.lab.flashlight.specular.g;
  98375. flashlight.specular.b = this._configuration.lab.flashlight.specular.b;
  98376. }
  98377. }
  98378. this.scene.constantlyUpdateMeshUnderPointer = true;
  98379. this.scene.onPointerObservable.add(function (eventData, eventState) {
  98380. if (eventData.type === 4 && eventData.pickInfo) {
  98381. lightTarget_1 = (eventData.pickInfo.pickedPoint);
  98382. }
  98383. else {
  98384. lightTarget_1 = undefined;
  98385. }
  98386. });
  98387. var updateFlashlightFunction = function () {
  98388. if (_this.camera && flashlight) {
  98389. flashlight.position.copyFrom(_this.camera.position);
  98390. if (lightTarget_1) {
  98391. lightTarget_1.subtractToRef(flashlight.position, flashlight.direction);
  98392. }
  98393. }
  98394. };
  98395. this.scene.registerBeforeRender(updateFlashlightFunction);
  98396. this._registeredOnBeforeRenderFunctions.push(updateFlashlightFunction);
  98397. }
  98398. };
  98399. return DefaultViewer;
  98400. }(viewer_1.AbstractViewer));
  98401. exports.DefaultViewer = DefaultViewer;
  98402. /***/ }),
  98403. /* 6 */
  98404. /***/ (function(module, exports, __webpack_require__) {
  98405. "use strict";
  98406. Object.defineProperty(exports, "__esModule", { value: true });
  98407. var viewerManager_1 = __webpack_require__(4);
  98408. var templateManager_1 = __webpack_require__(23);
  98409. var loader_1 = __webpack_require__(26);
  98410. var babylonjs_1 = __webpack_require__(0);
  98411. var deepmerge = __webpack_require__(2);
  98412. var modelLoader_1 = __webpack_require__(14);
  98413. /**
  98414. * The AbstractViewr is the center of Babylon's viewer.
  98415. * It is the basic implementation of the default viewer and is responsible of loading and showing the model and the templates
  98416. */
  98417. var AbstractViewer = /** @class */ (function () {
  98418. function AbstractViewer(containerElement, initialConfiguration) {
  98419. if (initialConfiguration === void 0) { initialConfiguration = {}; }
  98420. var _this = this;
  98421. this.containerElement = containerElement;
  98422. /**
  98423. * is this viewer disposed?
  98424. */
  98425. this._isDisposed = false;
  98426. /**
  98427. * The resize function that will be registered with the window object
  98428. */
  98429. this._resize = function () {
  98430. // Only resize if Canvas is in the DOM
  98431. if (!_this.isCanvasInDOM()) {
  98432. return;
  98433. }
  98434. if (_this.canvas.clientWidth <= 0 || _this.canvas.clientHeight <= 0) {
  98435. return;
  98436. }
  98437. _this.engine.resize();
  98438. };
  98439. /**
  98440. * render loop that will be executed by the engine
  98441. */
  98442. this._render = function () {
  98443. _this.scene && _this.scene.activeCamera && _this.scene.render();
  98444. };
  98445. // if exists, use the container id. otherwise, generate a random string.
  98446. if (containerElement.id) {
  98447. this.baseId = containerElement.id;
  98448. }
  98449. else {
  98450. this.baseId = containerElement.id = 'bjs' + Math.random().toString(32).substr(2, 8);
  98451. }
  98452. this.onSceneInitObservable = new babylonjs_1.Observable();
  98453. this.onEngineInitObservable = new babylonjs_1.Observable();
  98454. this.onModelLoadedObservable = new babylonjs_1.Observable();
  98455. this.onModelLoadProgressObservable = new babylonjs_1.Observable();
  98456. this.onModelLoadErrorObservable = new babylonjs_1.Observable();
  98457. this.onInitDoneObservable = new babylonjs_1.Observable();
  98458. this.onLoaderInitObservable = new babylonjs_1.Observable();
  98459. this._registeredOnBeforeRenderFunctions = [];
  98460. this.models = [];
  98461. this.modelLoader = new modelLoader_1.ModelLoader(this);
  98462. // add this viewer to the viewer manager
  98463. viewerManager_1.viewerManager.addViewer(this);
  98464. // create a new template manager. TODO - singleton?
  98465. this.templateManager = new templateManager_1.TemplateManager(containerElement);
  98466. this._prepareContainerElement();
  98467. // extend the configuration
  98468. this._configurationLoader = new loader_1.ConfigurationLoader();
  98469. this._configurationLoader.loadConfiguration(initialConfiguration, function (configuration) {
  98470. _this._configuration = deepmerge(_this._configuration || {}, configuration);
  98471. if (_this._configuration.observers) {
  98472. _this._configureObservers(_this._configuration.observers);
  98473. }
  98474. //this.updateConfiguration(configuration);
  98475. // initialize the templates
  98476. var templateConfiguration = _this._configuration.templates || {};
  98477. _this.templateManager.initTemplate(templateConfiguration);
  98478. // when done, execute onTemplatesLoaded()
  98479. _this.templateManager.onAllLoaded.add(function () {
  98480. var canvas = _this.templateManager.getCanvas();
  98481. if (canvas) {
  98482. _this._canvas = canvas;
  98483. }
  98484. _this._onTemplateLoaded();
  98485. });
  98486. });
  98487. }
  98488. Object.defineProperty(AbstractViewer.prototype, "isHdrSupported", {
  98489. /**
  98490. * Returns a boolean representing HDR support
  98491. */
  98492. get: function () {
  98493. return this._hdrSupport;
  98494. },
  98495. enumerable: true,
  98496. configurable: true
  98497. });
  98498. Object.defineProperty(AbstractViewer.prototype, "canvas", {
  98499. /**
  98500. * The (single) canvas of this viewer
  98501. */
  98502. get: function () {
  98503. return this._canvas;
  98504. },
  98505. enumerable: true,
  98506. configurable: true
  98507. });
  98508. /**
  98509. * get the baseId of this viewer
  98510. */
  98511. AbstractViewer.prototype.getBaseId = function () {
  98512. return this.baseId;
  98513. };
  98514. /**
  98515. * Do we have a canvas to render on, and is it a part of the scene
  98516. */
  98517. AbstractViewer.prototype.isCanvasInDOM = function () {
  98518. return !!this._canvas && !!this._canvas.parentElement;
  98519. };
  98520. /**
  98521. * Update the current viewer configuration with new values.
  98522. * Only provided information will be updated, old configuration values will be kept.
  98523. * If this.configuration was manually changed, you can trigger this function with no parameters,
  98524. * and the entire configuration will be updated.
  98525. * @param newConfiguration
  98526. */
  98527. AbstractViewer.prototype.updateConfiguration = function (newConfiguration) {
  98528. if (newConfiguration === void 0) { newConfiguration = this._configuration; }
  98529. // update this.configuration with the new data
  98530. this._configuration = deepmerge(this._configuration || {}, newConfiguration);
  98531. // update scene configuration
  98532. if (newConfiguration.scene) {
  98533. this._configureScene(newConfiguration.scene);
  98534. }
  98535. // optimizer
  98536. if (newConfiguration.optimizer) {
  98537. this._configureOptimizer(newConfiguration.optimizer);
  98538. }
  98539. // observers in configuration
  98540. if (newConfiguration.observers) {
  98541. this._configureObservers(newConfiguration.observers);
  98542. }
  98543. // configure model
  98544. if (newConfiguration.model && typeof newConfiguration.model === 'object') {
  98545. this._configureModel(newConfiguration.model);
  98546. }
  98547. // lights
  98548. if (newConfiguration.lights) {
  98549. this._configureLights(newConfiguration.lights);
  98550. }
  98551. // environment
  98552. if (newConfiguration.skybox !== undefined || newConfiguration.ground !== undefined) {
  98553. this._configureEnvironment(newConfiguration.skybox, newConfiguration.ground);
  98554. }
  98555. // camera
  98556. if (newConfiguration.camera) {
  98557. this._configureCamera(newConfiguration.camera);
  98558. }
  98559. };
  98560. AbstractViewer.prototype._configureEnvironment = function (skyboxConifguration, groundConfiguration) {
  98561. if (!skyboxConifguration && !groundConfiguration) {
  98562. if (this.environmentHelper) {
  98563. this.environmentHelper.dispose();
  98564. delete this.environmentHelper;
  98565. }
  98566. ;
  98567. return Promise.resolve(this.scene);
  98568. }
  98569. var options = {
  98570. createGround: !!groundConfiguration,
  98571. createSkybox: !!skyboxConifguration,
  98572. setupImageProcessing: false // will be done at the scene level!
  98573. };
  98574. if (groundConfiguration) {
  98575. var groundConfig = (typeof groundConfiguration === 'boolean') ? {} : groundConfiguration;
  98576. var groundSize = groundConfig.size || (typeof skyboxConifguration === 'object' && skyboxConifguration.scale);
  98577. if (groundSize) {
  98578. options.groundSize = groundSize;
  98579. }
  98580. options.enableGroundShadow = groundConfig === true || groundConfig.receiveShadows;
  98581. if (groundConfig.shadowLevel !== undefined) {
  98582. options.groundShadowLevel = groundConfig.shadowLevel;
  98583. }
  98584. options.enableGroundMirror = !!groundConfig.mirror;
  98585. if (groundConfig.texture) {
  98586. options.groundTexture = groundConfig.texture;
  98587. }
  98588. if (groundConfig.color) {
  98589. options.groundColor = new babylonjs_1.Color3(groundConfig.color.r, groundConfig.color.g, groundConfig.color.b);
  98590. }
  98591. if (groundConfig.opacity !== undefined) {
  98592. options.groundOpacity = groundConfig.opacity;
  98593. }
  98594. if (groundConfig.mirror) {
  98595. options.enableGroundMirror = true;
  98596. // to prevent undefines
  98597. if (typeof groundConfig.mirror === "object") {
  98598. if (groundConfig.mirror.amount !== undefined)
  98599. options.groundMirrorAmount = groundConfig.mirror.amount;
  98600. if (groundConfig.mirror.sizeRatio !== undefined)
  98601. options.groundMirrorSizeRatio = groundConfig.mirror.sizeRatio;
  98602. if (groundConfig.mirror.blurKernel !== undefined)
  98603. options.groundMirrorBlurKernel = groundConfig.mirror.blurKernel;
  98604. if (groundConfig.mirror.fresnelWeight !== undefined)
  98605. options.groundMirrorFresnelWeight = groundConfig.mirror.fresnelWeight;
  98606. if (groundConfig.mirror.fallOffDistance !== undefined)
  98607. options.groundMirrorFallOffDistance = groundConfig.mirror.fallOffDistance;
  98608. if (this._defaultPipelineTextureType !== undefined)
  98609. options.groundMirrorTextureType = this._defaultPipelineTextureType;
  98610. }
  98611. }
  98612. }
  98613. var postInitSkyboxMaterial = false;
  98614. if (skyboxConifguration) {
  98615. var conf = skyboxConifguration === true ? {} : skyboxConifguration;
  98616. if (conf.material && conf.material.imageProcessingConfiguration) {
  98617. options.setupImageProcessing = false; // will be configured later manually.
  98618. }
  98619. var skyboxSize = conf.scale;
  98620. if (skyboxSize) {
  98621. options.skyboxSize = skyboxSize;
  98622. }
  98623. options.sizeAuto = !options.skyboxSize;
  98624. if (conf.color) {
  98625. options.skyboxColor = new babylonjs_1.Color3(conf.color.r, conf.color.g, conf.color.b);
  98626. }
  98627. if (conf.cubeTexture && conf.cubeTexture.url) {
  98628. if (typeof conf.cubeTexture.url === "string") {
  98629. options.skyboxTexture = conf.cubeTexture.url;
  98630. }
  98631. else {
  98632. // init later!
  98633. postInitSkyboxMaterial = true;
  98634. }
  98635. }
  98636. if (conf.material && conf.material.imageProcessingConfiguration) {
  98637. postInitSkyboxMaterial = true;
  98638. }
  98639. }
  98640. options.setupImageProcessing = false; // TMP
  98641. if (!this.environmentHelper) {
  98642. this.environmentHelper = this.scene.createDefaultEnvironment(options);
  98643. }
  98644. else {
  98645. // there might be a new scene! we need to dispose.
  98646. // get the scene used by the envHelper
  98647. var scene = this.environmentHelper.rootMesh.getScene();
  98648. // is it a different scene? Oh no!
  98649. if (scene !== this.scene) {
  98650. this.environmentHelper.dispose();
  98651. this.environmentHelper = this.scene.createDefaultEnvironment(options);
  98652. }
  98653. else {
  98654. this.environmentHelper.updateOptions(options);
  98655. }
  98656. }
  98657. if (postInitSkyboxMaterial) {
  98658. var skyboxMaterial = this.environmentHelper.skyboxMaterial;
  98659. if (skyboxMaterial) {
  98660. if (typeof skyboxConifguration === 'object' && skyboxConifguration.material && skyboxConifguration.material.imageProcessingConfiguration) {
  98661. this._extendClassWithConfig(skyboxMaterial.imageProcessingConfiguration, skyboxConifguration.material.imageProcessingConfiguration);
  98662. }
  98663. }
  98664. }
  98665. };
  98666. /**
  98667. * internally configure the scene using the provided configuration.
  98668. * The scene will not be recreated, but just updated.
  98669. * @param sceneConfig the (new) scene configuration
  98670. */
  98671. AbstractViewer.prototype._configureScene = function (sceneConfig) {
  98672. // sanity check!
  98673. if (!this.scene) {
  98674. return;
  98675. }
  98676. if (sceneConfig.debug) {
  98677. this.scene.debugLayer.show();
  98678. }
  98679. else {
  98680. if (this.scene.debugLayer.isVisible()) {
  98681. this.scene.debugLayer.hide();
  98682. }
  98683. }
  98684. if (sceneConfig.clearColor) {
  98685. var cc = sceneConfig.clearColor;
  98686. var oldcc = this.scene.clearColor;
  98687. if (cc.r !== undefined) {
  98688. oldcc.r = cc.r;
  98689. }
  98690. if (cc.g !== undefined) {
  98691. oldcc.g = cc.g;
  98692. }
  98693. if (cc.b !== undefined) {
  98694. oldcc.b = cc.b;
  98695. }
  98696. if (cc.a !== undefined) {
  98697. oldcc.a = cc.a;
  98698. }
  98699. }
  98700. // image processing configuration - optional.
  98701. if (sceneConfig.imageProcessingConfiguration) {
  98702. this._extendClassWithConfig(this.scene.imageProcessingConfiguration, sceneConfig.imageProcessingConfiguration);
  98703. }
  98704. if (sceneConfig.environmentTexture) {
  98705. if (this.scene.environmentTexture) {
  98706. this.scene.environmentTexture.dispose();
  98707. }
  98708. var environmentTexture = babylonjs_1.CubeTexture.CreateFromPrefilteredData(sceneConfig.environmentTexture, this.scene);
  98709. this.scene.environmentTexture = environmentTexture;
  98710. }
  98711. if (sceneConfig.autoRotate) {
  98712. this.camera.useAutoRotationBehavior = true;
  98713. }
  98714. };
  98715. /**
  98716. * Configure the scene optimizer.
  98717. * The existing scene optimizer will be disposed and a new one will be created.
  98718. * @param optimizerConfig the (new) optimizer configuration
  98719. */
  98720. AbstractViewer.prototype._configureOptimizer = function (optimizerConfig) {
  98721. if (typeof optimizerConfig === 'boolean') {
  98722. if (this.sceneOptimizer) {
  98723. this.sceneOptimizer.stop();
  98724. this.sceneOptimizer.dispose();
  98725. delete this.sceneOptimizer;
  98726. }
  98727. if (optimizerConfig) {
  98728. this.sceneOptimizer = new babylonjs_1.SceneOptimizer(this.scene);
  98729. this.sceneOptimizer.start();
  98730. }
  98731. }
  98732. else {
  98733. var optimizerOptions = new babylonjs_1.SceneOptimizerOptions(optimizerConfig.targetFrameRate, optimizerConfig.trackerDuration);
  98734. // check for degradation
  98735. if (optimizerConfig.degradation) {
  98736. switch (optimizerConfig.degradation) {
  98737. case "low":
  98738. optimizerOptions = babylonjs_1.SceneOptimizerOptions.LowDegradationAllowed(optimizerConfig.targetFrameRate);
  98739. break;
  98740. case "moderate":
  98741. optimizerOptions = babylonjs_1.SceneOptimizerOptions.ModerateDegradationAllowed(optimizerConfig.targetFrameRate);
  98742. break;
  98743. case "hight":
  98744. optimizerOptions = babylonjs_1.SceneOptimizerOptions.HighDegradationAllowed(optimizerConfig.targetFrameRate);
  98745. break;
  98746. }
  98747. }
  98748. if (this.sceneOptimizer) {
  98749. this.sceneOptimizer.stop();
  98750. this.sceneOptimizer.dispose();
  98751. }
  98752. this.sceneOptimizer = new babylonjs_1.SceneOptimizer(this.scene, optimizerOptions, optimizerConfig.autoGeneratePriorities, optimizerConfig.improvementMode);
  98753. this.sceneOptimizer.start();
  98754. }
  98755. };
  98756. /**
  98757. * this is used to register native functions using the configuration object.
  98758. * This will configure the observers.
  98759. * @param observersConfiguration observers configuration
  98760. */
  98761. AbstractViewer.prototype._configureObservers = function (observersConfiguration) {
  98762. if (observersConfiguration.onEngineInit) {
  98763. this.onEngineInitObservable.add(window[observersConfiguration.onEngineInit]);
  98764. }
  98765. else {
  98766. if (observersConfiguration.onEngineInit === '' && this._configuration.observers && this._configuration.observers.onEngineInit) {
  98767. this.onEngineInitObservable.removeCallback(window[this._configuration.observers.onEngineInit]);
  98768. }
  98769. }
  98770. if (observersConfiguration.onSceneInit) {
  98771. this.onSceneInitObservable.add(window[observersConfiguration.onSceneInit]);
  98772. }
  98773. else {
  98774. if (observersConfiguration.onSceneInit === '' && this._configuration.observers && this._configuration.observers.onSceneInit) {
  98775. this.onSceneInitObservable.removeCallback(window[this._configuration.observers.onSceneInit]);
  98776. }
  98777. }
  98778. if (observersConfiguration.onModelLoaded) {
  98779. this.onModelLoadedObservable.add(window[observersConfiguration.onModelLoaded]);
  98780. }
  98781. else {
  98782. if (observersConfiguration.onModelLoaded === '' && this._configuration.observers && this._configuration.observers.onModelLoaded) {
  98783. this.onModelLoadedObservable.removeCallback(window[this._configuration.observers.onModelLoaded]);
  98784. }
  98785. }
  98786. };
  98787. /**
  98788. * (Re) configure the camera. The camera will only be created once and from this point will only be reconfigured.
  98789. * @param cameraConfig the new camera configuration
  98790. * @param model optionally use the model to configure the camera.
  98791. */
  98792. AbstractViewer.prototype._configureCamera = function (cameraConfig, model) {
  98793. var _this = this;
  98794. var focusMeshes = model ? model.meshes : this.scene.meshes;
  98795. if (!this.scene.activeCamera) {
  98796. this.scene.createDefaultCamera(true, true, true);
  98797. this.camera = this.scene.activeCamera;
  98798. }
  98799. if (cameraConfig.position) {
  98800. this.camera.position.copyFromFloats(cameraConfig.position.x || 0, cameraConfig.position.y || 0, cameraConfig.position.z || 0);
  98801. }
  98802. if (cameraConfig.rotation) {
  98803. this.camera.rotationQuaternion = new babylonjs_1.Quaternion(cameraConfig.rotation.x || 0, cameraConfig.rotation.y || 0, cameraConfig.rotation.z || 0, cameraConfig.rotation.w || 0);
  98804. }
  98805. this._extendClassWithConfig(this.camera, cameraConfig);
  98806. this.camera.minZ = cameraConfig.minZ || this.camera.minZ;
  98807. this.camera.maxZ = cameraConfig.maxZ || this.camera.maxZ;
  98808. if (cameraConfig.behaviors) {
  98809. for (var name_1 in cameraConfig.behaviors) {
  98810. this._setCameraBehavior(cameraConfig.behaviors[name_1], focusMeshes);
  98811. }
  98812. }
  98813. ;
  98814. var sceneExtends = this.scene.getWorldExtends(function (mesh) {
  98815. return !_this.environmentHelper || (mesh !== _this.environmentHelper.ground && mesh !== _this.environmentHelper.rootMesh && mesh !== _this.environmentHelper.skybox);
  98816. });
  98817. var sceneDiagonal = sceneExtends.max.subtract(sceneExtends.min);
  98818. var sceneDiagonalLenght = sceneDiagonal.length();
  98819. if (isFinite(sceneDiagonalLenght))
  98820. this.camera.upperRadiusLimit = sceneDiagonalLenght * 3;
  98821. };
  98822. /**
  98823. * configure the lights.
  98824. *
  98825. * @param lightsConfiguration the (new) light(s) configuration
  98826. * @param model optionally use the model to configure the camera.
  98827. */
  98828. AbstractViewer.prototype._configureLights = function (lightsConfiguration, model) {
  98829. var _this = this;
  98830. if (lightsConfiguration === void 0) { lightsConfiguration = {}; }
  98831. var focusMeshes = model ? model.meshes : this.scene.meshes;
  98832. // sanity check!
  98833. if (!Object.keys(lightsConfiguration).length)
  98834. return;
  98835. var lightsAvailable = this.scene.lights.map(function (light) { return light.name; });
  98836. // compare to the global (!) configuration object and dispose unneeded:
  98837. var lightsToConfigure = Object.keys(this._configuration.lights || []);
  98838. if (Object.keys(lightsToConfigure).length !== lightsAvailable.length) {
  98839. lightsAvailable.forEach(function (lName) {
  98840. if (lightsToConfigure.indexOf(lName) === -1) {
  98841. _this.scene.getLightByName(lName).dispose();
  98842. }
  98843. });
  98844. }
  98845. Object.keys(lightsConfiguration).forEach(function (name, idx) {
  98846. var lightConfig = { type: 0 };
  98847. if (typeof lightsConfiguration[name] === 'object') {
  98848. lightConfig = lightsConfiguration[name];
  98849. }
  98850. lightConfig.name = name;
  98851. var light;
  98852. // light is not already available
  98853. if (lightsAvailable.indexOf(name) === -1) {
  98854. var constructor = babylonjs_1.Light.GetConstructorFromName(lightConfig.type, lightConfig.name, _this.scene);
  98855. if (!constructor)
  98856. return;
  98857. light = constructor();
  98858. }
  98859. else {
  98860. // available? get it from the scene
  98861. light = _this.scene.getLightByName(name);
  98862. lightsAvailable = lightsAvailable.filter(function (ln) { return ln !== name; });
  98863. if (lightConfig.type !== undefined && light.getTypeID() !== lightConfig.type) {
  98864. light.dispose();
  98865. var constructor = babylonjs_1.Light.GetConstructorFromName(lightConfig.type, lightConfig.name, _this.scene);
  98866. if (!constructor)
  98867. return;
  98868. light = constructor();
  98869. }
  98870. }
  98871. // if config set the light to false, dispose it.
  98872. if (lightsConfiguration[name] === false) {
  98873. light.dispose();
  98874. return;
  98875. }
  98876. //enabled
  98877. var enabled = lightConfig.enabled !== undefined ? lightConfig.enabled : !lightConfig.disabled;
  98878. light.setEnabled(enabled);
  98879. _this._extendClassWithConfig(light, lightConfig);
  98880. //position. Some lights don't support shadows
  98881. if (light instanceof babylonjs_1.ShadowLight) {
  98882. if (lightConfig.target) {
  98883. if (light.setDirectionToTarget) {
  98884. var target = babylonjs_1.Vector3.Zero().copyFrom(lightConfig.target);
  98885. light.setDirectionToTarget(target);
  98886. }
  98887. }
  98888. else if (lightConfig.direction) {
  98889. var direction = babylonjs_1.Vector3.Zero().copyFrom(lightConfig.direction);
  98890. light.direction = direction;
  98891. }
  98892. var shadowGenerator = light.getShadowGenerator();
  98893. if (lightConfig.shadowEnabled && _this._maxShadows) {
  98894. if (!shadowGenerator) {
  98895. shadowGenerator = new babylonjs_1.ShadowGenerator(512, light);
  98896. // TODO blur kernel definition
  98897. }
  98898. _this._extendClassWithConfig(shadowGenerator, lightConfig.shadowConfig || {});
  98899. // add the focues meshes to the shadow list
  98900. var shadownMap = shadowGenerator.getShadowMap();
  98901. if (!shadownMap)
  98902. return;
  98903. var renderList = shadownMap.renderList;
  98904. for (var index = 0; index < focusMeshes.length; index++) {
  98905. if (babylonjs_1.Tags.MatchesQuery(focusMeshes[index], 'castShadow')) {
  98906. renderList && renderList.push(focusMeshes[index]);
  98907. }
  98908. }
  98909. }
  98910. else if (shadowGenerator) {
  98911. shadowGenerator.dispose();
  98912. }
  98913. }
  98914. });
  98915. };
  98916. /**
  98917. * configure all models using the configuration.
  98918. * @param modelConfiguration the configuration to use to reconfigure the models
  98919. */
  98920. AbstractViewer.prototype._configureModel = function (modelConfiguration) {
  98921. this.models.forEach(function (model) {
  98922. model.updateConfiguration(modelConfiguration);
  98923. });
  98924. };
  98925. /**
  98926. * Dispoe the entire viewer including the scene and the engine
  98927. */
  98928. AbstractViewer.prototype.dispose = function () {
  98929. if (this._isDisposed) {
  98930. return;
  98931. }
  98932. window.removeEventListener('resize', this._resize);
  98933. if (this.sceneOptimizer) {
  98934. this.sceneOptimizer.stop();
  98935. this.sceneOptimizer.dispose();
  98936. }
  98937. if (this.environmentHelper) {
  98938. this.environmentHelper.dispose();
  98939. }
  98940. if (this._configurationLoader) {
  98941. this._configurationLoader.dispose();
  98942. }
  98943. //observers
  98944. this.onEngineInitObservable.clear();
  98945. delete this.onEngineInitObservable;
  98946. this.onInitDoneObservable.clear();
  98947. delete this.onInitDoneObservable;
  98948. this.onLoaderInitObservable.clear();
  98949. delete this.onLoaderInitObservable;
  98950. this.onModelLoadedObservable.clear();
  98951. delete this.onModelLoadedObservable;
  98952. this.onModelLoadErrorObservable.clear();
  98953. delete this.onModelLoadErrorObservable;
  98954. this.onModelLoadProgressObservable.clear();
  98955. delete this.onModelLoadProgressObservable;
  98956. this.onSceneInitObservable.clear();
  98957. delete this.onSceneInitObservable;
  98958. if (this.scene.activeCamera) {
  98959. this.scene.activeCamera.detachControl(this.canvas);
  98960. }
  98961. this.modelLoader.dispose();
  98962. this.models.forEach(function (model) {
  98963. model.dispose();
  98964. });
  98965. this.models.length = 0;
  98966. this.scene.dispose();
  98967. this.engine.dispose();
  98968. this.templateManager.dispose();
  98969. viewerManager_1.viewerManager.removeViewer(this);
  98970. this._isDisposed = true;
  98971. };
  98972. /**
  98973. * This function will execute when the HTML templates finished initializing.
  98974. * It should initialize the engine and continue execution.
  98975. *
  98976. * @returns {Promise<AbstractViewer>} The viewer object will be returned after the object was loaded.
  98977. */
  98978. AbstractViewer.prototype._onTemplatesLoaded = function () {
  98979. return Promise.resolve(this);
  98980. };
  98981. /**
  98982. * This will force the creation of an engine and a scene.
  98983. * It will also load a model if preconfigured.
  98984. * But first - it will load the extendible onTemplateLoaded()!
  98985. */
  98986. AbstractViewer.prototype._onTemplateLoaded = function () {
  98987. var _this = this;
  98988. return this._onTemplatesLoaded().then(function () {
  98989. var autoLoadModel = _this._configuration.model;
  98990. return _this._initEngine().then(function (engine) {
  98991. return _this.onEngineInitObservable.notifyObserversWithPromise(engine);
  98992. }).then(function () {
  98993. if (autoLoadModel) {
  98994. return _this.loadModel().catch(function (e) { }).then(function () { return _this.scene; });
  98995. }
  98996. else {
  98997. return _this.scene || _this._initScene();
  98998. }
  98999. }).then(function (scene) {
  99000. return _this.onSceneInitObservable.notifyObserversWithPromise(scene);
  99001. }).then(function () {
  99002. return _this.onInitDoneObservable.notifyObserversWithPromise(_this);
  99003. }).catch(function (e) {
  99004. babylonjs_1.Tools.Warn(e.toString());
  99005. return _this;
  99006. });
  99007. });
  99008. };
  99009. /**
  99010. * Initialize the engine. Retruns a promise in case async calls are needed.
  99011. *
  99012. * @protected
  99013. * @returns {Promise<Engine>}
  99014. * @memberof Viewer
  99015. */
  99016. AbstractViewer.prototype._initEngine = function () {
  99017. // init custom shaders
  99018. this._injectCustomShaders();
  99019. var canvasElement = this.templateManager.getCanvas();
  99020. if (!canvasElement) {
  99021. return Promise.reject('Canvas element not found!');
  99022. }
  99023. var config = this._configuration.engine || {};
  99024. // TDO enable further configuration
  99025. this.engine = new babylonjs_1.Engine(canvasElement, !!config.antialiasing, config.engineOptions);
  99026. // Disable manifest checking
  99027. babylonjs_1.Database.IDBStorageEnabled = false;
  99028. if (!config.disableResize) {
  99029. window.addEventListener('resize', this._resize);
  99030. }
  99031. this.engine.runRenderLoop(this._render);
  99032. if (this._configuration.engine && this._configuration.engine.adaptiveQuality) {
  99033. var scale = Math.max(0.5, 1 / (window.devicePixelRatio || 2));
  99034. this.engine.setHardwareScalingLevel(scale);
  99035. }
  99036. // set hardware limitations for scene initialization
  99037. this._handleHardwareLimitations();
  99038. return Promise.resolve(this.engine);
  99039. };
  99040. /**
  99041. * initialize the scene. Calling thsi function again will dispose the old scene, if exists.
  99042. */
  99043. AbstractViewer.prototype._initScene = function () {
  99044. // if the scen exists, dispose it.
  99045. if (this.scene) {
  99046. this.scene.dispose();
  99047. }
  99048. // create a new scene
  99049. this.scene = new babylonjs_1.Scene(this.engine);
  99050. // make sure there is a default camera and light.
  99051. this.scene.createDefaultLight(true);
  99052. if (this._configuration.scene) {
  99053. this._configureScene(this._configuration.scene);
  99054. // Scene optimizer
  99055. if (this._configuration.optimizer) {
  99056. this._configureOptimizer(this._configuration.optimizer);
  99057. }
  99058. }
  99059. return Promise.resolve(this.scene);
  99060. };
  99061. /**
  99062. * Initialize a model loading. The returns object (a ViewerModel object) will be loaded in the background.
  99063. * The difference between this and loadModel is that loadModel will fulfill the promise when the model finished loading.
  99064. *
  99065. * @param modelConfig model configuration to use when loading the model.
  99066. * @param clearScene should the scene be cleared before loading this model
  99067. * @returns a ViewerModel object that is not yet fully loaded.
  99068. */
  99069. AbstractViewer.prototype.initModel = function (modelConfig, clearScene) {
  99070. var _this = this;
  99071. if (clearScene === void 0) { clearScene = true; }
  99072. if (clearScene) {
  99073. this.models.forEach(function (m) { return m.dispose(); });
  99074. this.models.length = 0;
  99075. }
  99076. var model = this.modelLoader.load(modelConfig);
  99077. this.lastUsedLoader = model.loader;
  99078. model.onLoadErrorObservable.add(function (errorObject) {
  99079. _this.onModelLoadErrorObservable.notifyObserversWithPromise(errorObject);
  99080. });
  99081. model.onLoadProgressObservable.add(function (progressEvent) {
  99082. return _this.onModelLoadProgressObservable.notifyObserversWithPromise(progressEvent);
  99083. });
  99084. this.onLoaderInitObservable.notifyObserversWithPromise(this.lastUsedLoader);
  99085. model.onLoadedObservable.add(function () {
  99086. _this.onModelLoadedObservable.notifyObserversWithPromise(model)
  99087. .then(function () {
  99088. _this._configureLights(_this._configuration.lights);
  99089. if (_this._configuration.camera || !_this.scene.activeCamera) {
  99090. _this._configureCamera(_this._configuration.camera || {}, model);
  99091. }
  99092. return _this._initEnvironment(model);
  99093. }).then(function () {
  99094. _this._isLoading = false;
  99095. return model;
  99096. });
  99097. });
  99098. return model;
  99099. };
  99100. /**
  99101. * load a model using the provided configuration
  99102. *
  99103. * @param modelConfig the model configuration or URL to load.
  99104. * @param clearScene Should the scene be cleared before loading the model
  99105. * @returns a Promise the fulfills when the model finished loading successfully.
  99106. */
  99107. AbstractViewer.prototype.loadModel = function (modelConfig, clearScene) {
  99108. var _this = this;
  99109. if (modelConfig === void 0) { modelConfig = this._configuration.model; }
  99110. if (clearScene === void 0) { clearScene = true; }
  99111. // no model was provided? Do nothing!
  99112. var modelUrl = (typeof modelConfig === 'string') ? modelConfig : modelConfig.url;
  99113. if (!modelUrl) {
  99114. return Promise.reject("no model configuration found");
  99115. }
  99116. if (this._isLoading) {
  99117. // We can decide here whether or not to cancel the lst load, but the developer can do that.
  99118. return Promise.reject("another model is curently being loaded.");
  99119. }
  99120. this._isLoading = true;
  99121. if ((typeof modelConfig === 'string')) {
  99122. if (this._configuration.model && typeof this._configuration.model === 'object') {
  99123. this._configuration.model.url = modelConfig;
  99124. }
  99125. }
  99126. else {
  99127. if (this._configuration.model) {
  99128. deepmerge(this._configuration.model, modelConfig);
  99129. }
  99130. else {
  99131. this._configuration.model = modelConfig;
  99132. }
  99133. }
  99134. return Promise.resolve(this.scene).then(function (scene) {
  99135. if (!scene)
  99136. return _this._initScene();
  99137. return scene;
  99138. }).then(function () {
  99139. return new Promise(function (resolve, reject) {
  99140. // at this point, configuration.model is an object, not a string
  99141. return _this.initModel(modelConfig, clearScene);
  99142. });
  99143. });
  99144. };
  99145. /**
  99146. * initialize the environment for a specific model.
  99147. * Per default it will use the viewer'S configuration.
  99148. * @param model the model to use to configure the environment.
  99149. * @returns a Promise that will resolve when the configuration is done.
  99150. */
  99151. AbstractViewer.prototype._initEnvironment = function (model) {
  99152. this._configureEnvironment(this._configuration.skybox, this._configuration.ground);
  99153. return Promise.resolve(this.scene);
  99154. };
  99155. /**
  99156. * Alters render settings to reduce features based on hardware feature limitations
  99157. * @param enableHDR Allows the viewer to run in HDR mode.
  99158. */
  99159. AbstractViewer.prototype._handleHardwareLimitations = function (enableHDR) {
  99160. if (enableHDR === void 0) { enableHDR = true; }
  99161. //flip rendering settings switches based on hardware support
  99162. var maxVaryingRows = this.engine.getCaps().maxVaryingVectors;
  99163. var maxFragmentSamplers = this.engine.getCaps().maxTexturesImageUnits;
  99164. //shadows are disabled if there's not enough varyings for a single shadow
  99165. if ((maxVaryingRows < 8) || (maxFragmentSamplers < 8)) {
  99166. this._maxShadows = 0;
  99167. }
  99168. else {
  99169. this._maxShadows = 3;
  99170. }
  99171. //can we render to any >= 16-bit targets (required for HDR)
  99172. var caps = this.engine.getCaps();
  99173. var linearHalfFloatTargets = caps.textureHalfFloatRender && caps.textureHalfFloatLinearFiltering;
  99174. var linearFloatTargets = caps.textureFloatRender && caps.textureFloatLinearFiltering;
  99175. this._hdrSupport = enableHDR && !!(linearFloatTargets || linearHalfFloatTargets);
  99176. if (linearHalfFloatTargets) {
  99177. this._defaultHighpTextureType = babylonjs_1.Engine.TEXTURETYPE_HALF_FLOAT;
  99178. this._shadowGeneratorBias = 0.002;
  99179. }
  99180. else if (linearFloatTargets) {
  99181. this._defaultHighpTextureType = babylonjs_1.Engine.TEXTURETYPE_FLOAT;
  99182. this._shadowGeneratorBias = 0.001;
  99183. }
  99184. else {
  99185. this._defaultHighpTextureType = babylonjs_1.Engine.TEXTURETYPE_UNSIGNED_INT;
  99186. this._shadowGeneratorBias = 0.001;
  99187. }
  99188. this._defaultPipelineTextureType = this._hdrSupport ? this._defaultHighpTextureType : babylonjs_1.Engine.TEXTURETYPE_UNSIGNED_INT;
  99189. };
  99190. /**
  99191. * Injects all the spectre shader in the babylon shader store
  99192. */
  99193. AbstractViewer.prototype._injectCustomShaders = function () {
  99194. var customShaders = this._configuration.customShaders;
  99195. // Inject all the spectre shader in the babylon shader store.
  99196. if (!customShaders) {
  99197. return;
  99198. }
  99199. if (customShaders.shaders) {
  99200. Object.keys(customShaders.shaders).forEach(function (key) {
  99201. // typescript considers a callback "unsafe", so... '!'
  99202. babylonjs_1.Effect.ShadersStore[key] = customShaders.shaders[key];
  99203. });
  99204. }
  99205. if (customShaders.includes) {
  99206. Object.keys(customShaders.includes).forEach(function (key) {
  99207. // typescript considers a callback "unsafe", so... '!'
  99208. babylonjs_1.Effect.IncludesShadersStore[key] = customShaders.includes[key];
  99209. });
  99210. }
  99211. };
  99212. /**
  99213. * This will extend an object with configuration values.
  99214. * What it practically does it take the keys from the configuration and set them on the object.
  99215. * I the configuration is a tree, it will traverse into the tree.
  99216. * @param object the object to extend
  99217. * @param config the configuration object that will extend the object
  99218. */
  99219. AbstractViewer.prototype._extendClassWithConfig = function (object, config) {
  99220. var _this = this;
  99221. if (!config)
  99222. return;
  99223. Object.keys(config).forEach(function (key) {
  99224. if (key in object && typeof object[key] !== 'function') {
  99225. // if (typeof object[key] === 'function') return;
  99226. // if it is an object, iterate internally until reaching basic types
  99227. if (typeof object[key] === 'object') {
  99228. _this._extendClassWithConfig(object[key], config[key]);
  99229. }
  99230. else {
  99231. if (config[key] !== undefined) {
  99232. object[key] = config[key];
  99233. }
  99234. }
  99235. }
  99236. });
  99237. };
  99238. AbstractViewer.prototype._setCameraBehavior = function (behaviorConfig, payload) {
  99239. var behavior;
  99240. var type = (typeof behaviorConfig !== "object") ? behaviorConfig : behaviorConfig.type;
  99241. var config = (typeof behaviorConfig === "object") ? behaviorConfig : {};
  99242. // constructing behavior
  99243. switch (type) {
  99244. case 0 /* AUTOROTATION */:
  99245. this.camera.useAutoRotationBehavior = true;
  99246. behavior = this.camera.autoRotationBehavior;
  99247. break;
  99248. case 1 /* BOUNCING */:
  99249. this.camera.useBouncingBehavior = true;
  99250. behavior = this.camera.bouncingBehavior;
  99251. break;
  99252. case 2 /* FRAMING */:
  99253. this.camera.useFramingBehavior = true;
  99254. behavior = this.camera.framingBehavior;
  99255. break;
  99256. default:
  99257. behavior = null;
  99258. break;
  99259. }
  99260. if (behavior) {
  99261. if (typeof behaviorConfig === "object") {
  99262. this._extendClassWithConfig(behavior, behaviorConfig);
  99263. }
  99264. }
  99265. // post attach configuration. Some functionalities require the attached camera.
  99266. switch (type) {
  99267. case 0 /* AUTOROTATION */:
  99268. break;
  99269. case 1 /* BOUNCING */:
  99270. break;
  99271. case 2 /* FRAMING */:
  99272. if (config.zoomOnBoundingInfo) {
  99273. //payload is an array of meshes
  99274. var meshes = payload;
  99275. var bounding = meshes[0].getHierarchyBoundingVectors();
  99276. behavior.zoomOnBoundingInfo(bounding.min, bounding.max);
  99277. }
  99278. break;
  99279. }
  99280. };
  99281. return AbstractViewer;
  99282. }());
  99283. exports.AbstractViewer = AbstractViewer;
  99284. /***/ }),
  99285. /* 7 */
  99286. /***/ (function(module, exports) {
  99287. module.exports = "<viewer></viewer> <loading-screen></loading-screen> <overlay></overlay>";
  99288. /***/ }),
  99289. /* 8 */
  99290. /***/ (function(module, exports) {
  99291. 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}}>";
  99292. /***/ }),
  99293. /* 9 */
  99294. /***/ (function(module, exports) {
  99295. 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=="
  99296. /***/ }),
  99297. /* 10 */
  99298. /***/ (function(module, exports) {
  99299. 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>";
  99300. /***/ }),
  99301. /* 11 */
  99302. /***/ (function(module, exports) {
  99303. 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>";
  99304. /***/ }),
  99305. /* 12 */
  99306. /***/ (function(module, exports) {
  99307. module.exports = "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAADAAAAAwCAQAAAD9CzEMAAAAt0lEQVR42u2WAQbDQBBFQ9IbRtDcrrqK3LBbXrEH6OuHEPMBjPd2xHyZKtdNpcLMg11Pr7y4/YdvwIdd4jtw4BU0Rjrbz9mNzkjzgpU3wNhCvH5M3i1fKzzeK3K8V+R4r8jxTpHjlULhc0WOd8fU6e4I8y3y13tFjHel4GswwAvFSR/ZN6Zv2gjvmzbGhwqPzxUenys83is8Pld4vFac/9sy8/SVNrbgYJl8WGhsvkpoA1+pVK6ZLyLNXm2txsT5AAAAAElFTkSuQmCC"
  99308. /***/ }),
  99309. /* 13 */
  99310. /***/ (function(module, exports) {
  99311. module.exports = "Error loading the model";
  99312. /***/ }),
  99313. /* 14 */
  99314. /***/ (function(module, exports, __webpack_require__) {
  99315. "use strict";
  99316. Object.defineProperty(exports, "__esModule", { value: true });
  99317. var babylonjs_1 = __webpack_require__(0);
  99318. var viewerModel_1 = __webpack_require__(15);
  99319. /**
  99320. * An instance of the class is in charge of loading the model correctly.
  99321. * This class will continously be expended with tasks required from the specific loaders Babylon has.
  99322. *
  99323. * A Model loader is unique per (Abstract)Viewer. It is being generated by the viewer
  99324. */
  99325. var ModelLoader = /** @class */ (function () {
  99326. /**
  99327. * Create a new Model loader
  99328. * @param _viewer the viewer using this model loader
  99329. */
  99330. function ModelLoader(_viewer) {
  99331. this._viewer = _viewer;
  99332. this._disposed = false;
  99333. this._loaders = [];
  99334. this._loadId = 0;
  99335. }
  99336. /**
  99337. * Load a model using predefined configuration
  99338. * @param modelConfiguration the modelConfiguration to use to load the model
  99339. */
  99340. ModelLoader.prototype.load = function (modelConfiguration) {
  99341. var model = new viewerModel_1.ViewerModel(this._viewer, modelConfiguration);
  99342. if (!modelConfiguration.url) {
  99343. model.state = viewerModel_1.ModelState.ERROR;
  99344. babylonjs_1.Tools.Error("No URL provided");
  99345. return model;
  99346. }
  99347. var filename = babylonjs_1.Tools.GetFilename(modelConfiguration.url) || modelConfiguration.url;
  99348. var base = modelConfiguration.root || babylonjs_1.Tools.GetFolderPath(modelConfiguration.url);
  99349. var plugin = modelConfiguration.loader;
  99350. model.loader = babylonjs_1.SceneLoader.ImportMesh(undefined, base, filename, this._viewer.scene, function (meshes, particleSystems, skeletons, animationGroups) {
  99351. meshes.forEach(function (mesh) {
  99352. babylonjs_1.Tags.AddTagsTo(mesh, "viewerMesh");
  99353. });
  99354. model.meshes = meshes;
  99355. model.particleSystems = particleSystems;
  99356. model.skeletons = skeletons;
  99357. for (var _i = 0, animationGroups_1 = animationGroups; _i < animationGroups_1.length; _i++) {
  99358. var animationGroup = animationGroups_1[_i];
  99359. model.addAnimationGroup(animationGroup);
  99360. }
  99361. model.initAnimations();
  99362. model.onLoadedObservable.notifyObserversWithPromise(model);
  99363. }, function (progressEvent) {
  99364. model.onLoadProgressObservable.notifyObserversWithPromise(progressEvent);
  99365. }, function (e, m, exception) {
  99366. model.state = viewerModel_1.ModelState.ERROR;
  99367. babylonjs_1.Tools.Error("Load Error: There was an error loading the model. " + m);
  99368. model.onLoadErrorObservable.notifyObserversWithPromise({ message: m, exception: exception });
  99369. }, plugin);
  99370. if (model.loader.name === "gltf") {
  99371. var gltfLoader = model.loader;
  99372. gltfLoader.animationStartMode = BABYLON.GLTFLoaderAnimationStartMode.NONE;
  99373. }
  99374. model.loadId = this._loadId++;
  99375. this._loaders.push(model.loader);
  99376. return model;
  99377. };
  99378. ModelLoader.prototype.cancelLoad = function (model) {
  99379. var loader = model.loader || this._loaders[model.loadId];
  99380. // ATM only available in the GLTF Loader
  99381. if (loader && loader.name === "gltf") {
  99382. var gltfLoader = loader;
  99383. gltfLoader.dispose();
  99384. model.state = viewerModel_1.ModelState.CANCELED;
  99385. }
  99386. else {
  99387. babylonjs_1.Tools.Warn("This type of loader cannot cancel the request");
  99388. }
  99389. };
  99390. /**
  99391. * dispose the model loader.
  99392. * If loaders are registered and are in the middle of loading, they will be disposed and the request(s) will be cancelled.
  99393. */
  99394. ModelLoader.prototype.dispose = function () {
  99395. this._loaders.forEach(function (loader) {
  99396. if (loader.name === "gltf") {
  99397. loader.dispose();
  99398. }
  99399. });
  99400. this._loaders.length = 0;
  99401. this._disposed = true;
  99402. };
  99403. return ModelLoader;
  99404. }());
  99405. exports.ModelLoader = ModelLoader;
  99406. /***/ }),
  99407. /* 15 */
  99408. /***/ (function(module, exports, __webpack_require__) {
  99409. "use strict";
  99410. Object.defineProperty(exports, "__esModule", { value: true });
  99411. var babylonjs_1 = __webpack_require__(0);
  99412. var modelAnimation_1 = __webpack_require__(16);
  99413. var deepmerge = __webpack_require__(2);
  99414. var ModelState;
  99415. (function (ModelState) {
  99416. ModelState[ModelState["INIT"] = 0] = "INIT";
  99417. ModelState[ModelState["LOADING"] = 1] = "LOADING";
  99418. ModelState[ModelState["LOADED"] = 2] = "LOADED";
  99419. ModelState[ModelState["CANCELED"] = 3] = "CANCELED";
  99420. ModelState[ModelState["ERROR"] = 4] = "ERROR";
  99421. })(ModelState = exports.ModelState || (exports.ModelState = {}));
  99422. /**
  99423. * The viewer model is a container for all assets representing a sngle loaded model.
  99424. */
  99425. var ViewerModel = /** @class */ (function () {
  99426. function ViewerModel(_viewer, modelConfiguration) {
  99427. this._viewer = _viewer;
  99428. /**
  99429. * the list of meshes that are a part of this model
  99430. */
  99431. this.meshes = [];
  99432. /**
  99433. * ParticleSystems connected to this model
  99434. */
  99435. this.particleSystems = [];
  99436. /**
  99437. * Skeletons defined in this model
  99438. */
  99439. this.skeletons = [];
  99440. this.onLoadedObservable = new babylonjs_1.Observable();
  99441. this.onLoadErrorObservable = new babylonjs_1.Observable();
  99442. this.onLoadProgressObservable = new babylonjs_1.Observable();
  99443. this.onAfterConfigure = new babylonjs_1.Observable();
  99444. this.state = ModelState.INIT;
  99445. this._animations = [];
  99446. //create a copy of the configuration to make sure it doesn't change even after it is changed in the viewer
  99447. this._modelConfiguration = deepmerge({}, modelConfiguration);
  99448. this._viewer.models.push(this);
  99449. }
  99450. Object.defineProperty(ViewerModel.prototype, "configuration", {
  99451. /**
  99452. * Get the model's configuration
  99453. */
  99454. get: function () {
  99455. return this._modelConfiguration;
  99456. },
  99457. /**
  99458. * (Re-)set the model's entire configuration
  99459. * @param newConfiguration the new configuration to replace the new one
  99460. */
  99461. set: function (newConfiguration) {
  99462. this._modelConfiguration = newConfiguration;
  99463. this._configureModel();
  99464. },
  99465. enumerable: true,
  99466. configurable: true
  99467. });
  99468. /**
  99469. * Update the current configuration with new values.
  99470. * Configuration will not be overwritten, but merged with the new configuration.
  99471. * Priority is to the new configuration
  99472. * @param newConfiguration the configuration to be merged into the current configuration;
  99473. */
  99474. ViewerModel.prototype.updateConfiguration = function (newConfiguration) {
  99475. this._modelConfiguration = deepmerge(this._modelConfiguration, newConfiguration);
  99476. this._configureModel();
  99477. };
  99478. ViewerModel.prototype.initAnimations = function () {
  99479. var _this = this;
  99480. this._animations.forEach(function (a) {
  99481. a.dispose();
  99482. });
  99483. this._animations.length = 0;
  99484. // check if this is not a gltf loader and init the animations
  99485. if (this.loader.name !== 'gltf') {
  99486. this.skeletons.forEach(function (skeleton, idx) {
  99487. var ag = new babylonjs_1.AnimationGroup("animation-" + idx, _this._viewer.scene);
  99488. skeleton.getAnimatables().forEach(function (a) {
  99489. if (a.animations[0]) {
  99490. ag.addTargetedAnimation(a.animations[0], a);
  99491. }
  99492. });
  99493. _this.addAnimationGroup(ag);
  99494. });
  99495. }
  99496. if (!this._modelConfiguration)
  99497. return;
  99498. if (this._modelConfiguration.animation) {
  99499. if (this._modelConfiguration.animation.playOnce) {
  99500. this._animations.forEach(function (a) {
  99501. a.playMode = modelAnimation_1.AnimationPlayMode.ONCE;
  99502. });
  99503. }
  99504. if (this._modelConfiguration.animation.autoStart && this._animations.length) {
  99505. var animationName = this._modelConfiguration.animation.autoStart === true ?
  99506. this._animations[0].name : this._modelConfiguration.animation.autoStart;
  99507. this.playAnimation(animationName);
  99508. }
  99509. }
  99510. };
  99511. /**
  99512. * Add a new animation group to this model.
  99513. * @param animationGroup the new animation group to be added
  99514. */
  99515. ViewerModel.prototype.addAnimationGroup = function (animationGroup) {
  99516. this._animations.push(new modelAnimation_1.GroupModelAnimation(animationGroup));
  99517. };
  99518. /**
  99519. * Get the ModelAnimation array
  99520. */
  99521. ViewerModel.prototype.getAnimations = function () {
  99522. return this._animations;
  99523. };
  99524. /**
  99525. * Get the animations' names. Using the names you can play a specific animation.
  99526. */
  99527. ViewerModel.prototype.getAnimationNames = function () {
  99528. return this._animations.map(function (a) { return a.name; });
  99529. };
  99530. /**
  99531. * Get an animation by the provided name. Used mainly when playing n animation.
  99532. * @param name the name of the animation to find
  99533. */
  99534. ViewerModel.prototype._getAnimationByName = function (name) {
  99535. // can't use .find, noe available on IE
  99536. var filtered = this._animations.filter(function (a) { return a.name === name; });
  99537. // what the next line means - if two animations have the same name, they will not be returned!
  99538. if (filtered.length === 1) {
  99539. return filtered[0];
  99540. }
  99541. else {
  99542. return null;
  99543. }
  99544. };
  99545. /**
  99546. * Choose an initialized animation using its name and start playing it
  99547. * @param name the name of the animation to play
  99548. * @returns The model aniamtion to be played.
  99549. */
  99550. ViewerModel.prototype.playAnimation = function (name) {
  99551. var animation = this._getAnimationByName(name);
  99552. if (animation) {
  99553. if (this.currentAnimation) {
  99554. this.currentAnimation.stop();
  99555. }
  99556. this.currentAnimation = animation;
  99557. animation.start();
  99558. return animation;
  99559. }
  99560. else {
  99561. throw new Error("animation not found - " + name);
  99562. }
  99563. };
  99564. ViewerModel.prototype._configureModel = function () {
  99565. var meshesWithNoParent = this.meshes.filter(function (m) { return !m.parent; });
  99566. var updateMeshesWithNoParent = function (variable, value, param) {
  99567. meshesWithNoParent.forEach(function (mesh) {
  99568. if (param) {
  99569. mesh[variable][param] = value;
  99570. }
  99571. else {
  99572. mesh[variable] = value;
  99573. }
  99574. });
  99575. };
  99576. var updateXYZ = function (variable, configValues) {
  99577. if (configValues.x !== undefined) {
  99578. updateMeshesWithNoParent(variable, configValues.x, 'x');
  99579. }
  99580. if (configValues.y !== undefined) {
  99581. updateMeshesWithNoParent(variable, configValues.y, 'y');
  99582. }
  99583. if (configValues.z !== undefined) {
  99584. updateMeshesWithNoParent(variable, configValues.z, 'z');
  99585. }
  99586. if (configValues.w !== undefined) {
  99587. updateMeshesWithNoParent(variable, configValues.w, 'w');
  99588. }
  99589. };
  99590. // position?
  99591. if (this._modelConfiguration.position) {
  99592. updateXYZ('position', this._modelConfiguration.position);
  99593. }
  99594. if (this._modelConfiguration.rotation) {
  99595. //quaternion?
  99596. if (this._modelConfiguration.rotation.w) {
  99597. meshesWithNoParent.forEach(function (mesh) {
  99598. if (!mesh.rotationQuaternion) {
  99599. mesh.rotationQuaternion = new babylonjs_1.Quaternion();
  99600. }
  99601. });
  99602. updateXYZ('rotationQuaternion', this._modelConfiguration.rotation);
  99603. }
  99604. else {
  99605. updateXYZ('rotation', this._modelConfiguration.rotation);
  99606. }
  99607. }
  99608. if (this._modelConfiguration.scaling) {
  99609. updateXYZ('scaling', this._modelConfiguration.scaling);
  99610. }
  99611. if (this._modelConfiguration.castShadow) {
  99612. this.meshes.forEach(function (mesh) {
  99613. babylonjs_1.Tags.AddTagsTo(mesh, 'castShadow');
  99614. });
  99615. }
  99616. if (this._modelConfiguration.normalize) {
  99617. var center = false;
  99618. var unitSize = false;
  99619. var parentIndex = void 0;
  99620. if (this._modelConfiguration.normalize === true) {
  99621. center = true;
  99622. unitSize = true;
  99623. parentIndex = 0;
  99624. }
  99625. else {
  99626. center = !!this._modelConfiguration.normalize.center;
  99627. unitSize = !!this._modelConfiguration.normalize.unitSize;
  99628. parentIndex = this._modelConfiguration.normalize.parentIndex;
  99629. }
  99630. var meshesToNormalize = [];
  99631. if (parentIndex !== undefined) {
  99632. meshesToNormalize.push(this.meshes[parentIndex]);
  99633. }
  99634. else {
  99635. meshesToNormalize = meshesWithNoParent;
  99636. }
  99637. if (unitSize) {
  99638. meshesToNormalize.forEach(function (mesh) {
  99639. mesh.normalizeToUnitCube(true);
  99640. mesh.computeWorldMatrix(true);
  99641. });
  99642. }
  99643. if (center) {
  99644. meshesToNormalize.forEach(function (mesh) {
  99645. var boundingInfo = mesh.getHierarchyBoundingVectors(true);
  99646. var sizeVec = boundingInfo.max.subtract(boundingInfo.min);
  99647. var halfSizeVec = sizeVec.scale(0.5);
  99648. var center = boundingInfo.min.add(halfSizeVec);
  99649. mesh.position = center.scale(-1);
  99650. // Set on ground.
  99651. mesh.position.y += halfSizeVec.y;
  99652. // Recompute Info.
  99653. mesh.computeWorldMatrix(true);
  99654. });
  99655. }
  99656. }
  99657. this.onAfterConfigure.notifyObservers(this);
  99658. };
  99659. /**
  99660. * Dispose this model, including all of its associated assets.
  99661. */
  99662. ViewerModel.prototype.dispose = function () {
  99663. this.onAfterConfigure.clear();
  99664. this.onLoadedObservable.clear();
  99665. this.onLoadErrorObservable.clear();
  99666. this.onLoadProgressObservable.clear();
  99667. if (this.loader && this.loader.name === "gltf") {
  99668. this.loader.dispose();
  99669. }
  99670. this.particleSystems.forEach(function (ps) { return ps.dispose(); });
  99671. this.particleSystems.length = 0;
  99672. this.skeletons.forEach(function (s) { return s.dispose(); });
  99673. this.skeletons.length = 0;
  99674. this._animations.forEach(function (ag) { return ag.dispose(); });
  99675. this._animations.length = 0;
  99676. this.meshes.forEach(function (m) { return m.dispose(); });
  99677. this.meshes.length = 0;
  99678. this._viewer.models.splice(this._viewer.models.indexOf(this), 1);
  99679. };
  99680. return ViewerModel;
  99681. }());
  99682. exports.ViewerModel = ViewerModel;
  99683. /***/ }),
  99684. /* 16 */
  99685. /***/ (function(module, exports, __webpack_require__) {
  99686. "use strict";
  99687. Object.defineProperty(exports, "__esModule", { value: true });
  99688. /**
  99689. * Animation play mode enum - is the animation looping or playing once
  99690. */
  99691. var AnimationPlayMode;
  99692. (function (AnimationPlayMode) {
  99693. AnimationPlayMode[AnimationPlayMode["ONCE"] = 0] = "ONCE";
  99694. AnimationPlayMode[AnimationPlayMode["LOOP"] = 1] = "LOOP";
  99695. })(AnimationPlayMode = exports.AnimationPlayMode || (exports.AnimationPlayMode = {}));
  99696. /**
  99697. * An enum representing the current state of an animation object
  99698. */
  99699. var AnimationState;
  99700. (function (AnimationState) {
  99701. AnimationState[AnimationState["INIT"] = 0] = "INIT";
  99702. AnimationState[AnimationState["PLAYING"] = 1] = "PLAYING";
  99703. AnimationState[AnimationState["PAUSED"] = 2] = "PAUSED";
  99704. AnimationState[AnimationState["STOPPED"] = 3] = "STOPPED";
  99705. AnimationState[AnimationState["ENDED"] = 4] = "ENDED";
  99706. })(AnimationState = exports.AnimationState || (exports.AnimationState = {}));
  99707. /**
  99708. * The GroupModelAnimation is an implementation of the IModelAnimation interface using BABYLON's
  99709. * native GroupAnimation class.
  99710. */
  99711. var GroupModelAnimation = /** @class */ (function () {
  99712. /**
  99713. * Create a new GroupModelAnimation object using an AnimationGroup object
  99714. * @param _animationGroup The aniamtion group to base the class on
  99715. */
  99716. function GroupModelAnimation(_animationGroup) {
  99717. var _this = this;
  99718. this._animationGroup = _animationGroup;
  99719. this._state = AnimationState.INIT;
  99720. this._playMode = AnimationPlayMode.LOOP;
  99721. this._animationGroup.onAnimationEndObservable.add(function () {
  99722. _this.stop();
  99723. _this._state = AnimationState.ENDED;
  99724. });
  99725. }
  99726. Object.defineProperty(GroupModelAnimation.prototype, "name", {
  99727. /**
  99728. * Get the animation's name
  99729. */
  99730. get: function () {
  99731. return this._animationGroup.name;
  99732. },
  99733. enumerable: true,
  99734. configurable: true
  99735. });
  99736. Object.defineProperty(GroupModelAnimation.prototype, "state", {
  99737. /**
  99738. * Get the current animation's state
  99739. */
  99740. get: function () {
  99741. return this._state;
  99742. },
  99743. enumerable: true,
  99744. configurable: true
  99745. });
  99746. Object.defineProperty(GroupModelAnimation.prototype, "speedRatio", {
  99747. /**
  99748. * Gets the speed ratio to use for all animations
  99749. */
  99750. get: function () {
  99751. return this._animationGroup.speedRatio;
  99752. },
  99753. /**
  99754. * Sets the speed ratio to use for all animations
  99755. */
  99756. set: function (value) {
  99757. this._animationGroup.speedRatio = value;
  99758. },
  99759. enumerable: true,
  99760. configurable: true
  99761. });
  99762. Object.defineProperty(GroupModelAnimation.prototype, "frames", {
  99763. /**
  99764. * Get the max numbers of frame available in the animation group
  99765. *
  99766. * In correlation to an arry, this would be ".length"
  99767. */
  99768. get: function () {
  99769. var animationFrames = this._animationGroup.targetedAnimations.map(function (ta) {
  99770. var keys = ta.animation.getKeys();
  99771. return keys[keys.length - 1].frame;
  99772. });
  99773. return Math.max.apply(null, animationFrames);
  99774. },
  99775. enumerable: true,
  99776. configurable: true
  99777. });
  99778. Object.defineProperty(GroupModelAnimation.prototype, "currentFrame", {
  99779. /**
  99780. * Get the current frame playing right now.
  99781. * This can be used to poll the frame currently playing (and, for exmaple, display a progress bar with the data)
  99782. *
  99783. * In correlation to an array, this would be the current index
  99784. */
  99785. get: function () {
  99786. // get the first currentFrame found
  99787. for (var i = 0; i < this._animationGroup.animatables.length; ++i) {
  99788. var animatable = this._animationGroup.animatables[i];
  99789. var animations = animatable.getAnimations();
  99790. if (!animations || !animations.length) {
  99791. continue;
  99792. }
  99793. for (var idx = 0; idx < animations.length; ++idx) {
  99794. if (animations[idx].currentFrame) {
  99795. return animations[idx].currentFrame;
  99796. }
  99797. }
  99798. }
  99799. return 0;
  99800. },
  99801. enumerable: true,
  99802. configurable: true
  99803. });
  99804. Object.defineProperty(GroupModelAnimation.prototype, "fps", {
  99805. /**
  99806. * Get the FPS value of this animation
  99807. */
  99808. get: function () {
  99809. // get the first currentFrame found
  99810. for (var i = 0; i < this._animationGroup.animatables.length; ++i) {
  99811. var animatable = this._animationGroup.animatables[i];
  99812. var animations = animatable.getAnimations();
  99813. if (!animations || !animations.length) {
  99814. continue;
  99815. }
  99816. for (var idx = 0; idx < animations.length; ++idx) {
  99817. if (animations[idx].animation && animations[idx].animation.framePerSecond) {
  99818. return animations[idx].animation.framePerSecond;
  99819. }
  99820. }
  99821. }
  99822. return 0;
  99823. },
  99824. enumerable: true,
  99825. configurable: true
  99826. });
  99827. Object.defineProperty(GroupModelAnimation.prototype, "playMode", {
  99828. /**
  99829. * What is the animation'S play mode (looping or played once)
  99830. */
  99831. get: function () {
  99832. return this._playMode;
  99833. },
  99834. /**
  99835. * Set the play mode.
  99836. * If the animation is played, it will continue playing at least once more, depending on the new play mode set.
  99837. * If the animation is not set, the will be initialized and will wait for the user to start playing it.
  99838. */
  99839. set: function (value) {
  99840. if (value === this._playMode) {
  99841. return;
  99842. }
  99843. this._playMode = value;
  99844. if (this.state === AnimationState.PLAYING) {
  99845. this._animationGroup.play(this._playMode === AnimationPlayMode.LOOP);
  99846. }
  99847. else {
  99848. this._animationGroup.reset();
  99849. this._state = AnimationState.INIT;
  99850. }
  99851. },
  99852. enumerable: true,
  99853. configurable: true
  99854. });
  99855. /**
  99856. * Reset the animation group
  99857. */
  99858. GroupModelAnimation.prototype.reset = function () {
  99859. this._animationGroup.reset();
  99860. };
  99861. /**
  99862. * Restart the animation group
  99863. */
  99864. GroupModelAnimation.prototype.restart = function () {
  99865. this._animationGroup.restart();
  99866. };
  99867. /**
  99868. *
  99869. * @param frameNumber Go to a specific frame in the animation
  99870. */
  99871. GroupModelAnimation.prototype.goToFrame = function (frameNumber) {
  99872. // this._animationGroup.goToFrame(frameNumber);
  99873. this._animationGroup['_animatables'].forEach(function (a) {
  99874. a.goToFrame(frameNumber);
  99875. });
  99876. };
  99877. /**
  99878. * Start playing the animation.
  99879. */
  99880. GroupModelAnimation.prototype.start = function () {
  99881. this._animationGroup.start(this.playMode === AnimationPlayMode.LOOP, this.speedRatio);
  99882. if (this._animationGroup.isStarted) {
  99883. this._state = AnimationState.PLAYING;
  99884. }
  99885. };
  99886. /**
  99887. * Pause the animation
  99888. */
  99889. GroupModelAnimation.prototype.pause = function () {
  99890. this._animationGroup.pause();
  99891. this._state = AnimationState.PAUSED;
  99892. };
  99893. /**
  99894. * Stop the animation.
  99895. * This will fail silently if the animation group is already stopped.
  99896. */
  99897. GroupModelAnimation.prototype.stop = function () {
  99898. this._animationGroup.stop();
  99899. if (!this._animationGroup.isStarted) {
  99900. this._state = AnimationState.STOPPED;
  99901. }
  99902. };
  99903. /**
  99904. * Dispose this animation object.
  99905. */
  99906. GroupModelAnimation.prototype.dispose = function () {
  99907. this._animationGroup.dispose();
  99908. };
  99909. return GroupModelAnimation;
  99910. }());
  99911. exports.GroupModelAnimation = GroupModelAnimation;
  99912. /***/ }),
  99913. /* 17 */
  99914. /***/ (function(module, exports, __webpack_require__) {
  99915. module.exports = __webpack_require__(18);
  99916. /***/ }),
  99917. /* 18 */
  99918. /***/ (function(module, exports, __webpack_require__) {
  99919. "use strict";
  99920. Object.defineProperty(exports, "__esModule", { value: true });
  99921. /// <reference path="../../dist/babylon.glTF2Interface.d.ts"/>
  99922. var mappers_1 = __webpack_require__(1);
  99923. exports.mapperManager = mappers_1.mapperManager;
  99924. var viewerManager_1 = __webpack_require__(4);
  99925. exports.viewerManager = viewerManager_1.viewerManager;
  99926. var defaultViewer_1 = __webpack_require__(5);
  99927. exports.DefaultViewer = defaultViewer_1.DefaultViewer;
  99928. var viewer_1 = __webpack_require__(6);
  99929. exports.AbstractViewer = viewer_1.AbstractViewer;
  99930. var modelLoader_1 = __webpack_require__(14);
  99931. exports.ModelLoader = modelLoader_1.ModelLoader;
  99932. var viewerModel_1 = __webpack_require__(15);
  99933. exports.ViewerModel = viewerModel_1.ViewerModel;
  99934. exports.ModelState = viewerModel_1.ModelState;
  99935. var modelAnimation_1 = __webpack_require__(16);
  99936. exports.AnimationPlayMode = modelAnimation_1.AnimationPlayMode;
  99937. exports.AnimationState = modelAnimation_1.AnimationState;
  99938. /**
  99939. * BabylonJS Viewer
  99940. *
  99941. * An HTML-Based viewer for 3D models, based on BabylonJS and its extensions.
  99942. */
  99943. var babylonjs_1 = __webpack_require__(0);
  99944. // load needed modules.
  99945. __webpack_require__(34);
  99946. __webpack_require__(35);
  99947. var initializer_1 = __webpack_require__(36);
  99948. exports.InitTags = initializer_1.InitTags;
  99949. // promise polyfill, if needed!
  99950. babylonjs_1.PromisePolyfill.Apply();
  99951. exports.disableInit = false;
  99952. document.addEventListener("DOMContentLoaded", init);
  99953. function init(event) {
  99954. document.removeEventListener("DOMContentLoaded", init);
  99955. if (exports.disableInit)
  99956. return;
  99957. initializer_1.InitTags();
  99958. }
  99959. /**
  99960. * Dispose all viewers currently registered
  99961. */
  99962. function disposeAll() {
  99963. viewerManager_1.viewerManager.dispose();
  99964. mappers_1.mapperManager.dispose();
  99965. }
  99966. exports.disposeAll = disposeAll;
  99967. /***/ }),
  99968. /* 19 */
  99969. /***/ (function(module, exports) {
  99970. var g;
  99971. // This works in non-strict mode
  99972. g = (function() {
  99973. return this;
  99974. })();
  99975. try {
  99976. // This works if eval is allowed (see CSP)
  99977. g = g || Function("return this")() || (1,eval)("this");
  99978. } catch(e) {
  99979. // This works if the window reference is available
  99980. if(typeof window === "object")
  99981. g = window;
  99982. }
  99983. // g can still be undefined, but nothing to do about it...
  99984. // We return undefined, instead of nothing here, so it's
  99985. // easier to handle this case. if(!global) { ...}
  99986. module.exports = g;
  99987. /***/ }),
  99988. /* 20 */
  99989. /***/ (function(module, exports) {
  99990. if(typeof CANNON === 'undefined') {var e = new Error("Cannot find module \"CANNON\""); e.code = 'MODULE_NOT_FOUND'; throw e;}
  99991. module.exports = CANNON;
  99992. /***/ }),
  99993. /* 21 */
  99994. /***/ (function(module, exports) {
  99995. if(typeof OIMO === 'undefined') {var e = new Error("Cannot find module \"OIMO\""); e.code = 'MODULE_NOT_FOUND'; throw e;}
  99996. module.exports = OIMO;
  99997. /***/ }),
  99998. /* 22 */
  99999. /***/ (function(module, exports) {
  100000. if(typeof earcut === 'undefined') {var e = new Error("Cannot find module \"earcut\""); e.code = 'MODULE_NOT_FOUND'; throw e;}
  100001. module.exports = earcut;
  100002. /***/ }),
  100003. /* 23 */
  100004. /***/ (function(module, exports, __webpack_require__) {
  100005. "use strict";
  100006. Object.defineProperty(exports, "__esModule", { value: true });
  100007. var babylonjs_1 = __webpack_require__(0);
  100008. var helper_1 = __webpack_require__(3);
  100009. /**
  100010. * The template manager, a member of the viewer class, will manage the viewer's templates and generate the HTML.
  100011. * The template manager managers a single viewer and can be seen as the collection of all sub-templates of the viewer.
  100012. */
  100013. var TemplateManager = /** @class */ (function () {
  100014. function TemplateManager(containerElement) {
  100015. this.containerElement = containerElement;
  100016. this.templates = {};
  100017. this.onTemplateInit = new babylonjs_1.Observable();
  100018. this.onTemplateLoaded = new babylonjs_1.Observable();
  100019. this.onTemplateStateChange = new babylonjs_1.Observable();
  100020. this.onAllLoaded = new babylonjs_1.Observable();
  100021. this.onEventTriggered = new babylonjs_1.Observable();
  100022. this.eventManager = new eventManager_1.EventManager(this);
  100023. }
  100024. /**
  100025. * Initialize the template(s) for the viewer. Called bay the Viewer class
  100026. * @param templates the templates to be used to initialize the main template
  100027. */
  100028. TemplateManager.prototype.initTemplate = function (templates) {
  100029. var _this = this;
  100030. var internalInit = function (dependencyMap, name, parentTemplate) {
  100031. //init template
  100032. var template = _this.templates[name];
  100033. var childrenTemplates = Object.keys(dependencyMap).map(function (childName) {
  100034. return internalInit(dependencyMap[childName], childName, template);
  100035. });
  100036. // register the observers
  100037. //template.onLoaded.add(() => {
  100038. var addToParent = function () {
  100039. var containingElement = parentTemplate && parentTemplate.parent.querySelector(helper_1.camelToKebab(name)) || _this.containerElement;
  100040. template.appendTo(containingElement);
  100041. _this._checkLoadedState();
  100042. };
  100043. if (parentTemplate && !parentTemplate.parent) {
  100044. parentTemplate.onAppended.add(function () {
  100045. addToParent();
  100046. });
  100047. }
  100048. else {
  100049. addToParent();
  100050. }
  100051. //});
  100052. return template;
  100053. };
  100054. //build the html tree
  100055. return this._buildHTMLTree(templates).then(function (htmlTree) {
  100056. if (_this.templates['main']) {
  100057. internalInit(htmlTree, 'main');
  100058. }
  100059. else {
  100060. _this._checkLoadedState();
  100061. }
  100062. return;
  100063. });
  100064. };
  100065. /**
  100066. *
  100067. * This function will create a simple map with child-dependencies of the template html tree.
  100068. * It will compile each template, check if its children exist in the configuration and will add them if they do.
  100069. * It is expected that the main template will be called main!
  100070. *
  100071. * @param templates
  100072. */
  100073. TemplateManager.prototype._buildHTMLTree = function (templates) {
  100074. var _this = this;
  100075. var promises = Object.keys(templates).map(function (name) {
  100076. // if the template was overridden
  100077. if (!templates[name])
  100078. return Promise.resolve(false);
  100079. // else - we have a template, let's do our job!
  100080. var template = new Template(name, templates[name]);
  100081. template.onLoaded.add(function () {
  100082. _this.onTemplateLoaded.notifyObservers(template);
  100083. });
  100084. template.onStateChange.add(function () {
  100085. _this.onTemplateStateChange.notifyObservers(template);
  100086. });
  100087. _this.onTemplateInit.notifyObservers(template);
  100088. // make sure the global onEventTriggered is called as well
  100089. template.onEventTriggered.add(function (eventData) { return _this.onEventTriggered.notifyObservers(eventData); });
  100090. _this.templates[name] = template;
  100091. return template.initPromise;
  100092. });
  100093. return Promise.all(promises).then(function () {
  100094. var templateStructure = {};
  100095. // now iterate through all templates and check for children:
  100096. var buildTree = function (parentObject, name) {
  100097. _this.templates[name].isInHtmlTree = true;
  100098. var childNodes = _this.templates[name].getChildElements().filter(function (n) { return !!_this.templates[n]; });
  100099. childNodes.forEach(function (element) {
  100100. parentObject[element] = {};
  100101. buildTree(parentObject[element], element);
  100102. });
  100103. };
  100104. if (_this.templates['main']) {
  100105. buildTree(templateStructure, "main");
  100106. }
  100107. return templateStructure;
  100108. });
  100109. };
  100110. /**
  100111. * Get the canvas in the template tree.
  100112. * There must be one and only one canvas inthe template.
  100113. */
  100114. TemplateManager.prototype.getCanvas = function () {
  100115. return this.containerElement.querySelector('canvas');
  100116. };
  100117. /**
  100118. * Get a specific template from the template tree
  100119. * @param name the name of the template to load
  100120. */
  100121. TemplateManager.prototype.getTemplate = function (name) {
  100122. return this.templates[name];
  100123. };
  100124. TemplateManager.prototype._checkLoadedState = function () {
  100125. var _this = this;
  100126. var done = Object.keys(this.templates).length === 0 || Object.keys(this.templates).every(function (key) {
  100127. return (_this.templates[key].isLoaded && !!_this.templates[key].parent) || !_this.templates[key].isInHtmlTree;
  100128. });
  100129. if (done) {
  100130. this.onAllLoaded.notifyObservers(this);
  100131. }
  100132. };
  100133. /**
  100134. * Dispose the template manager
  100135. */
  100136. TemplateManager.prototype.dispose = function () {
  100137. var _this = this;
  100138. // dispose all templates
  100139. Object.keys(this.templates).forEach(function (template) {
  100140. _this.templates[template].dispose();
  100141. });
  100142. this.templates = {};
  100143. this.eventManager.dispose();
  100144. this.onTemplateInit.clear();
  100145. this.onAllLoaded.clear();
  100146. this.onEventTriggered.clear();
  100147. this.onTemplateLoaded.clear();
  100148. this.onTemplateStateChange.clear();
  100149. };
  100150. return TemplateManager;
  100151. }());
  100152. exports.TemplateManager = TemplateManager;
  100153. var Handlebars = __webpack_require__(24);
  100154. var eventManager_1 = __webpack_require__(25);
  100155. // register a new helper. modified https://stackoverflow.com/questions/9838925/is-there-any-method-to-iterate-a-map-with-handlebars-js
  100156. Handlebars.registerHelper('eachInMap', function (map, block) {
  100157. var out = '';
  100158. Object.keys(map).map(function (prop) {
  100159. var data = map[prop];
  100160. if (typeof data === 'object') {
  100161. data.id = data.id || prop;
  100162. out += block.fn(data);
  100163. }
  100164. else {
  100165. out += block.fn({ id: prop, value: data });
  100166. }
  100167. });
  100168. return out;
  100169. });
  100170. /**
  100171. * This class represents a single template in the viewer's template tree.
  100172. * An example for a template is a single canvas, an overlay (containing sub-templates) or the navigation bar.
  100173. * A template is injected using the template manager in the correct position.
  100174. * The template is rendered using Handlebars and can use Handlebars' features (such as parameter injection)
  100175. *
  100176. * For further information please refer to the documentation page, https://doc.babylonjs.com
  100177. */
  100178. var Template = /** @class */ (function () {
  100179. function Template(name, _configuration) {
  100180. var _this = this;
  100181. this.name = name;
  100182. this._configuration = _configuration;
  100183. this.onLoaded = new babylonjs_1.Observable();
  100184. this.onAppended = new babylonjs_1.Observable();
  100185. this.onStateChange = new babylonjs_1.Observable();
  100186. this.onEventTriggered = new babylonjs_1.Observable();
  100187. this.loadRequests = [];
  100188. this.isLoaded = false;
  100189. this.isShown = false;
  100190. this.isInHtmlTree = false;
  100191. var htmlContentPromise = this._getTemplateAsHtml(_configuration);
  100192. this.initPromise = htmlContentPromise.then(function (htmlTemplate) {
  100193. if (htmlTemplate) {
  100194. _this._htmlTemplate = htmlTemplate;
  100195. var compiledTemplate = Handlebars.compile(htmlTemplate);
  100196. var config = _this._configuration.params || {};
  100197. var rawHtml = compiledTemplate(config);
  100198. _this._fragment = document.createRange().createContextualFragment(rawHtml);
  100199. _this.isLoaded = true;
  100200. _this.isShown = true;
  100201. _this.onLoaded.notifyObservers(_this);
  100202. }
  100203. return _this;
  100204. });
  100205. }
  100206. /**
  100207. * Some templates have parameters (like background color for example).
  100208. * The parameters are provided to Handlebars which in turn generates the template.
  100209. * This function will update the template with the new parameters
  100210. *
  100211. * @param params the new template parameters
  100212. */
  100213. Template.prototype.updateParams = function (params) {
  100214. this._configuration.params = params;
  100215. // update the template
  100216. if (this.isLoaded) {
  100217. this.dispose();
  100218. }
  100219. var compiledTemplate = Handlebars.compile(this._htmlTemplate);
  100220. var config = this._configuration.params || {};
  100221. var rawHtml = compiledTemplate(config);
  100222. this._fragment = document.createRange().createContextualFragment(rawHtml);
  100223. if (this.parent) {
  100224. this.appendTo(this.parent, true);
  100225. }
  100226. };
  100227. Object.defineProperty(Template.prototype, "configuration", {
  100228. /**
  100229. * Get the template'S configuration
  100230. */
  100231. get: function () {
  100232. return this._configuration;
  100233. },
  100234. enumerable: true,
  100235. configurable: true
  100236. });
  100237. /**
  100238. * A template can be a parent element for other templates or HTML elements.
  100239. * This function will deliver all child HTML elements of this template.
  100240. */
  100241. Template.prototype.getChildElements = function () {
  100242. var childrenArray = [];
  100243. //Edge and IE don't support frage,ent.children
  100244. var children = this._fragment.children;
  100245. if (!children) {
  100246. // casting to HTMLCollection, as both NodeListOf and HTMLCollection have 'item()' and 'length'.
  100247. children = this._fragment.querySelectorAll('*');
  100248. }
  100249. for (var i = 0; i < children.length; ++i) {
  100250. childrenArray.push(helper_1.kebabToCamel(children.item(i).nodeName.toLowerCase()));
  100251. }
  100252. return childrenArray;
  100253. };
  100254. /**
  100255. * Appending the template to a parent HTML element.
  100256. * If a parent is already set and you wish to replace the old HTML with new one, forceRemove should be true.
  100257. * @param parent the parent to which the template is added
  100258. * @param forceRemove if the parent already exists, shoud the template be removed from it?
  100259. */
  100260. Template.prototype.appendTo = function (parent, forceRemove) {
  100261. var _this = this;
  100262. if (this.parent) {
  100263. if (forceRemove) {
  100264. this.parent.removeChild(this._fragment);
  100265. }
  100266. else {
  100267. return;
  100268. }
  100269. }
  100270. this.parent = parent;
  100271. if (this._configuration.id) {
  100272. this.parent.id = this._configuration.id;
  100273. }
  100274. this._fragment = this.parent.appendChild(this._fragment);
  100275. // appended only one frame after.
  100276. setTimeout(function () {
  100277. _this._registerEvents();
  100278. _this.onAppended.notifyObservers(_this);
  100279. });
  100280. };
  100281. /**
  100282. * Show the template using the provided visibilityFunction, or natively using display: flex.
  100283. * The provided function returns a promise that should be fullfilled when the element is shown.
  100284. * Since it is a promise async operations are more than possible.
  100285. * See the default viewer for an opacity example.
  100286. * @param visibilityFunction The function to execute to show the template.
  100287. */
  100288. Template.prototype.show = function (visibilityFunction) {
  100289. var _this = this;
  100290. if (this._isHiding)
  100291. return Promise.resolve(this);
  100292. return Promise.resolve().then(function () {
  100293. _this._isShowing = true;
  100294. if (visibilityFunction) {
  100295. return visibilityFunction(_this);
  100296. }
  100297. else {
  100298. // flex? box? should this be configurable easier than the visibilityFunction?
  100299. _this.parent.style.display = 'flex';
  100300. return _this;
  100301. }
  100302. }).then(function () {
  100303. _this.isShown = true;
  100304. _this._isShowing = false;
  100305. _this.onStateChange.notifyObservers(_this);
  100306. return _this;
  100307. });
  100308. };
  100309. /**
  100310. * Hide the template using the provided visibilityFunction, or natively using display: none.
  100311. * The provided function returns a promise that should be fullfilled when the element is hidden.
  100312. * Since it is a promise async operations are more than possible.
  100313. * See the default viewer for an opacity example.
  100314. * @param visibilityFunction The function to execute to show the template.
  100315. */
  100316. Template.prototype.hide = function (visibilityFunction) {
  100317. var _this = this;
  100318. if (this._isShowing)
  100319. return Promise.resolve(this);
  100320. return Promise.resolve().then(function () {
  100321. _this._isHiding = true;
  100322. if (visibilityFunction) {
  100323. return visibilityFunction(_this);
  100324. }
  100325. else {
  100326. // flex? box? should this be configurable easier than the visibilityFunction?
  100327. _this.parent.style.display = 'hide';
  100328. return _this;
  100329. }
  100330. }).then(function () {
  100331. _this.isShown = false;
  100332. _this._isHiding = false;
  100333. _this.onStateChange.notifyObservers(_this);
  100334. return _this;
  100335. });
  100336. };
  100337. /**
  100338. * Dispose this template
  100339. */
  100340. Template.prototype.dispose = function () {
  100341. this.onAppended.clear();
  100342. this.onEventTriggered.clear();
  100343. this.onLoaded.clear();
  100344. this.onStateChange.clear();
  100345. this.isLoaded = false;
  100346. // remove from parent
  100347. try {
  100348. this.parent.removeChild(this._fragment);
  100349. }
  100350. catch (e) {
  100351. //noop
  100352. }
  100353. this.loadRequests.forEach(function (request) {
  100354. request.abort();
  100355. });
  100356. if (this._registeredEvents) {
  100357. this._registeredEvents.forEach(function (evt) {
  100358. evt.htmlElement.removeEventListener(evt.eventName, evt.function);
  100359. });
  100360. }
  100361. delete this._fragment;
  100362. };
  100363. Template.prototype._getTemplateAsHtml = function (templateConfig) {
  100364. var _this = this;
  100365. if (!templateConfig) {
  100366. return Promise.reject('No templateConfig provided');
  100367. }
  100368. else if (templateConfig.html !== undefined) {
  100369. return Promise.resolve(templateConfig.html);
  100370. }
  100371. else {
  100372. var location_1 = this._getTemplateLocation(templateConfig);
  100373. if (helper_1.isUrl(location_1)) {
  100374. return new Promise(function (resolve, reject) {
  100375. var fileRequest = babylonjs_1.Tools.LoadFile(location_1, function (data) {
  100376. resolve(data);
  100377. }, undefined, undefined, false, function (request, error) {
  100378. reject(error);
  100379. });
  100380. _this.loadRequests.push(fileRequest);
  100381. });
  100382. }
  100383. else {
  100384. location_1 = location_1.replace('#', '');
  100385. var element = document.getElementById(location_1);
  100386. if (element) {
  100387. return Promise.resolve(element.innerHTML);
  100388. }
  100389. else {
  100390. return Promise.reject('Template ID not found');
  100391. }
  100392. }
  100393. }
  100394. };
  100395. Template.prototype._registerEvents = function () {
  100396. var _this = this;
  100397. this._registeredEvents = this._registeredEvents || [];
  100398. if (this._registeredEvents.length) {
  100399. // first remove the registered events
  100400. this._registeredEvents.forEach(function (evt) {
  100401. evt.htmlElement.removeEventListener(evt.eventName, evt.function);
  100402. });
  100403. }
  100404. if (this._configuration.events) {
  100405. var _loop_1 = function (eventName) {
  100406. if (this_1._configuration.events && this_1._configuration.events[eventName]) {
  100407. var functionToFire_1 = function (selector, event) {
  100408. _this.onEventTriggered.notifyObservers({ event: event, template: _this, selector: selector });
  100409. };
  100410. // if boolean, set the parent as the event listener
  100411. if (typeof this_1._configuration.events[eventName] === 'boolean') {
  100412. var binding = functionToFire_1.bind(this_1, '#' + this_1.parent.id);
  100413. this_1.parent.addEventListener(eventName, functionToFire_1.bind(this_1, '#' + this_1.parent.id), false);
  100414. this_1._registeredEvents.push({
  100415. htmlElement: this_1.parent,
  100416. eventName: eventName,
  100417. function: binding
  100418. });
  100419. }
  100420. else if (typeof this_1._configuration.events[eventName] === 'object') {
  100421. var selectorsArray = Object.keys(this_1._configuration.events[eventName] || {});
  100422. // strict null checl is working incorrectly, must override:
  100423. var event_1 = this_1._configuration.events[eventName] || {};
  100424. selectorsArray.filter(function (selector) { return event_1[selector]; }).forEach(function (selector) {
  100425. if (selector && selector.indexOf('#') !== 0) {
  100426. selector = '#' + selector;
  100427. }
  100428. var htmlElement = _this.parent.querySelector(selector);
  100429. if (htmlElement) {
  100430. var binding = functionToFire_1.bind(_this, selector);
  100431. htmlElement.addEventListener(eventName, binding, false);
  100432. _this._registeredEvents.push({
  100433. htmlElement: htmlElement,
  100434. eventName: eventName,
  100435. function: binding
  100436. });
  100437. }
  100438. });
  100439. }
  100440. }
  100441. };
  100442. var this_1 = this;
  100443. for (var eventName in this._configuration.events) {
  100444. _loop_1(eventName);
  100445. }
  100446. }
  100447. };
  100448. Template.prototype._getTemplateLocation = function (templateConfig) {
  100449. if (!templateConfig || typeof templateConfig === 'string') {
  100450. return templateConfig;
  100451. }
  100452. else {
  100453. return templateConfig.location;
  100454. }
  100455. };
  100456. return Template;
  100457. }());
  100458. exports.Template = Template;
  100459. /***/ }),
  100460. /* 24 */
  100461. /***/ (function(module, exports, __webpack_require__) {
  100462. /**!
  100463. @license
  100464. handlebars v4.0.11
  100465. Copyright (C) 2011-2017 by Yehuda Katz
  100466. Permission is hereby granted, free of charge, to any person obtaining a copy
  100467. of this software and associated documentation files (the "Software"), to deal
  100468. in the Software without restriction, including without limitation the rights
  100469. to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  100470. copies of the Software, and to permit persons to whom the Software is
  100471. furnished to do so, subject to the following conditions:
  100472. The above copyright notice and this permission notice shall be included in
  100473. all copies or substantial portions of the Software.
  100474. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  100475. IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  100476. FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  100477. AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  100478. LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  100479. OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
  100480. THE SOFTWARE.
  100481. */
  100482. !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],
  100483. 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){
  100484. 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"]}])});
  100485. /***/ }),
  100486. /* 25 */
  100487. /***/ (function(module, exports, __webpack_require__) {
  100488. "use strict";
  100489. Object.defineProperty(exports, "__esModule", { value: true });
  100490. /**
  100491. * The EventManager is in charge of registering user interctions with the viewer.
  100492. * It is used in the TemplateManager
  100493. */
  100494. var EventManager = /** @class */ (function () {
  100495. function EventManager(_templateManager) {
  100496. var _this = this;
  100497. this._templateManager = _templateManager;
  100498. this._callbacksContainer = {};
  100499. this._templateManager.onEventTriggered.add(function (eventData) {
  100500. _this._eventTriggered(eventData);
  100501. });
  100502. }
  100503. /**
  100504. * Register a new callback to a specific template.
  100505. * The best example for the usage can be found in the DefaultViewer
  100506. *
  100507. * @param templateName the templateName to register the event to
  100508. * @param callback The callback to be executed
  100509. * @param eventType the type of event to register
  100510. * @param selector an optional selector. if not defined the parent object in the template will be selected
  100511. */
  100512. EventManager.prototype.registerCallback = function (templateName, callback, eventType, selector) {
  100513. if (!this._callbacksContainer[templateName]) {
  100514. this._callbacksContainer[templateName] = [];
  100515. }
  100516. this._callbacksContainer[templateName].push({
  100517. eventType: eventType,
  100518. callback: callback
  100519. });
  100520. };
  100521. /**
  100522. * This will remove a registered event from the defined template.
  100523. * Each one of the variables apart from the template name are optional, but one must be provided.
  100524. *
  100525. * @param templateName the templateName
  100526. * @param callback the callback to remove (optional)
  100527. * @param eventType the event type to remove (optional)
  100528. * @param selector the selector from which to remove the event (optional)
  100529. */
  100530. EventManager.prototype.unregisterCallback = function (templateName, callback, eventType, selector) {
  100531. var callbackDefs = this._callbacksContainer[templateName] || [];
  100532. this._callbacksContainer[templateName] = callbackDefs.filter(function (callbackDef) { return (!callbackDef.eventType || callbackDef.eventType === eventType) && (!callbackDef.selector || callbackDef.selector === selector); });
  100533. };
  100534. EventManager.prototype._eventTriggered = function (data) {
  100535. var templateName = data.template.name;
  100536. var eventType = data.event.type;
  100537. var selector = data.selector;
  100538. var callbackDefs = this._callbacksContainer[templateName] || [];
  100539. callbackDefs.filter(function (callbackDef) { return (!callbackDef.eventType || callbackDef.eventType === eventType) && (!callbackDef.selector || callbackDef.selector === selector); }).forEach(function (callbackDef) {
  100540. callbackDef.callback(data);
  100541. });
  100542. };
  100543. /**
  100544. * Dispose the event manager
  100545. */
  100546. EventManager.prototype.dispose = function () {
  100547. this._callbacksContainer = {};
  100548. };
  100549. return EventManager;
  100550. }());
  100551. exports.EventManager = EventManager;
  100552. /***/ }),
  100553. /* 26 */
  100554. /***/ (function(module, exports, __webpack_require__) {
  100555. "use strict";
  100556. Object.defineProperty(exports, "__esModule", { value: true });
  100557. var mappers_1 = __webpack_require__(1);
  100558. var types_1 = __webpack_require__(27);
  100559. var deepmerge = __webpack_require__(2);
  100560. var babylonjs_1 = __webpack_require__(0);
  100561. /**
  100562. * The configuration loader will load the configuration object from any source and will use the defined mapper to
  100563. * parse the object and return a conform ViewerConfiguration.
  100564. * It is a private member of the scene.
  100565. */
  100566. var ConfigurationLoader = /** @class */ (function () {
  100567. function ConfigurationLoader(_enableCache) {
  100568. if (_enableCache === void 0) { _enableCache = false; }
  100569. this._enableCache = _enableCache;
  100570. this._configurationCache = {};
  100571. this._loadRequests = [];
  100572. }
  100573. /**
  100574. * load a configuration object that is defined in the initial configuration provided.
  100575. * The viewer configuration can extend different types of configuration objects and have an extra configuration defined.
  100576. *
  100577. * @param initConfig the initial configuration that has the definitions of further configuration to load.
  100578. * @param callback an optional callback that will be called sync, if noconfiguration needs to be loaded or configuration is payload-only
  100579. * @returns A promise that delivers the extended viewer configuration, when done.
  100580. */
  100581. ConfigurationLoader.prototype.loadConfiguration = function (initConfig, callback) {
  100582. var _this = this;
  100583. if (initConfig === void 0) { initConfig = {}; }
  100584. var loadedConfig = deepmerge({}, initConfig);
  100585. var extendedConfiguration = types_1.getConfigurationType(loadedConfig.extends || "");
  100586. loadedConfig = deepmerge(extendedConfiguration, loadedConfig);
  100587. if (loadedConfig.configuration) {
  100588. var mapperType_1 = "json";
  100589. return Promise.resolve().then(function () {
  100590. if (typeof loadedConfig.configuration === "string" || (loadedConfig.configuration && loadedConfig.configuration.url)) {
  100591. // a file to load
  100592. var url = '';
  100593. if (typeof loadedConfig.configuration === "string") {
  100594. url = loadedConfig.configuration;
  100595. }
  100596. // if configuration is an object
  100597. if (typeof loadedConfig.configuration === "object" && loadedConfig.configuration.url) {
  100598. url = loadedConfig.configuration.url;
  100599. var type = loadedConfig.configuration.mapper;
  100600. // empty string?
  100601. if (!type) {
  100602. // load mapper type from filename / url
  100603. type = loadedConfig.configuration.url.split('.').pop();
  100604. }
  100605. mapperType_1 = type || mapperType_1;
  100606. }
  100607. return _this._loadFile(url);
  100608. }
  100609. else {
  100610. if (typeof loadedConfig.configuration === "object") {
  100611. mapperType_1 = loadedConfig.configuration.mapper || mapperType_1;
  100612. return loadedConfig.configuration.payload || {};
  100613. }
  100614. return {};
  100615. }
  100616. }).then(function (data) {
  100617. var mapper = mappers_1.mapperManager.getMapper(mapperType_1);
  100618. var parsed = mapper.map(data);
  100619. var merged = deepmerge(loadedConfig, parsed);
  100620. if (callback)
  100621. callback(merged);
  100622. return merged;
  100623. });
  100624. }
  100625. else {
  100626. if (callback)
  100627. callback(loadedConfig);
  100628. return Promise.resolve(loadedConfig);
  100629. }
  100630. };
  100631. /**
  100632. * Dispose the configuration loader. This will cancel file requests, if active.
  100633. */
  100634. ConfigurationLoader.prototype.dispose = function () {
  100635. this._loadRequests.forEach(function (request) {
  100636. request.abort();
  100637. });
  100638. this._loadRequests.length = 0;
  100639. };
  100640. ConfigurationLoader.prototype._loadFile = function (url) {
  100641. var _this = this;
  100642. var cacheReference = this._configurationCache;
  100643. if (this._enableCache && cacheReference[url]) {
  100644. return Promise.resolve(cacheReference[url]);
  100645. }
  100646. return new Promise(function (resolve, reject) {
  100647. var fileRequest = babylonjs_1.Tools.LoadFile(url, function (result) {
  100648. var idx = _this._loadRequests.indexOf(fileRequest);
  100649. if (idx !== -1)
  100650. _this._loadRequests.splice(idx, 1);
  100651. if (_this._enableCache)
  100652. cacheReference[url] = result;
  100653. resolve(result);
  100654. }, undefined, undefined, false, function (request, error) {
  100655. var idx = _this._loadRequests.indexOf(fileRequest);
  100656. if (idx !== -1)
  100657. _this._loadRequests.splice(idx, 1);
  100658. reject(error);
  100659. });
  100660. _this._loadRequests.push(fileRequest);
  100661. });
  100662. };
  100663. return ConfigurationLoader;
  100664. }());
  100665. exports.ConfigurationLoader = ConfigurationLoader;
  100666. /***/ }),
  100667. /* 27 */
  100668. /***/ (function(module, exports, __webpack_require__) {
  100669. "use strict";
  100670. Object.defineProperty(exports, "__esModule", { value: true });
  100671. var minimal_1 = __webpack_require__(28);
  100672. exports.minimalConfiguration = minimal_1.minimalConfiguration;
  100673. var default_1 = __webpack_require__(29);
  100674. exports.defaultConfiguration = default_1.defaultConfiguration;
  100675. var getConfigurationType = function (type) {
  100676. switch (type) {
  100677. case 'default':
  100678. return default_1.defaultConfiguration;
  100679. case 'minimal':
  100680. return minimal_1.minimalConfiguration;
  100681. case 'none':
  100682. return {};
  100683. default:
  100684. return default_1.defaultConfiguration;
  100685. }
  100686. };
  100687. exports.getConfigurationType = getConfigurationType;
  100688. /***/ }),
  100689. /* 28 */
  100690. /***/ (function(module, exports, __webpack_require__) {
  100691. "use strict";
  100692. Object.defineProperty(exports, "__esModule", { value: true });
  100693. exports.minimalConfiguration = {
  100694. version: "0.1",
  100695. templates: {
  100696. main: {
  100697. html: __webpack_require__(7)
  100698. },
  100699. loadingScreen: {
  100700. html: __webpack_require__(8),
  100701. params: {
  100702. backgroundColor: "#000000",
  100703. 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"
  100704. }
  100705. },
  100706. viewer: {
  100707. html: __webpack_require__(10),
  100708. },
  100709. overlay: {
  100710. html: __webpack_require__(11),
  100711. params: {
  100712. closeImage: __webpack_require__(12),
  100713. closeText: 'Close'
  100714. }
  100715. },
  100716. error: {
  100717. html: __webpack_require__(13)
  100718. }
  100719. },
  100720. engine: {
  100721. antialiasing: true
  100722. }
  100723. };
  100724. /***/ }),
  100725. /* 29 */
  100726. /***/ (function(module, exports, __webpack_require__) {
  100727. "use strict";
  100728. Object.defineProperty(exports, "__esModule", { value: true });
  100729. exports.defaultConfiguration = {
  100730. version: "3.2.0-alpha4",
  100731. templates: {
  100732. main: {
  100733. html: __webpack_require__(7)
  100734. },
  100735. loadingScreen: {
  100736. html: __webpack_require__(8),
  100737. params: {
  100738. backgroundColor: "#000000",
  100739. loadingImage: __webpack_require__(9)
  100740. }
  100741. },
  100742. viewer: {
  100743. html: __webpack_require__(10),
  100744. events: {
  100745. pointerout: true,
  100746. pointerdown: true,
  100747. pointerup: true
  100748. }
  100749. },
  100750. navBar: {
  100751. html: __webpack_require__(30),
  100752. params: {
  100753. buttons: {
  100754. /*"help-button": {
  100755. altText: "Help",
  100756. image: require('../../../assets/img/help-circle.png')
  100757. },*/
  100758. "fullscreen-button": {
  100759. altText: "Fullscreen",
  100760. image: __webpack_require__(31)
  100761. }
  100762. },
  100763. visibilityTimeout: 2000
  100764. },
  100765. events: {
  100766. pointerdown: { 'fullscreen-button': true /*, '#help-button': true*/ },
  100767. pointerover: true
  100768. }
  100769. },
  100770. overlay: {
  100771. html: __webpack_require__(11),
  100772. params: {
  100773. closeImage: __webpack_require__(12),
  100774. closeText: 'Close'
  100775. }
  100776. },
  100777. help: {
  100778. html: __webpack_require__(32)
  100779. },
  100780. share: {
  100781. html: __webpack_require__(33)
  100782. },
  100783. error: {
  100784. html: __webpack_require__(13)
  100785. }
  100786. },
  100787. camera: {
  100788. behaviors: {
  100789. autoRotate: 0,
  100790. framing: {
  100791. type: 2,
  100792. zoomOnBoundingInfo: true,
  100793. zoomStopsAnimation: false
  100794. }
  100795. }
  100796. },
  100797. /*lights: {
  100798. "default": {
  100799. type: 1,
  100800. shadowEnabled: true,
  100801. direction: { x: -0.2, y: -0.8, z: 0 },
  100802. position: { x: 10, y: 10, z: 0 },
  100803. intensity: 4.5,
  100804. shadowConfig: {
  100805. useBlurExponentialShadowMap: true,
  100806. useKernelBlur: true,
  100807. blurKernel: 64,
  100808. blurScale: 4
  100809. }
  100810. }
  100811. },*/
  100812. skybox: {
  100813. /*cubeTexture: {
  100814. url: 'https://playground.babylonjs.com/textures/environment.dds',
  100815. gammaSpace: false
  100816. },*/
  100817. pbr: true,
  100818. blur: 0.7,
  100819. infiniteDIstance: false,
  100820. },
  100821. ground: true,
  100822. engine: {
  100823. antialiasing: true
  100824. },
  100825. scene: {
  100826. imageProcessingConfiguration: {
  100827. exposure: 1.4,
  100828. contrast: 1.66,
  100829. toneMappingEnabled: true
  100830. }
  100831. }
  100832. };
  100833. /***/ }),
  100834. /* 30 */
  100835. /***/ (function(module, exports) {
  100836. 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>";
  100837. /***/ }),
  100838. /* 31 */
  100839. /***/ (function(module, exports) {
  100840. module.exports = "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAADAAAAAwAQAAAAB/ecQqAAAAAnRSTlMAAHaTzTgAAAAeSURBVHgBY6ASsP/A/wcXZQNGhCkyAfE24HUndQAAXlkXcQ24P7gAAAAASUVORK5CYII="
  100841. /***/ }),
  100842. /* 32 */
  100843. /***/ (function(module, exports) {
  100844. module.exports = "HELP";
  100845. /***/ }),
  100846. /* 33 */
  100847. /***/ (function(module, exports) {
  100848. module.exports = "SHARE";
  100849. /***/ }),
  100850. /* 34 */
  100851. /***/ (function(module, exports, __webpack_require__) {
  100852. (function universalModuleDefinition(root, factory) {
  100853. var amdDependencies = [];
  100854. var BABYLON = root.BABYLON || this.BABYLON;
  100855. if(true) {
  100856. BABYLON = BABYLON || __webpack_require__(0);
  100857. module.exports = factory(BABYLON);
  100858. } else if(typeof define === 'function' && define.amd) {
  100859. amdDependencies.push("babylonjs");
  100860. define("babylonjs-loaders", amdDependencies, factory);
  100861. } else if(typeof exports === 'object') {
  100862. BABYLON = BABYLON || require("babylonjs");
  100863. exports["babylonjs-loaders"] = factory(BABYLON);
  100864. } else {
  100865. root["BABYLON"] = factory(BABYLON);
  100866. }
  100867. })(this, function(BABYLON) {
  100868. BABYLON = BABYLON || this.BABYLON;
  100869. 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};
  100870. 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)}}();
  100871. var BABYLON;
  100872. (function (BABYLON) {
  100873. var STLFileLoader = /** @class */ (function () {
  100874. function STLFileLoader() {
  100875. this.solidPattern = /solid (\S*)([\S\s]*)endsolid[ ]*(\S*)/g;
  100876. this.facetsPattern = /facet([\s\S]*?)endfacet/g;
  100877. 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;
  100878. 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;
  100879. this.name = "stl";
  100880. // force data to come in as an ArrayBuffer
  100881. // we'll convert to string if it looks like it's an ASCII .stl
  100882. this.extensions = {
  100883. ".stl": { isBinary: true },
  100884. };
  100885. }
  100886. STLFileLoader.prototype.importMesh = function (meshesNames, scene, data, rootUrl, meshes, particleSystems, skeletons) {
  100887. var matches;
  100888. if (this.isBinary(data)) {
  100889. // binary .stl
  100890. var babylonMesh = new BABYLON.Mesh("stlmesh", scene);
  100891. this.parseBinary(babylonMesh, data);
  100892. if (meshes) {
  100893. meshes.push(babylonMesh);
  100894. }
  100895. return true;
  100896. }
  100897. // ASCII .stl
  100898. // convert to string
  100899. var array_buffer = new Uint8Array(data);
  100900. var str = '';
  100901. for (var i = 0; i < data.byteLength; i++) {
  100902. str += String.fromCharCode(array_buffer[i]); // implicitly assumes little-endian
  100903. }
  100904. data = str;
  100905. while (matches = this.solidPattern.exec(data)) {
  100906. var meshName = matches[1];
  100907. var meshNameFromEnd = matches[3];
  100908. if (meshName != meshNameFromEnd) {
  100909. BABYLON.Tools.Error("Error in STL, solid name != endsolid name");
  100910. return false;
  100911. }
  100912. // check meshesNames
  100913. if (meshesNames && meshName) {
  100914. if (meshesNames instanceof Array) {
  100915. if (!meshesNames.indexOf(meshName)) {
  100916. continue;
  100917. }
  100918. }
  100919. else {
  100920. if (meshName !== meshesNames) {
  100921. continue;
  100922. }
  100923. }
  100924. }
  100925. // stl mesh name can be empty as well
  100926. meshName = meshName || "stlmesh";
  100927. var babylonMesh = new BABYLON.Mesh(meshName, scene);
  100928. this.parseASCII(babylonMesh, matches[2]);
  100929. if (meshes) {
  100930. meshes.push(babylonMesh);
  100931. }
  100932. }
  100933. return true;
  100934. };
  100935. STLFileLoader.prototype.load = function (scene, data, rootUrl) {
  100936. var result = this.importMesh(null, scene, data, rootUrl, null, null, null);
  100937. if (result) {
  100938. scene.createDefaultCameraOrLight();
  100939. }
  100940. return result;
  100941. };
  100942. STLFileLoader.prototype.loadAssetContainer = function (scene, data, rootUrl, onError) {
  100943. var container = new BABYLON.AssetContainer(scene);
  100944. this.importMesh(null, scene, data, rootUrl, container.meshes, null, null);
  100945. container.removeAllFromScene();
  100946. return container;
  100947. };
  100948. STLFileLoader.prototype.isBinary = function (data) {
  100949. // check if file size is correct for binary stl
  100950. var faceSize, nFaces, reader;
  100951. reader = new DataView(data);
  100952. faceSize = (32 / 8 * 3) + ((32 / 8 * 3) * 3) + (16 / 8);
  100953. nFaces = reader.getUint32(80, true);
  100954. if (80 + (32 / 8) + (nFaces * faceSize) === reader.byteLength) {
  100955. return true;
  100956. }
  100957. // check characters higher than ASCII to confirm binary
  100958. var fileLength = reader.byteLength;
  100959. for (var index = 0; index < fileLength; index++) {
  100960. if (reader.getUint8(index) > 127) {
  100961. return true;
  100962. }
  100963. }
  100964. return false;
  100965. };
  100966. STLFileLoader.prototype.parseBinary = function (mesh, data) {
  100967. var reader = new DataView(data);
  100968. var faces = reader.getUint32(80, true);
  100969. var dataOffset = 84;
  100970. var faceLength = 12 * 4 + 2;
  100971. var offset = 0;
  100972. var positions = new Float32Array(faces * 3 * 3);
  100973. var normals = new Float32Array(faces * 3 * 3);
  100974. var indices = new Uint32Array(faces * 3);
  100975. var indicesCount = 0;
  100976. for (var face = 0; face < faces; face++) {
  100977. var start = dataOffset + face * faceLength;
  100978. var normalX = reader.getFloat32(start, true);
  100979. var normalY = reader.getFloat32(start + 4, true);
  100980. var normalZ = reader.getFloat32(start + 8, true);
  100981. for (var i = 1; i <= 3; i++) {
  100982. var vertexstart = start + i * 12;
  100983. // ordering is intentional to match ascii import
  100984. positions[offset] = reader.getFloat32(vertexstart, true);
  100985. positions[offset + 2] = reader.getFloat32(vertexstart + 4, true);
  100986. positions[offset + 1] = reader.getFloat32(vertexstart + 8, true);
  100987. normals[offset] = normalX;
  100988. normals[offset + 2] = normalY;
  100989. normals[offset + 1] = normalZ;
  100990. offset += 3;
  100991. }
  100992. indices[indicesCount] = indicesCount++;
  100993. indices[indicesCount] = indicesCount++;
  100994. indices[indicesCount] = indicesCount++;
  100995. }
  100996. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, positions);
  100997. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals);
  100998. mesh.setIndices(indices);
  100999. mesh.computeWorldMatrix(true);
  101000. };
  101001. STLFileLoader.prototype.parseASCII = function (mesh, solidData) {
  101002. var positions = [];
  101003. var normals = [];
  101004. var indices = [];
  101005. var indicesCount = 0;
  101006. //load facets, ignoring loop as the standard doesn't define it can contain more than vertices
  101007. var matches;
  101008. while (matches = this.facetsPattern.exec(solidData)) {
  101009. var facet = matches[1];
  101010. //one normal per face
  101011. var normalMatches = this.normalPattern.exec(facet);
  101012. this.normalPattern.lastIndex = 0;
  101013. if (!normalMatches) {
  101014. continue;
  101015. }
  101016. var normal = [Number(normalMatches[1]), Number(normalMatches[5]), Number(normalMatches[3])];
  101017. var vertexMatch;
  101018. while (vertexMatch = this.vertexPattern.exec(facet)) {
  101019. positions.push(Number(vertexMatch[1]), Number(vertexMatch[5]), Number(vertexMatch[3]));
  101020. normals.push(normal[0], normal[1], normal[2]);
  101021. }
  101022. indices.push(indicesCount++, indicesCount++, indicesCount++);
  101023. this.vertexPattern.lastIndex = 0;
  101024. }
  101025. this.facetsPattern.lastIndex = 0;
  101026. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, positions);
  101027. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals);
  101028. mesh.setIndices(indices);
  101029. mesh.computeWorldMatrix(true);
  101030. };
  101031. return STLFileLoader;
  101032. }());
  101033. BABYLON.STLFileLoader = STLFileLoader;
  101034. if (BABYLON.SceneLoader) {
  101035. BABYLON.SceneLoader.RegisterPlugin(new STLFileLoader());
  101036. }
  101037. })(BABYLON || (BABYLON = {}));
  101038. //# sourceMappingURL=babylon.stlFileLoader.js.map
  101039. var BABYLON;
  101040. (function (BABYLON) {
  101041. /**
  101042. * Class reading and parsing the MTL file bundled with the obj file.
  101043. */
  101044. var MTLFileLoader = /** @class */ (function () {
  101045. function MTLFileLoader() {
  101046. // All material loaded from the mtl will be set here
  101047. this.materials = [];
  101048. }
  101049. /**
  101050. * This function will read the mtl file and create each material described inside
  101051. * This function could be improve by adding :
  101052. * -some component missing (Ni, Tf...)
  101053. * -including the specific options available
  101054. *
  101055. * @param scene
  101056. * @param data
  101057. * @param rootUrl
  101058. */
  101059. MTLFileLoader.prototype.parseMTL = function (scene, data, rootUrl) {
  101060. if (data instanceof ArrayBuffer) {
  101061. return;
  101062. }
  101063. //Split the lines from the file
  101064. var lines = data.split('\n');
  101065. //Space char
  101066. var delimiter_pattern = /\s+/;
  101067. //Array with RGB colors
  101068. var color;
  101069. //New material
  101070. var material = null;
  101071. //Look at each line
  101072. for (var i = 0; i < lines.length; i++) {
  101073. var line = lines[i].trim();
  101074. // Blank line or comment
  101075. if (line.length === 0 || line.charAt(0) === '#') {
  101076. continue;
  101077. }
  101078. //Get the first parameter (keyword)
  101079. var pos = line.indexOf(' ');
  101080. var key = (pos >= 0) ? line.substring(0, pos) : line;
  101081. key = key.toLowerCase();
  101082. //Get the data following the key
  101083. var value = (pos >= 0) ? line.substring(pos + 1).trim() : "";
  101084. //This mtl keyword will create the new material
  101085. if (key === "newmtl") {
  101086. //Check if it is the first material.
  101087. // Materials specifications are described after this keyword.
  101088. if (material) {
  101089. //Add the previous material in the material array.
  101090. this.materials.push(material);
  101091. }
  101092. //Create a new material.
  101093. // value is the name of the material read in the mtl file
  101094. material = new BABYLON.StandardMaterial(value, scene);
  101095. }
  101096. else if (key === "kd" && material) {
  101097. // Diffuse color (color under white light) using RGB values
  101098. //value = "r g b"
  101099. color = value.split(delimiter_pattern, 3).map(parseFloat);
  101100. //color = [r,g,b]
  101101. //Set tghe color into the material
  101102. material.diffuseColor = BABYLON.Color3.FromArray(color);
  101103. }
  101104. else if (key === "ka" && material) {
  101105. // Ambient color (color under shadow) using RGB values
  101106. //value = "r g b"
  101107. color = value.split(delimiter_pattern, 3).map(parseFloat);
  101108. //color = [r,g,b]
  101109. //Set tghe color into the material
  101110. material.ambientColor = BABYLON.Color3.FromArray(color);
  101111. }
  101112. else if (key === "ks" && material) {
  101113. // Specular color (color when light is reflected from shiny surface) using RGB values
  101114. //value = "r g b"
  101115. color = value.split(delimiter_pattern, 3).map(parseFloat);
  101116. //color = [r,g,b]
  101117. //Set the color into the material
  101118. material.specularColor = BABYLON.Color3.FromArray(color);
  101119. }
  101120. else if (key === "ke" && material) {
  101121. // Emissive color using RGB values
  101122. color = value.split(delimiter_pattern, 3).map(parseFloat);
  101123. material.emissiveColor = BABYLON.Color3.FromArray(color);
  101124. }
  101125. else if (key === "ns" && material) {
  101126. //value = "Integer"
  101127. material.specularPower = parseFloat(value);
  101128. }
  101129. else if (key === "d" && material) {
  101130. //d is dissolve for current material. It mean alpha for BABYLON
  101131. material.alpha = parseFloat(value);
  101132. //Texture
  101133. //This part can be improved by adding the possible options of texture
  101134. }
  101135. else if (key === "map_ka" && material) {
  101136. // ambient texture map with a loaded image
  101137. //We must first get the folder of the image
  101138. material.ambientTexture = MTLFileLoader._getTexture(rootUrl, value, scene);
  101139. }
  101140. else if (key === "map_kd" && material) {
  101141. // Diffuse texture map with a loaded image
  101142. material.diffuseTexture = MTLFileLoader._getTexture(rootUrl, value, scene);
  101143. }
  101144. else if (key === "map_ks" && material) {
  101145. // Specular texture map with a loaded image
  101146. //We must first get the folder of the image
  101147. material.specularTexture = MTLFileLoader._getTexture(rootUrl, value, scene);
  101148. }
  101149. else if (key === "map_ns") {
  101150. //Specular
  101151. //Specular highlight component
  101152. //We must first get the folder of the image
  101153. //
  101154. //Not supported by BABYLON
  101155. //
  101156. // continue;
  101157. }
  101158. else if (key === "map_bump" && material) {
  101159. //The bump texture
  101160. material.bumpTexture = MTLFileLoader._getTexture(rootUrl, value, scene);
  101161. }
  101162. else if (key === "map_d" && material) {
  101163. // The dissolve of the material
  101164. material.opacityTexture = MTLFileLoader._getTexture(rootUrl, value, scene);
  101165. //Options for illumination
  101166. }
  101167. else if (key === "illum") {
  101168. //Illumination
  101169. if (value === "0") {
  101170. //That mean Kd == Kd
  101171. }
  101172. else if (value === "1") {
  101173. //Color on and Ambient on
  101174. }
  101175. else if (value === "2") {
  101176. //Highlight on
  101177. }
  101178. else if (value === "3") {
  101179. //Reflection on and Ray trace on
  101180. }
  101181. else if (value === "4") {
  101182. //Transparency: Glass on, Reflection: Ray trace on
  101183. }
  101184. else if (value === "5") {
  101185. //Reflection: Fresnel on and Ray trace on
  101186. }
  101187. else if (value === "6") {
  101188. //Transparency: Refraction on, Reflection: Fresnel off and Ray trace on
  101189. }
  101190. else if (value === "7") {
  101191. //Transparency: Refraction on, Reflection: Fresnel on and Ray trace on
  101192. }
  101193. else if (value === "8") {
  101194. //Reflection on and Ray trace off
  101195. }
  101196. else if (value === "9") {
  101197. //Transparency: Glass on, Reflection: Ray trace off
  101198. }
  101199. else if (value === "10") {
  101200. //Casts shadows onto invisible surfaces
  101201. }
  101202. }
  101203. else {
  101204. // console.log("Unhandled expression at line : " + i +'\n' + "with value : " + line);
  101205. }
  101206. }
  101207. //At the end of the file, add the last material
  101208. if (material) {
  101209. this.materials.push(material);
  101210. }
  101211. };
  101212. /**
  101213. * Gets the texture for the material.
  101214. *
  101215. * If the material is imported from input file,
  101216. * We sanitize the url to ensure it takes the textre from aside the material.
  101217. *
  101218. * @param rootUrl The root url to load from
  101219. * @param value The value stored in the mtl
  101220. * @return The Texture
  101221. */
  101222. MTLFileLoader._getTexture = function (rootUrl, value, scene) {
  101223. if (!value) {
  101224. return null;
  101225. }
  101226. var url = rootUrl;
  101227. // Load from input file.
  101228. if (rootUrl === "file:") {
  101229. var lastDelimiter = value.lastIndexOf("\\");
  101230. if (lastDelimiter === -1) {
  101231. lastDelimiter = value.lastIndexOf("/");
  101232. }
  101233. if (lastDelimiter > -1) {
  101234. url += value.substr(lastDelimiter + 1);
  101235. }
  101236. else {
  101237. url += value;
  101238. }
  101239. }
  101240. // Not from input file.
  101241. else {
  101242. url += value;
  101243. }
  101244. return new BABYLON.Texture(url, scene);
  101245. };
  101246. return MTLFileLoader;
  101247. }());
  101248. BABYLON.MTLFileLoader = MTLFileLoader;
  101249. var OBJFileLoader = /** @class */ (function () {
  101250. function OBJFileLoader() {
  101251. this.name = "obj";
  101252. this.extensions = ".obj";
  101253. this.obj = /^o/;
  101254. this.group = /^g/;
  101255. this.mtllib = /^mtllib /;
  101256. this.usemtl = /^usemtl /;
  101257. this.smooth = /^s /;
  101258. this.vertexPattern = /v( +[\d|\.|\+|\-|e|E]+)( +[\d|\.|\+|\-|e|E]+)( +[\d|\.|\+|\-|e|E]+)/;
  101259. // vn float float float
  101260. this.normalPattern = /vn( +[\d|\.|\+|\-|e|E]+)( +[\d|\.|\+|\-|e|E]+)( +[\d|\.|\+|\-|e|E]+)/;
  101261. // vt float float
  101262. this.uvPattern = /vt( +[\d|\.|\+|\-|e|E]+)( +[\d|\.|\+|\-|e|E]+)/;
  101263. // f vertex vertex vertex ...
  101264. this.facePattern1 = /f\s+(([\d]{1,}[\s]?){3,})+/;
  101265. // f vertex/uvs vertex/uvs vertex/uvs ...
  101266. this.facePattern2 = /f\s+((([\d]{1,}\/[\d]{1,}[\s]?){3,})+)/;
  101267. // f vertex/uvs/normal vertex/uvs/normal vertex/uvs/normal ...
  101268. this.facePattern3 = /f\s+((([\d]{1,}\/[\d]{1,}\/[\d]{1,}[\s]?){3,})+)/;
  101269. // f vertex//normal vertex//normal vertex//normal ...
  101270. this.facePattern4 = /f\s+((([\d]{1,}\/\/[\d]{1,}[\s]?){3,})+)/;
  101271. }
  101272. /**
  101273. * Calls synchronously the MTL file attached to this obj.
  101274. * Load function or importMesh function don't enable to load 2 files in the same time asynchronously.
  101275. * Without this function materials are not displayed in the first frame (but displayed after).
  101276. * In consequence it is impossible to get material information in your HTML file
  101277. *
  101278. * @param url The URL of the MTL file
  101279. * @param rootUrl
  101280. * @param onSuccess Callback function to be called when the MTL file is loaded
  101281. * @private
  101282. */
  101283. OBJFileLoader.prototype._loadMTL = function (url, rootUrl, onSuccess) {
  101284. //The complete path to the mtl file
  101285. var pathOfFile = BABYLON.Tools.BaseUrl + rootUrl + url;
  101286. // Loads through the babylon tools to allow fileInput search.
  101287. BABYLON.Tools.LoadFile(pathOfFile, onSuccess, undefined, undefined, false, function () { console.warn("Error - Unable to load " + pathOfFile); });
  101288. };
  101289. OBJFileLoader.prototype.importMesh = function (meshesNames, scene, data, rootUrl, meshes, particleSystems, skeletons) {
  101290. //get the meshes from OBJ file
  101291. var loadedMeshes = this._parseSolid(meshesNames, scene, data, rootUrl);
  101292. //Push meshes from OBJ file into the variable mesh of this function
  101293. if (meshes) {
  101294. loadedMeshes.forEach(function (mesh) {
  101295. meshes.push(mesh);
  101296. });
  101297. }
  101298. return true;
  101299. };
  101300. OBJFileLoader.prototype.load = function (scene, data, rootUrl) {
  101301. //Get the 3D model
  101302. return this.importMesh(null, scene, data, rootUrl, null, null, null);
  101303. };
  101304. OBJFileLoader.prototype.loadAssetContainer = function (scene, data, rootUrl, onError) {
  101305. var container = new BABYLON.AssetContainer(scene);
  101306. this.importMesh(null, scene, data, rootUrl, container.meshes, null, null);
  101307. container.removeAllFromScene();
  101308. return container;
  101309. };
  101310. /**
  101311. * Read the OBJ file and create an Array of meshes.
  101312. * Each mesh contains all information given by the OBJ and the MTL file.
  101313. * i.e. vertices positions and indices, optional normals values, optional UV values, optional material
  101314. *
  101315. * @param meshesNames
  101316. * @param scene BABYLON.Scene The scene where are displayed the data
  101317. * @param data String The content of the obj file
  101318. * @param rootUrl String The path to the folder
  101319. * @returns Array<AbstractMesh>
  101320. * @private
  101321. */
  101322. OBJFileLoader.prototype._parseSolid = function (meshesNames, scene, data, rootUrl) {
  101323. var positions = []; //values for the positions of vertices
  101324. var normals = []; //Values for the normals
  101325. var uvs = []; //Values for the textures
  101326. var meshesFromObj = []; //[mesh] Contains all the obj meshes
  101327. var handledMesh; //The current mesh of meshes array
  101328. var indicesForBabylon = []; //The list of indices for VertexData
  101329. var wrappedPositionForBabylon = []; //The list of position in vectors
  101330. var wrappedUvsForBabylon = []; //Array with all value of uvs to match with the indices
  101331. var wrappedNormalsForBabylon = []; //Array with all value of normals to match with the indices
  101332. var tuplePosNorm = []; //Create a tuple with indice of Position, Normal, UV [pos, norm, uvs]
  101333. var curPositionInIndices = 0;
  101334. var hasMeshes = false; //Meshes are defined in the file
  101335. var unwrappedPositionsForBabylon = []; //Value of positionForBabylon w/o Vector3() [x,y,z]
  101336. var unwrappedNormalsForBabylon = []; //Value of normalsForBabylon w/o Vector3() [x,y,z]
  101337. var unwrappedUVForBabylon = []; //Value of uvsForBabylon w/o Vector3() [x,y,z]
  101338. var triangles = []; //Indices from new triangles coming from polygons
  101339. var materialNameFromObj = ""; //The name of the current material
  101340. var fileToLoad = ""; //The name of the mtlFile to load
  101341. var materialsFromMTLFile = new MTLFileLoader();
  101342. var objMeshName = ""; //The name of the current obj mesh
  101343. var increment = 1; //Id for meshes created by the multimaterial
  101344. var isFirstMaterial = true;
  101345. /**
  101346. * Search for obj in the given array.
  101347. * This function is called to check if a couple of data already exists in an array.
  101348. *
  101349. * If found, returns the index of the founded tuple index. Returns -1 if not found
  101350. * @param arr Array<{ normals: Array<number>, idx: Array<number> }>
  101351. * @param obj Array<number>
  101352. * @returns {boolean}
  101353. */
  101354. var isInArray = function (arr, obj) {
  101355. if (!arr[obj[0]])
  101356. arr[obj[0]] = { normals: [], idx: [] };
  101357. var idx = arr[obj[0]].normals.indexOf(obj[1]);
  101358. return idx === -1 ? -1 : arr[obj[0]].idx[idx];
  101359. };
  101360. var isInArrayUV = function (arr, obj) {
  101361. if (!arr[obj[0]])
  101362. arr[obj[0]] = { normals: [], idx: [], uv: [] };
  101363. var idx = arr[obj[0]].normals.indexOf(obj[1]);
  101364. if (idx != 1 && (obj[2] == arr[obj[0]].uv[idx])) {
  101365. return arr[obj[0]].idx[idx];
  101366. }
  101367. return -1;
  101368. };
  101369. /**
  101370. * This function set the data for each triangle.
  101371. * Data are position, normals and uvs
  101372. * If a tuple of (position, normal) is not set, add the data into the corresponding array
  101373. * If the tuple already exist, add only their indice
  101374. *
  101375. * @param indicePositionFromObj Integer The index in positions array
  101376. * @param indiceUvsFromObj Integer The index in uvs array
  101377. * @param indiceNormalFromObj Integer The index in normals array
  101378. * @param positionVectorFromOBJ Vector3 The value of position at index objIndice
  101379. * @param textureVectorFromOBJ Vector3 The value of uvs
  101380. * @param normalsVectorFromOBJ Vector3 The value of normals at index objNormale
  101381. */
  101382. var setData = function (indicePositionFromObj, indiceUvsFromObj, indiceNormalFromObj, positionVectorFromOBJ, textureVectorFromOBJ, normalsVectorFromOBJ) {
  101383. //Check if this tuple already exists in the list of tuples
  101384. var _index;
  101385. if (OBJFileLoader.OPTIMIZE_WITH_UV) {
  101386. _index = isInArrayUV(tuplePosNorm, [
  101387. indicePositionFromObj,
  101388. indiceNormalFromObj,
  101389. indiceUvsFromObj
  101390. ]);
  101391. }
  101392. else {
  101393. _index = isInArray(tuplePosNorm, [
  101394. indicePositionFromObj,
  101395. indiceNormalFromObj
  101396. ]);
  101397. }
  101398. //If it not exists
  101399. if (_index == -1) {
  101400. //Add an new indice.
  101401. //The array of indices is only an array with his length equal to the number of triangles - 1.
  101402. //We add vertices data in this order
  101403. indicesForBabylon.push(wrappedPositionForBabylon.length);
  101404. //Push the position of vertice for Babylon
  101405. //Each element is a BABYLON.Vector3(x,y,z)
  101406. wrappedPositionForBabylon.push(positionVectorFromOBJ);
  101407. //Push the uvs for Babylon
  101408. //Each element is a BABYLON.Vector3(u,v)
  101409. wrappedUvsForBabylon.push(textureVectorFromOBJ);
  101410. //Push the normals for Babylon
  101411. //Each element is a BABYLON.Vector3(x,y,z)
  101412. wrappedNormalsForBabylon.push(normalsVectorFromOBJ);
  101413. //Add the tuple in the comparison list
  101414. tuplePosNorm[indicePositionFromObj].normals.push(indiceNormalFromObj);
  101415. tuplePosNorm[indicePositionFromObj].idx.push(curPositionInIndices++);
  101416. if (OBJFileLoader.OPTIMIZE_WITH_UV)
  101417. tuplePosNorm[indicePositionFromObj].uv.push(indiceUvsFromObj);
  101418. }
  101419. else {
  101420. //The tuple already exists
  101421. //Add the index of the already existing tuple
  101422. //At this index we can get the value of position, normal and uvs of vertex
  101423. indicesForBabylon.push(_index);
  101424. }
  101425. };
  101426. /**
  101427. * Transform BABYLON.Vector() object onto 3 digits in an array
  101428. */
  101429. var unwrapData = function () {
  101430. //Every array has the same length
  101431. for (var l = 0; l < wrappedPositionForBabylon.length; l++) {
  101432. //Push the x, y, z values of each element in the unwrapped array
  101433. unwrappedPositionsForBabylon.push(wrappedPositionForBabylon[l].x, wrappedPositionForBabylon[l].y, wrappedPositionForBabylon[l].z);
  101434. unwrappedNormalsForBabylon.push(wrappedNormalsForBabylon[l].x, wrappedNormalsForBabylon[l].y, wrappedNormalsForBabylon[l].z);
  101435. unwrappedUVForBabylon.push(wrappedUvsForBabylon[l].x, wrappedUvsForBabylon[l].y); //z is an optional value not supported by BABYLON
  101436. }
  101437. // Reset arrays for the next new meshes
  101438. wrappedPositionForBabylon = [];
  101439. wrappedNormalsForBabylon = [];
  101440. wrappedUvsForBabylon = [];
  101441. tuplePosNorm = [];
  101442. curPositionInIndices = 0;
  101443. };
  101444. /**
  101445. * Create triangles from polygons by recursion
  101446. * The best to understand how it works is to draw it in the same time you get the recursion.
  101447. * It is important to notice that a triangle is a polygon
  101448. * We get 4 patterns of face defined in OBJ File :
  101449. * facePattern1 = ["1","2","3","4","5","6"]
  101450. * facePattern2 = ["1/1","2/2","3/3","4/4","5/5","6/6"]
  101451. * facePattern3 = ["1/1/1","2/2/2","3/3/3","4/4/4","5/5/5","6/6/6"]
  101452. * facePattern4 = ["1//1","2//2","3//3","4//4","5//5","6//6"]
  101453. * Each pattern is divided by the same method
  101454. * @param face Array[String] The indices of elements
  101455. * @param v Integer The variable to increment
  101456. */
  101457. var getTriangles = function (face, v) {
  101458. //Work for each element of the array
  101459. if (v + 1 < face.length) {
  101460. //Add on the triangle variable the indexes to obtain triangles
  101461. triangles.push(face[0], face[v], face[v + 1]);
  101462. //Incrementation for recursion
  101463. v += 1;
  101464. //Recursion
  101465. getTriangles(face, v);
  101466. }
  101467. //Result obtained after 2 iterations:
  101468. //Pattern1 => triangle = ["1","2","3","1","3","4"];
  101469. //Pattern2 => triangle = ["1/1","2/2","3/3","1/1","3/3","4/4"];
  101470. //Pattern3 => triangle = ["1/1/1","2/2/2","3/3/3","1/1/1","3/3/3","4/4/4"];
  101471. //Pattern4 => triangle = ["1//1","2//2","3//3","1//1","3//3","4//4"];
  101472. };
  101473. /**
  101474. * Create triangles and push the data for each polygon for the pattern 1
  101475. * In this pattern we get vertice positions
  101476. * @param face
  101477. * @param v
  101478. */
  101479. var setDataForCurrentFaceWithPattern1 = function (face, v) {
  101480. //Get the indices of triangles for each polygon
  101481. getTriangles(face, v);
  101482. //For each element in the triangles array.
  101483. //This var could contains 1 to an infinity of triangles
  101484. for (var k = 0; k < triangles.length; k++) {
  101485. // Set position indice
  101486. var indicePositionFromObj = parseInt(triangles[k]) - 1;
  101487. setData(indicePositionFromObj, 0, 0, //In the pattern 1, normals and uvs are not defined
  101488. positions[indicePositionFromObj], //Get the vectors data
  101489. BABYLON.Vector2.Zero(), BABYLON.Vector3.Up() //Create default vectors
  101490. );
  101491. }
  101492. //Reset variable for the next line
  101493. triangles = [];
  101494. };
  101495. /**
  101496. * Create triangles and push the data for each polygon for the pattern 2
  101497. * In this pattern we get vertice positions and uvsu
  101498. * @param face
  101499. * @param v
  101500. */
  101501. var setDataForCurrentFaceWithPattern2 = function (face, v) {
  101502. //Get the indices of triangles for each polygon
  101503. getTriangles(face, v);
  101504. for (var k = 0; k < triangles.length; k++) {
  101505. //triangle[k] = "1/1"
  101506. //Split the data for getting position and uv
  101507. var point = triangles[k].split("/"); // ["1", "1"]
  101508. //Set position indice
  101509. var indicePositionFromObj = parseInt(point[0]) - 1;
  101510. //Set uv indice
  101511. var indiceUvsFromObj = parseInt(point[1]) - 1;
  101512. setData(indicePositionFromObj, indiceUvsFromObj, 0, //Default value for normals
  101513. positions[indicePositionFromObj], //Get the values for each element
  101514. uvs[indiceUvsFromObj], BABYLON.Vector3.Up() //Default value for normals
  101515. );
  101516. }
  101517. //Reset variable for the next line
  101518. triangles = [];
  101519. };
  101520. /**
  101521. * Create triangles and push the data for each polygon for the pattern 3
  101522. * In this pattern we get vertice positions, uvs and normals
  101523. * @param face
  101524. * @param v
  101525. */
  101526. var setDataForCurrentFaceWithPattern3 = function (face, v) {
  101527. //Get the indices of triangles for each polygon
  101528. getTriangles(face, v);
  101529. for (var k = 0; k < triangles.length; k++) {
  101530. //triangle[k] = "1/1/1"
  101531. //Split the data for getting position, uv, and normals
  101532. var point = triangles[k].split("/"); // ["1", "1", "1"]
  101533. // Set position indice
  101534. var indicePositionFromObj = parseInt(point[0]) - 1;
  101535. // Set uv indice
  101536. var indiceUvsFromObj = parseInt(point[1]) - 1;
  101537. // Set normal indice
  101538. var indiceNormalFromObj = parseInt(point[2]) - 1;
  101539. setData(indicePositionFromObj, indiceUvsFromObj, indiceNormalFromObj, positions[indicePositionFromObj], uvs[indiceUvsFromObj], normals[indiceNormalFromObj] //Set the vector for each component
  101540. );
  101541. }
  101542. //Reset variable for the next line
  101543. triangles = [];
  101544. };
  101545. /**
  101546. * Create triangles and push the data for each polygon for the pattern 4
  101547. * In this pattern we get vertice positions and normals
  101548. * @param face
  101549. * @param v
  101550. */
  101551. var setDataForCurrentFaceWithPattern4 = function (face, v) {
  101552. getTriangles(face, v);
  101553. for (var k = 0; k < triangles.length; k++) {
  101554. //triangle[k] = "1//1"
  101555. //Split the data for getting position and normals
  101556. var point = triangles[k].split("//"); // ["1", "1"]
  101557. // We check indices, and normals
  101558. var indicePositionFromObj = parseInt(point[0]) - 1;
  101559. var indiceNormalFromObj = parseInt(point[1]) - 1;
  101560. setData(indicePositionFromObj, 1, //Default value for uv
  101561. indiceNormalFromObj, positions[indicePositionFromObj], //Get each vector of data
  101562. BABYLON.Vector2.Zero(), normals[indiceNormalFromObj]);
  101563. }
  101564. //Reset variable for the next line
  101565. triangles = [];
  101566. };
  101567. var addPreviousObjMesh = function () {
  101568. //Check if it is not the first mesh. Otherwise we don't have data.
  101569. if (meshesFromObj.length > 0) {
  101570. //Get the previous mesh for applying the data about the faces
  101571. //=> in obj file, faces definition append after the name of the mesh
  101572. handledMesh = meshesFromObj[meshesFromObj.length - 1];
  101573. //Set the data into Array for the mesh
  101574. unwrapData();
  101575. // Reverse tab. Otherwise face are displayed in the wrong sens
  101576. indicesForBabylon.reverse();
  101577. //Set the information for the mesh
  101578. //Slice the array to avoid rewriting because of the fact this is the same var which be rewrited
  101579. handledMesh.indices = indicesForBabylon.slice();
  101580. handledMesh.positions = unwrappedPositionsForBabylon.slice();
  101581. handledMesh.normals = unwrappedNormalsForBabylon.slice();
  101582. handledMesh.uvs = unwrappedUVForBabylon.slice();
  101583. //Reset the array for the next mesh
  101584. indicesForBabylon = [];
  101585. unwrappedPositionsForBabylon = [];
  101586. unwrappedNormalsForBabylon = [];
  101587. unwrappedUVForBabylon = [];
  101588. }
  101589. };
  101590. //Main function
  101591. //Split the file into lines
  101592. var lines = data.split('\n');
  101593. //Look at each line
  101594. for (var i = 0; i < lines.length; i++) {
  101595. var line = lines[i].trim();
  101596. var result;
  101597. //Comment or newLine
  101598. if (line.length === 0 || line.charAt(0) === '#') {
  101599. continue;
  101600. //Get information about one position possible for the vertices
  101601. }
  101602. else if ((result = this.vertexPattern.exec(line)) !== null) {
  101603. //Create a Vector3 with the position x, y, z
  101604. //Value of result:
  101605. // ["v 1.0 2.0 3.0", "1.0", "2.0", "3.0"]
  101606. //Add the Vector in the list of positions
  101607. positions.push(new BABYLON.Vector3(parseFloat(result[1]), parseFloat(result[2]), parseFloat(result[3])));
  101608. }
  101609. else if ((result = this.normalPattern.exec(line)) !== null) {
  101610. //Create a Vector3 with the normals x, y, z
  101611. //Value of result
  101612. // ["vn 1.0 2.0 3.0", "1.0", "2.0", "3.0"]
  101613. //Add the Vector in the list of normals
  101614. normals.push(new BABYLON.Vector3(parseFloat(result[1]), parseFloat(result[2]), parseFloat(result[3])));
  101615. }
  101616. else if ((result = this.uvPattern.exec(line)) !== null) {
  101617. //Create a Vector2 with the normals u, v
  101618. //Value of result
  101619. // ["vt 0.1 0.2 0.3", "0.1", "0.2"]
  101620. //Add the Vector in the list of uvs
  101621. uvs.push(new BABYLON.Vector2(parseFloat(result[1]), parseFloat(result[2])));
  101622. //Identify patterns of faces
  101623. //Face could be defined in different type of pattern
  101624. }
  101625. else if ((result = this.facePattern3.exec(line)) !== null) {
  101626. //Value of result:
  101627. //["f 1/1/1 2/2/2 3/3/3", "1/1/1 2/2/2 3/3/3"...]
  101628. //Set the data for this face
  101629. setDataForCurrentFaceWithPattern3(result[1].trim().split(" "), // ["1/1/1", "2/2/2", "3/3/3"]
  101630. 1);
  101631. }
  101632. else if ((result = this.facePattern4.exec(line)) !== null) {
  101633. //Value of result:
  101634. //["f 1//1 2//2 3//3", "1//1 2//2 3//3"...]
  101635. //Set the data for this face
  101636. setDataForCurrentFaceWithPattern4(result[1].trim().split(" "), // ["1//1", "2//2", "3//3"]
  101637. 1);
  101638. }
  101639. else if ((result = this.facePattern2.exec(line)) !== null) {
  101640. //Value of result:
  101641. //["f 1/1 2/2 3/3", "1/1 2/2 3/3"...]
  101642. //Set the data for this face
  101643. setDataForCurrentFaceWithPattern2(result[1].trim().split(" "), // ["1/1", "2/2", "3/3"]
  101644. 1);
  101645. }
  101646. else if ((result = this.facePattern1.exec(line)) !== null) {
  101647. //Value of result
  101648. //["f 1 2 3", "1 2 3"...]
  101649. //Set the data for this face
  101650. setDataForCurrentFaceWithPattern1(result[1].trim().split(" "), // ["1", "2", "3"]
  101651. 1);
  101652. //Define a mesh or an object
  101653. //Each time this keyword is analysed, create a new Object with all data for creating a babylonMesh
  101654. }
  101655. else if (this.group.test(line) || this.obj.test(line)) {
  101656. //Create a new mesh corresponding to the name of the group.
  101657. //Definition of the mesh
  101658. var objMesh =
  101659. //Set the name of the current obj mesh
  101660. {
  101661. name: line.substring(2).trim(),
  101662. indices: undefined,
  101663. positions: undefined,
  101664. normals: undefined,
  101665. uvs: undefined,
  101666. materialName: ""
  101667. };
  101668. addPreviousObjMesh();
  101669. //Push the last mesh created with only the name
  101670. meshesFromObj.push(objMesh);
  101671. //Set this variable to indicate that now meshesFromObj has objects defined inside
  101672. hasMeshes = true;
  101673. isFirstMaterial = true;
  101674. increment = 1;
  101675. //Keyword for applying a material
  101676. }
  101677. else if (this.usemtl.test(line)) {
  101678. //Get the name of the material
  101679. materialNameFromObj = line.substring(7).trim();
  101680. //If this new material is in the same mesh
  101681. if (!isFirstMaterial) {
  101682. //Set the data for the previous mesh
  101683. addPreviousObjMesh();
  101684. //Create a new mesh
  101685. var objMesh =
  101686. //Set the name of the current obj mesh
  101687. {
  101688. name: objMeshName + "_mm" + increment.toString(),
  101689. indices: undefined,
  101690. positions: undefined,
  101691. normals: undefined,
  101692. uvs: undefined,
  101693. materialName: materialNameFromObj
  101694. };
  101695. increment++;
  101696. //If meshes are already defined
  101697. meshesFromObj.push(objMesh);
  101698. }
  101699. //Set the material name if the previous line define a mesh
  101700. if (hasMeshes && isFirstMaterial) {
  101701. //Set the material name to the previous mesh (1 material per mesh)
  101702. meshesFromObj[meshesFromObj.length - 1].materialName = materialNameFromObj;
  101703. isFirstMaterial = false;
  101704. }
  101705. //Keyword for loading the mtl file
  101706. }
  101707. else if (this.mtllib.test(line)) {
  101708. //Get the name of mtl file
  101709. fileToLoad = line.substring(7).trim();
  101710. //Apply smoothing
  101711. }
  101712. else if (this.smooth.test(line)) {
  101713. // smooth shading => apply smoothing
  101714. //Toda y I don't know it work with babylon and with obj.
  101715. //With the obj file an integer is set
  101716. }
  101717. else {
  101718. //If there is another possibility
  101719. console.log("Unhandled expression at line : " + line);
  101720. }
  101721. }
  101722. //At the end of the file, add the last mesh into the meshesFromObj array
  101723. if (hasMeshes) {
  101724. //Set the data for the last mesh
  101725. handledMesh = meshesFromObj[meshesFromObj.length - 1];
  101726. //Reverse indices for displaying faces in the good sens
  101727. indicesForBabylon.reverse();
  101728. //Get the good array
  101729. unwrapData();
  101730. //Set array
  101731. handledMesh.indices = indicesForBabylon;
  101732. handledMesh.positions = unwrappedPositionsForBabylon;
  101733. handledMesh.normals = unwrappedNormalsForBabylon;
  101734. handledMesh.uvs = unwrappedUVForBabylon;
  101735. }
  101736. //If any o or g keyword found, create a mesj with a random id
  101737. if (!hasMeshes) {
  101738. // reverse tab of indices
  101739. indicesForBabylon.reverse();
  101740. //Get positions normals uvs
  101741. unwrapData();
  101742. //Set data for one mesh
  101743. meshesFromObj.push({
  101744. name: BABYLON.Geometry.RandomId(),
  101745. indices: indicesForBabylon,
  101746. positions: unwrappedPositionsForBabylon,
  101747. normals: unwrappedNormalsForBabylon,
  101748. uvs: unwrappedUVForBabylon,
  101749. materialName: materialNameFromObj
  101750. });
  101751. }
  101752. //Create a BABYLON.Mesh list
  101753. var babylonMeshesArray = []; //The mesh for babylon
  101754. var materialToUse = new Array();
  101755. //Set data for each mesh
  101756. for (var j = 0; j < meshesFromObj.length; j++) {
  101757. //check meshesNames (stlFileLoader)
  101758. if (meshesNames && meshesFromObj[j].name) {
  101759. if (meshesNames instanceof Array) {
  101760. if (meshesNames.indexOf(meshesFromObj[j].name) == -1) {
  101761. continue;
  101762. }
  101763. }
  101764. else {
  101765. if (meshesFromObj[j].name !== meshesNames) {
  101766. continue;
  101767. }
  101768. }
  101769. }
  101770. //Get the current mesh
  101771. //Set the data with VertexBuffer for each mesh
  101772. handledMesh = meshesFromObj[j];
  101773. //Create a BABYLON.Mesh with the name of the obj mesh
  101774. var babylonMesh = new BABYLON.Mesh(meshesFromObj[j].name, scene);
  101775. //Push the name of the material to an array
  101776. //This is indispensable for the importMesh function
  101777. materialToUse.push(meshesFromObj[j].materialName);
  101778. var vertexData = new BABYLON.VertexData(); //The container for the values
  101779. //Set the data for the babylonMesh
  101780. vertexData.positions = handledMesh.positions;
  101781. vertexData.normals = handledMesh.normals;
  101782. vertexData.uvs = handledMesh.uvs;
  101783. vertexData.indices = handledMesh.indices;
  101784. //Set the data from the VertexBuffer to the current BABYLON.Mesh
  101785. vertexData.applyToMesh(babylonMesh);
  101786. if (OBJFileLoader.INVERT_Y) {
  101787. babylonMesh.scaling.y *= -1;
  101788. }
  101789. //Push the mesh into an array
  101790. babylonMeshesArray.push(babylonMesh);
  101791. }
  101792. //load the materials
  101793. //Check if we have a file to load
  101794. if (fileToLoad !== "") {
  101795. //Load the file synchronously
  101796. this._loadMTL(fileToLoad, rootUrl, function (dataLoaded) {
  101797. //Create materials thanks MTLLoader function
  101798. materialsFromMTLFile.parseMTL(scene, dataLoaded, rootUrl);
  101799. //Look at each material loaded in the mtl file
  101800. for (var n = 0; n < materialsFromMTLFile.materials.length; n++) {
  101801. //Three variables to get all meshes with the same material
  101802. var startIndex = 0;
  101803. var _indices = [];
  101804. var _index;
  101805. //The material from MTL file is used in the meshes loaded
  101806. //Push the indice in an array
  101807. //Check if the material is not used for another mesh
  101808. while ((_index = materialToUse.indexOf(materialsFromMTLFile.materials[n].name, startIndex)) > -1) {
  101809. _indices.push(_index);
  101810. startIndex = _index + 1;
  101811. }
  101812. //If the material is not used dispose it
  101813. if (_index == -1 && _indices.length == 0) {
  101814. //If the material is not needed, remove it
  101815. materialsFromMTLFile.materials[n].dispose();
  101816. }
  101817. else {
  101818. for (var o = 0; o < _indices.length; o++) {
  101819. //Apply the material to the BABYLON.Mesh for each mesh with the material
  101820. babylonMeshesArray[_indices[o]].material = materialsFromMTLFile.materials[n];
  101821. }
  101822. }
  101823. }
  101824. });
  101825. }
  101826. //Return an array with all BABYLON.Mesh
  101827. return babylonMeshesArray;
  101828. };
  101829. OBJFileLoader.OPTIMIZE_WITH_UV = false;
  101830. OBJFileLoader.INVERT_Y = false;
  101831. return OBJFileLoader;
  101832. }());
  101833. BABYLON.OBJFileLoader = OBJFileLoader;
  101834. if (BABYLON.SceneLoader) {
  101835. //Add this loader into the register plugin
  101836. BABYLON.SceneLoader.RegisterPlugin(new OBJFileLoader());
  101837. }
  101838. })(BABYLON || (BABYLON = {}));
  101839. //# sourceMappingURL=babylon.objFileLoader.js.map
  101840. var BABYLON;
  101841. (function (BABYLON) {
  101842. /**
  101843. * Mode that determines the coordinate system to use.
  101844. */
  101845. var GLTFLoaderCoordinateSystemMode;
  101846. (function (GLTFLoaderCoordinateSystemMode) {
  101847. /**
  101848. * Automatically convert the glTF right-handed data to the appropriate system based on the current coordinate system mode of the scene.
  101849. */
  101850. GLTFLoaderCoordinateSystemMode[GLTFLoaderCoordinateSystemMode["AUTO"] = 0] = "AUTO";
  101851. /**
  101852. * Sets the useRightHandedSystem flag on the scene.
  101853. */
  101854. GLTFLoaderCoordinateSystemMode[GLTFLoaderCoordinateSystemMode["FORCE_RIGHT_HANDED"] = 1] = "FORCE_RIGHT_HANDED";
  101855. })(GLTFLoaderCoordinateSystemMode = BABYLON.GLTFLoaderCoordinateSystemMode || (BABYLON.GLTFLoaderCoordinateSystemMode = {}));
  101856. /**
  101857. * Mode that determines what animations will start.
  101858. */
  101859. var GLTFLoaderAnimationStartMode;
  101860. (function (GLTFLoaderAnimationStartMode) {
  101861. /**
  101862. * No animation will start.
  101863. */
  101864. GLTFLoaderAnimationStartMode[GLTFLoaderAnimationStartMode["NONE"] = 0] = "NONE";
  101865. /**
  101866. * The first animation will start.
  101867. */
  101868. GLTFLoaderAnimationStartMode[GLTFLoaderAnimationStartMode["FIRST"] = 1] = "FIRST";
  101869. /**
  101870. * All animations will start.
  101871. */
  101872. GLTFLoaderAnimationStartMode[GLTFLoaderAnimationStartMode["ALL"] = 2] = "ALL";
  101873. })(GLTFLoaderAnimationStartMode = BABYLON.GLTFLoaderAnimationStartMode || (BABYLON.GLTFLoaderAnimationStartMode = {}));
  101874. /**
  101875. * Loader state.
  101876. */
  101877. var GLTFLoaderState;
  101878. (function (GLTFLoaderState) {
  101879. /**
  101880. * The asset is loading.
  101881. */
  101882. GLTFLoaderState[GLTFLoaderState["LOADING"] = 0] = "LOADING";
  101883. /**
  101884. * The asset is ready for rendering.
  101885. */
  101886. GLTFLoaderState[GLTFLoaderState["READY"] = 1] = "READY";
  101887. /**
  101888. * The asset is completely loaded.
  101889. */
  101890. GLTFLoaderState[GLTFLoaderState["COMPLETE"] = 2] = "COMPLETE";
  101891. })(GLTFLoaderState = BABYLON.GLTFLoaderState || (BABYLON.GLTFLoaderState = {}));
  101892. /**
  101893. * File loader for loading glTF files into a scene.
  101894. */
  101895. var GLTFFileLoader = /** @class */ (function () {
  101896. function GLTFFileLoader() {
  101897. // #region Common options
  101898. /**
  101899. * Raised when the asset has been parsed
  101900. */
  101901. this.onParsedObservable = new BABYLON.Observable();
  101902. // #endregion
  101903. // #region V2 options
  101904. /**
  101905. * The coordinate system mode. Defaults to AUTO.
  101906. */
  101907. this.coordinateSystemMode = GLTFLoaderCoordinateSystemMode.AUTO;
  101908. /**
  101909. * The animation start mode. Defaults to FIRST.
  101910. */
  101911. this.animationStartMode = GLTFLoaderAnimationStartMode.FIRST;
  101912. /**
  101913. * Defines if the loader should compile materials before raising the success callback. Defaults to false.
  101914. */
  101915. this.compileMaterials = false;
  101916. /**
  101917. * Defines if the loader should also compile materials with clip planes. Defaults to false.
  101918. */
  101919. this.useClipPlane = false;
  101920. /**
  101921. * Defines if the loader should compile shadow generators before raising the success callback. Defaults to false.
  101922. */
  101923. this.compileShadowGenerators = false;
  101924. /**
  101925. * Function called before loading a url referenced by the asset.
  101926. */
  101927. this.preprocessUrlAsync = function (url) { return Promise.resolve(url); };
  101928. /**
  101929. * Observable raised when the loader creates a mesh after parsing the glTF properties of the mesh.
  101930. */
  101931. this.onMeshLoadedObservable = new BABYLON.Observable();
  101932. /**
  101933. * Observable raised when the loader creates a texture after parsing the glTF properties of the texture.
  101934. */
  101935. this.onTextureLoadedObservable = new BABYLON.Observable();
  101936. /**
  101937. * Observable raised when the loader creates a material after parsing the glTF properties of the material.
  101938. */
  101939. this.onMaterialLoadedObservable = new BABYLON.Observable();
  101940. /**
  101941. * Observable raised when the loader creates a camera after parsing the glTF properties of the camera.
  101942. */
  101943. this.onCameraLoadedObservable = new BABYLON.Observable();
  101944. /**
  101945. * Observable raised when the asset is completely loaded, immediately before the loader is disposed.
  101946. * For assets with LODs, raised when all of the LODs are complete.
  101947. * For assets without LODs, raised when the model is complete, immediately after the loader resolves the returned promise.
  101948. */
  101949. this.onCompleteObservable = new BABYLON.Observable();
  101950. /**
  101951. * Observable raised after the loader is disposed.
  101952. */
  101953. this.onDisposeObservable = new BABYLON.Observable();
  101954. /**
  101955. * Observable raised after a loader extension is created.
  101956. * Set additional options for a loader extension in this event.
  101957. */
  101958. this.onExtensionLoadedObservable = new BABYLON.Observable();
  101959. // #endregion
  101960. this._loader = null;
  101961. /**
  101962. * Name of the loader ("gltf")
  101963. */
  101964. this.name = "gltf";
  101965. /**
  101966. * Supported file extensions of the loader (.gltf, .glb)
  101967. */
  101968. this.extensions = {
  101969. ".gltf": { isBinary: false },
  101970. ".glb": { isBinary: true }
  101971. };
  101972. }
  101973. Object.defineProperty(GLTFFileLoader.prototype, "onParsed", {
  101974. /**
  101975. * Raised when the asset has been parsed
  101976. */
  101977. set: function (callback) {
  101978. if (this._onParsedObserver) {
  101979. this.onParsedObservable.remove(this._onParsedObserver);
  101980. }
  101981. this._onParsedObserver = this.onParsedObservable.add(callback);
  101982. },
  101983. enumerable: true,
  101984. configurable: true
  101985. });
  101986. Object.defineProperty(GLTFFileLoader.prototype, "onMeshLoaded", {
  101987. /**
  101988. * Callback raised when the loader creates a mesh after parsing the glTF properties of the mesh.
  101989. */
  101990. set: function (callback) {
  101991. if (this._onMeshLoadedObserver) {
  101992. this.onMeshLoadedObservable.remove(this._onMeshLoadedObserver);
  101993. }
  101994. this._onMeshLoadedObserver = this.onMeshLoadedObservable.add(callback);
  101995. },
  101996. enumerable: true,
  101997. configurable: true
  101998. });
  101999. Object.defineProperty(GLTFFileLoader.prototype, "onTextureLoaded", {
  102000. /**
  102001. * Callback raised when the loader creates a texture after parsing the glTF properties of the texture.
  102002. */
  102003. set: function (callback) {
  102004. if (this._onTextureLoadedObserver) {
  102005. this.onTextureLoadedObservable.remove(this._onTextureLoadedObserver);
  102006. }
  102007. this._onTextureLoadedObserver = this.onTextureLoadedObservable.add(callback);
  102008. },
  102009. enumerable: true,
  102010. configurable: true
  102011. });
  102012. Object.defineProperty(GLTFFileLoader.prototype, "onMaterialLoaded", {
  102013. /**
  102014. * Callback raised when the loader creates a material after parsing the glTF properties of the material.
  102015. */
  102016. set: function (callback) {
  102017. if (this._onMaterialLoadedObserver) {
  102018. this.onMaterialLoadedObservable.remove(this._onMaterialLoadedObserver);
  102019. }
  102020. this._onMaterialLoadedObserver = this.onMaterialLoadedObservable.add(callback);
  102021. },
  102022. enumerable: true,
  102023. configurable: true
  102024. });
  102025. Object.defineProperty(GLTFFileLoader.prototype, "onCameraLoaded", {
  102026. /**
  102027. * Callback raised when the loader creates a camera after parsing the glTF properties of the camera.
  102028. */
  102029. set: function (callback) {
  102030. if (this._onCameraLoadedObserver) {
  102031. this.onCameraLoadedObservable.remove(this._onCameraLoadedObserver);
  102032. }
  102033. this._onCameraLoadedObserver = this.onCameraLoadedObservable.add(callback);
  102034. },
  102035. enumerable: true,
  102036. configurable: true
  102037. });
  102038. Object.defineProperty(GLTFFileLoader.prototype, "onComplete", {
  102039. /**
  102040. * Callback raised when the asset is completely loaded, immediately before the loader is disposed.
  102041. */
  102042. set: function (callback) {
  102043. if (this._onCompleteObserver) {
  102044. this.onCompleteObservable.remove(this._onCompleteObserver);
  102045. }
  102046. this._onCompleteObserver = this.onCompleteObservable.add(callback);
  102047. },
  102048. enumerable: true,
  102049. configurable: true
  102050. });
  102051. Object.defineProperty(GLTFFileLoader.prototype, "onDispose", {
  102052. /**
  102053. * Callback raised after the loader is disposed.
  102054. */
  102055. set: function (callback) {
  102056. if (this._onDisposeObserver) {
  102057. this.onDisposeObservable.remove(this._onDisposeObserver);
  102058. }
  102059. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  102060. },
  102061. enumerable: true,
  102062. configurable: true
  102063. });
  102064. Object.defineProperty(GLTFFileLoader.prototype, "onExtensionLoaded", {
  102065. /**
  102066. * Callback raised after a loader extension is created.
  102067. */
  102068. set: function (callback) {
  102069. if (this._onExtensionLoadedObserver) {
  102070. this.onExtensionLoadedObservable.remove(this._onExtensionLoadedObserver);
  102071. }
  102072. this._onExtensionLoadedObserver = this.onExtensionLoadedObservable.add(callback);
  102073. },
  102074. enumerable: true,
  102075. configurable: true
  102076. });
  102077. /**
  102078. * Returns a promise that resolves when the asset is completely loaded.
  102079. * @returns a promise that resolves when the asset is completely loaded.
  102080. */
  102081. GLTFFileLoader.prototype.whenCompleteAsync = function () {
  102082. var _this = this;
  102083. return new Promise(function (resolve) {
  102084. _this.onCompleteObservable.add(function () {
  102085. resolve();
  102086. }, undefined, undefined, undefined, true);
  102087. });
  102088. };
  102089. Object.defineProperty(GLTFFileLoader.prototype, "loaderState", {
  102090. /**
  102091. * The loader state or null if the loader is not active.
  102092. */
  102093. get: function () {
  102094. return this._loader ? this._loader.state : null;
  102095. },
  102096. enumerable: true,
  102097. configurable: true
  102098. });
  102099. /**
  102100. * Disposes the loader, releases resources during load, and cancels any outstanding requests.
  102101. */
  102102. GLTFFileLoader.prototype.dispose = function () {
  102103. if (this._loader) {
  102104. this._loader.dispose();
  102105. this._loader = null;
  102106. }
  102107. this.preprocessUrlAsync = function (url) { return Promise.resolve(url); };
  102108. this.onMeshLoadedObservable.clear();
  102109. this.onTextureLoadedObservable.clear();
  102110. this.onMaterialLoadedObservable.clear();
  102111. this.onCameraLoadedObservable.clear();
  102112. this.onCompleteObservable.clear();
  102113. this.onExtensionLoadedObservable.clear();
  102114. this.onDisposeObservable.notifyObservers(this);
  102115. this.onDisposeObservable.clear();
  102116. };
  102117. /**
  102118. * Imports one or more meshes from the loaded glTF data and adds them to the scene
  102119. * @param meshesNames a string or array of strings of the mesh names that should be loaded from the file
  102120. * @param scene the scene the meshes should be added to
  102121. * @param data the glTF data to load
  102122. * @param rootUrl root url to load from
  102123. * @param onProgress event that fires when loading progress has occured
  102124. * @returns a promise containg the loaded meshes, particles, skeletons and animations
  102125. */
  102126. GLTFFileLoader.prototype.importMeshAsync = function (meshesNames, scene, data, rootUrl, onProgress) {
  102127. var _this = this;
  102128. return Promise.resolve().then(function () {
  102129. var loaderData = _this._parse(data);
  102130. _this._loader = _this._getLoader(loaderData);
  102131. return _this._loader.importMeshAsync(meshesNames, scene, loaderData, rootUrl, onProgress);
  102132. });
  102133. };
  102134. /**
  102135. * Imports all objects from the loaded glTF data and adds them to the scene
  102136. * @param scene the scene the objects should be added to
  102137. * @param data the glTF data to load
  102138. * @param rootUrl root url to load from
  102139. * @param onProgress event that fires when loading progress has occured
  102140. * @returns a promise which completes when objects have been loaded to the scene
  102141. */
  102142. GLTFFileLoader.prototype.loadAsync = function (scene, data, rootUrl, onProgress) {
  102143. var _this = this;
  102144. return Promise.resolve().then(function () {
  102145. var loaderData = _this._parse(data);
  102146. _this._loader = _this._getLoader(loaderData);
  102147. return _this._loader.loadAsync(scene, loaderData, rootUrl, onProgress);
  102148. });
  102149. };
  102150. /**
  102151. * Load into an asset container.
  102152. * @param scene The scene to load into
  102153. * @param data The data to import
  102154. * @param rootUrl The root url for scene and resources
  102155. * @param onProgress The callback when the load progresses
  102156. * @returns The loaded asset container
  102157. */
  102158. GLTFFileLoader.prototype.loadAssetContainerAsync = function (scene, data, rootUrl, onProgress) {
  102159. var _this = this;
  102160. return Promise.resolve().then(function () {
  102161. var loaderData = _this._parse(data);
  102162. _this._loader = _this._getLoader(loaderData);
  102163. return _this._loader.importMeshAsync(null, scene, loaderData, rootUrl, onProgress).then(function (result) {
  102164. var container = new BABYLON.AssetContainer(scene);
  102165. Array.prototype.push.apply(container.meshes, result.meshes);
  102166. Array.prototype.push.apply(container.particleSystems, result.particleSystems);
  102167. Array.prototype.push.apply(container.skeletons, result.skeletons);
  102168. Array.prototype.push.apply(container.animationGroups, result.animationGroups);
  102169. container.removeAllFromScene();
  102170. return container;
  102171. });
  102172. });
  102173. };
  102174. /**
  102175. * If the data string can be loaded directly.
  102176. * @param data string contianing the file data
  102177. * @returns if the data can be loaded directly
  102178. */
  102179. GLTFFileLoader.prototype.canDirectLoad = function (data) {
  102180. return ((data.indexOf("scene") !== -1) && (data.indexOf("node") !== -1));
  102181. };
  102182. /**
  102183. * Instantiates a glTF file loader plugin.
  102184. * @returns the created plugin
  102185. */
  102186. GLTFFileLoader.prototype.createPlugin = function () {
  102187. return new GLTFFileLoader();
  102188. };
  102189. GLTFFileLoader.prototype._parse = function (data) {
  102190. var parsedData;
  102191. if (data instanceof ArrayBuffer) {
  102192. parsedData = GLTFFileLoader._parseBinary(data);
  102193. }
  102194. else {
  102195. parsedData = {
  102196. json: JSON.parse(data),
  102197. bin: null
  102198. };
  102199. }
  102200. this.onParsedObservable.notifyObservers(parsedData);
  102201. this.onParsedObservable.clear();
  102202. return parsedData;
  102203. };
  102204. GLTFFileLoader.prototype._getLoader = function (loaderData) {
  102205. var _this = this;
  102206. var loaderVersion = { major: 2, minor: 0 };
  102207. var asset = loaderData.json.asset || {};
  102208. var version = GLTFFileLoader._parseVersion(asset.version);
  102209. if (!version) {
  102210. throw new Error("Invalid version: " + asset.version);
  102211. }
  102212. if (asset.minVersion !== undefined) {
  102213. var minVersion = GLTFFileLoader._parseVersion(asset.minVersion);
  102214. if (!minVersion) {
  102215. throw new Error("Invalid minimum version: " + asset.minVersion);
  102216. }
  102217. if (GLTFFileLoader._compareVersion(minVersion, loaderVersion) > 0) {
  102218. throw new Error("Incompatible minimum version: " + asset.minVersion);
  102219. }
  102220. }
  102221. var createLoaders = {
  102222. 1: GLTFFileLoader.CreateGLTFLoaderV1,
  102223. 2: GLTFFileLoader.CreateGLTFLoaderV2
  102224. };
  102225. var createLoader = createLoaders[version.major];
  102226. if (!createLoader) {
  102227. throw new Error("Unsupported version: " + asset.version);
  102228. }
  102229. var loader = createLoader();
  102230. loader.coordinateSystemMode = this.coordinateSystemMode;
  102231. loader.animationStartMode = this.animationStartMode;
  102232. loader.compileMaterials = this.compileMaterials;
  102233. loader.useClipPlane = this.useClipPlane;
  102234. loader.compileShadowGenerators = this.compileShadowGenerators;
  102235. loader.preprocessUrlAsync = this.preprocessUrlAsync;
  102236. loader.onMeshLoadedObservable.add(function (mesh) { return _this.onMeshLoadedObservable.notifyObservers(mesh); });
  102237. loader.onTextureLoadedObservable.add(function (texture) { return _this.onTextureLoadedObservable.notifyObservers(texture); });
  102238. loader.onMaterialLoadedObservable.add(function (material) { return _this.onMaterialLoadedObservable.notifyObservers(material); });
  102239. loader.onCameraLoadedObservable.add(function (camera) { return _this.onCameraLoadedObservable.notifyObservers(camera); });
  102240. loader.onExtensionLoadedObservable.add(function (extension) {
  102241. _this.onExtensionLoadedObservable.notifyObservers(extension);
  102242. _this.onExtensionLoadedObservable.clear();
  102243. });
  102244. loader.onCompleteObservable.add(function () {
  102245. _this.onMeshLoadedObservable.clear();
  102246. _this.onTextureLoadedObservable.clear();
  102247. _this.onMaterialLoadedObservable.clear();
  102248. _this.onCameraLoadedObservable.clear();
  102249. _this.onCompleteObservable.notifyObservers(_this);
  102250. _this.onCompleteObservable.clear();
  102251. });
  102252. return loader;
  102253. };
  102254. GLTFFileLoader._parseBinary = function (data) {
  102255. var Binary = {
  102256. Magic: 0x46546C67
  102257. };
  102258. var binaryReader = new BinaryReader(data);
  102259. var magic = binaryReader.readUint32();
  102260. if (magic !== Binary.Magic) {
  102261. throw new Error("Unexpected magic: " + magic);
  102262. }
  102263. var version = binaryReader.readUint32();
  102264. switch (version) {
  102265. case 1: return GLTFFileLoader._parseV1(binaryReader);
  102266. case 2: return GLTFFileLoader._parseV2(binaryReader);
  102267. }
  102268. throw new Error("Unsupported version: " + version);
  102269. };
  102270. GLTFFileLoader._parseV1 = function (binaryReader) {
  102271. var ContentFormat = {
  102272. JSON: 0
  102273. };
  102274. var length = binaryReader.readUint32();
  102275. if (length != binaryReader.getLength()) {
  102276. throw new Error("Length in header does not match actual data length: " + length + " != " + binaryReader.getLength());
  102277. }
  102278. var contentLength = binaryReader.readUint32();
  102279. var contentFormat = binaryReader.readUint32();
  102280. var content;
  102281. switch (contentFormat) {
  102282. case ContentFormat.JSON: {
  102283. content = JSON.parse(GLTFFileLoader._decodeBufferToText(binaryReader.readUint8Array(contentLength)));
  102284. break;
  102285. }
  102286. default: {
  102287. throw new Error("Unexpected content format: " + contentFormat);
  102288. }
  102289. }
  102290. var bytesRemaining = binaryReader.getLength() - binaryReader.getPosition();
  102291. var body = binaryReader.readUint8Array(bytesRemaining);
  102292. return {
  102293. json: content,
  102294. bin: body
  102295. };
  102296. };
  102297. GLTFFileLoader._parseV2 = function (binaryReader) {
  102298. var ChunkFormat = {
  102299. JSON: 0x4E4F534A,
  102300. BIN: 0x004E4942
  102301. };
  102302. var length = binaryReader.readUint32();
  102303. if (length !== binaryReader.getLength()) {
  102304. throw new Error("Length in header does not match actual data length: " + length + " != " + binaryReader.getLength());
  102305. }
  102306. // JSON chunk
  102307. var chunkLength = binaryReader.readUint32();
  102308. var chunkFormat = binaryReader.readUint32();
  102309. if (chunkFormat !== ChunkFormat.JSON) {
  102310. throw new Error("First chunk format is not JSON");
  102311. }
  102312. var json = JSON.parse(GLTFFileLoader._decodeBufferToText(binaryReader.readUint8Array(chunkLength)));
  102313. // Look for BIN chunk
  102314. var bin = null;
  102315. while (binaryReader.getPosition() < binaryReader.getLength()) {
  102316. var chunkLength_1 = binaryReader.readUint32();
  102317. var chunkFormat_1 = binaryReader.readUint32();
  102318. switch (chunkFormat_1) {
  102319. case ChunkFormat.JSON: {
  102320. throw new Error("Unexpected JSON chunk");
  102321. }
  102322. case ChunkFormat.BIN: {
  102323. bin = binaryReader.readUint8Array(chunkLength_1);
  102324. break;
  102325. }
  102326. default: {
  102327. // ignore unrecognized chunkFormat
  102328. binaryReader.skipBytes(chunkLength_1);
  102329. break;
  102330. }
  102331. }
  102332. }
  102333. return {
  102334. json: json,
  102335. bin: bin
  102336. };
  102337. };
  102338. GLTFFileLoader._parseVersion = function (version) {
  102339. if (version === "1.0" || version === "1.0.1") {
  102340. return {
  102341. major: 1,
  102342. minor: 0
  102343. };
  102344. }
  102345. var match = (version + "").match(/^(\d+)\.(\d+)/);
  102346. if (!match) {
  102347. return null;
  102348. }
  102349. return {
  102350. major: parseInt(match[1]),
  102351. minor: parseInt(match[2])
  102352. };
  102353. };
  102354. GLTFFileLoader._compareVersion = function (a, b) {
  102355. if (a.major > b.major)
  102356. return 1;
  102357. if (a.major < b.major)
  102358. return -1;
  102359. if (a.minor > b.minor)
  102360. return 1;
  102361. if (a.minor < b.minor)
  102362. return -1;
  102363. return 0;
  102364. };
  102365. GLTFFileLoader._decodeBufferToText = function (buffer) {
  102366. var result = "";
  102367. var length = buffer.byteLength;
  102368. for (var i = 0; i < length; i++) {
  102369. result += String.fromCharCode(buffer[i]);
  102370. }
  102371. return result;
  102372. };
  102373. // #endregion
  102374. // #region V1 options
  102375. /**
  102376. * 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.
  102377. * Textures always loads asynchronously. For example, the success callback can compute the bounding information of the loaded meshes when incremental loading is disabled.
  102378. * Defaults to true.
  102379. */
  102380. GLTFFileLoader.IncrementalLoading = true;
  102381. /**
  102382. * Set this property to true in order to work with homogeneous coordinates, available with some converters and exporters.
  102383. * Defaults to false. See https://en.wikipedia.org/wiki/Homogeneous_coordinates.
  102384. */
  102385. GLTFFileLoader.HomogeneousCoordinates = false;
  102386. return GLTFFileLoader;
  102387. }());
  102388. BABYLON.GLTFFileLoader = GLTFFileLoader;
  102389. var BinaryReader = /** @class */ (function () {
  102390. function BinaryReader(arrayBuffer) {
  102391. this._arrayBuffer = arrayBuffer;
  102392. this._dataView = new DataView(arrayBuffer);
  102393. this._byteOffset = 0;
  102394. }
  102395. BinaryReader.prototype.getPosition = function () {
  102396. return this._byteOffset;
  102397. };
  102398. BinaryReader.prototype.getLength = function () {
  102399. return this._arrayBuffer.byteLength;
  102400. };
  102401. BinaryReader.prototype.readUint32 = function () {
  102402. var value = this._dataView.getUint32(this._byteOffset, true);
  102403. this._byteOffset += 4;
  102404. return value;
  102405. };
  102406. BinaryReader.prototype.readUint8Array = function (length) {
  102407. var value = new Uint8Array(this._arrayBuffer, this._byteOffset, length);
  102408. this._byteOffset += length;
  102409. return value;
  102410. };
  102411. BinaryReader.prototype.skipBytes = function (length) {
  102412. this._byteOffset += length;
  102413. };
  102414. return BinaryReader;
  102415. }());
  102416. if (BABYLON.SceneLoader) {
  102417. BABYLON.SceneLoader.RegisterPlugin(new GLTFFileLoader());
  102418. }
  102419. })(BABYLON || (BABYLON = {}));
  102420. //# sourceMappingURL=babylon.glTFFileLoader.js.map
  102421. var BABYLON;
  102422. (function (BABYLON) {
  102423. var GLTF1;
  102424. (function (GLTF1) {
  102425. /**
  102426. * Enums
  102427. */
  102428. var EComponentType;
  102429. (function (EComponentType) {
  102430. EComponentType[EComponentType["BYTE"] = 5120] = "BYTE";
  102431. EComponentType[EComponentType["UNSIGNED_BYTE"] = 5121] = "UNSIGNED_BYTE";
  102432. EComponentType[EComponentType["SHORT"] = 5122] = "SHORT";
  102433. EComponentType[EComponentType["UNSIGNED_SHORT"] = 5123] = "UNSIGNED_SHORT";
  102434. EComponentType[EComponentType["FLOAT"] = 5126] = "FLOAT";
  102435. })(EComponentType = GLTF1.EComponentType || (GLTF1.EComponentType = {}));
  102436. var EShaderType;
  102437. (function (EShaderType) {
  102438. EShaderType[EShaderType["FRAGMENT"] = 35632] = "FRAGMENT";
  102439. EShaderType[EShaderType["VERTEX"] = 35633] = "VERTEX";
  102440. })(EShaderType = GLTF1.EShaderType || (GLTF1.EShaderType = {}));
  102441. var EParameterType;
  102442. (function (EParameterType) {
  102443. EParameterType[EParameterType["BYTE"] = 5120] = "BYTE";
  102444. EParameterType[EParameterType["UNSIGNED_BYTE"] = 5121] = "UNSIGNED_BYTE";
  102445. EParameterType[EParameterType["SHORT"] = 5122] = "SHORT";
  102446. EParameterType[EParameterType["UNSIGNED_SHORT"] = 5123] = "UNSIGNED_SHORT";
  102447. EParameterType[EParameterType["INT"] = 5124] = "INT";
  102448. EParameterType[EParameterType["UNSIGNED_INT"] = 5125] = "UNSIGNED_INT";
  102449. EParameterType[EParameterType["FLOAT"] = 5126] = "FLOAT";
  102450. EParameterType[EParameterType["FLOAT_VEC2"] = 35664] = "FLOAT_VEC2";
  102451. EParameterType[EParameterType["FLOAT_VEC3"] = 35665] = "FLOAT_VEC3";
  102452. EParameterType[EParameterType["FLOAT_VEC4"] = 35666] = "FLOAT_VEC4";
  102453. EParameterType[EParameterType["INT_VEC2"] = 35667] = "INT_VEC2";
  102454. EParameterType[EParameterType["INT_VEC3"] = 35668] = "INT_VEC3";
  102455. EParameterType[EParameterType["INT_VEC4"] = 35669] = "INT_VEC4";
  102456. EParameterType[EParameterType["BOOL"] = 35670] = "BOOL";
  102457. EParameterType[EParameterType["BOOL_VEC2"] = 35671] = "BOOL_VEC2";
  102458. EParameterType[EParameterType["BOOL_VEC3"] = 35672] = "BOOL_VEC3";
  102459. EParameterType[EParameterType["BOOL_VEC4"] = 35673] = "BOOL_VEC4";
  102460. EParameterType[EParameterType["FLOAT_MAT2"] = 35674] = "FLOAT_MAT2";
  102461. EParameterType[EParameterType["FLOAT_MAT3"] = 35675] = "FLOAT_MAT3";
  102462. EParameterType[EParameterType["FLOAT_MAT4"] = 35676] = "FLOAT_MAT4";
  102463. EParameterType[EParameterType["SAMPLER_2D"] = 35678] = "SAMPLER_2D";
  102464. })(EParameterType = GLTF1.EParameterType || (GLTF1.EParameterType = {}));
  102465. var ETextureWrapMode;
  102466. (function (ETextureWrapMode) {
  102467. ETextureWrapMode[ETextureWrapMode["CLAMP_TO_EDGE"] = 33071] = "CLAMP_TO_EDGE";
  102468. ETextureWrapMode[ETextureWrapMode["MIRRORED_REPEAT"] = 33648] = "MIRRORED_REPEAT";
  102469. ETextureWrapMode[ETextureWrapMode["REPEAT"] = 10497] = "REPEAT";
  102470. })(ETextureWrapMode = GLTF1.ETextureWrapMode || (GLTF1.ETextureWrapMode = {}));
  102471. var ETextureFilterType;
  102472. (function (ETextureFilterType) {
  102473. ETextureFilterType[ETextureFilterType["NEAREST"] = 9728] = "NEAREST";
  102474. ETextureFilterType[ETextureFilterType["LINEAR"] = 9728] = "LINEAR";
  102475. ETextureFilterType[ETextureFilterType["NEAREST_MIPMAP_NEAREST"] = 9984] = "NEAREST_MIPMAP_NEAREST";
  102476. ETextureFilterType[ETextureFilterType["LINEAR_MIPMAP_NEAREST"] = 9985] = "LINEAR_MIPMAP_NEAREST";
  102477. ETextureFilterType[ETextureFilterType["NEAREST_MIPMAP_LINEAR"] = 9986] = "NEAREST_MIPMAP_LINEAR";
  102478. ETextureFilterType[ETextureFilterType["LINEAR_MIPMAP_LINEAR"] = 9987] = "LINEAR_MIPMAP_LINEAR";
  102479. })(ETextureFilterType = GLTF1.ETextureFilterType || (GLTF1.ETextureFilterType = {}));
  102480. var ETextureFormat;
  102481. (function (ETextureFormat) {
  102482. ETextureFormat[ETextureFormat["ALPHA"] = 6406] = "ALPHA";
  102483. ETextureFormat[ETextureFormat["RGB"] = 6407] = "RGB";
  102484. ETextureFormat[ETextureFormat["RGBA"] = 6408] = "RGBA";
  102485. ETextureFormat[ETextureFormat["LUMINANCE"] = 6409] = "LUMINANCE";
  102486. ETextureFormat[ETextureFormat["LUMINANCE_ALPHA"] = 6410] = "LUMINANCE_ALPHA";
  102487. })(ETextureFormat = GLTF1.ETextureFormat || (GLTF1.ETextureFormat = {}));
  102488. var ECullingType;
  102489. (function (ECullingType) {
  102490. ECullingType[ECullingType["FRONT"] = 1028] = "FRONT";
  102491. ECullingType[ECullingType["BACK"] = 1029] = "BACK";
  102492. ECullingType[ECullingType["FRONT_AND_BACK"] = 1032] = "FRONT_AND_BACK";
  102493. })(ECullingType = GLTF1.ECullingType || (GLTF1.ECullingType = {}));
  102494. var EBlendingFunction;
  102495. (function (EBlendingFunction) {
  102496. EBlendingFunction[EBlendingFunction["ZERO"] = 0] = "ZERO";
  102497. EBlendingFunction[EBlendingFunction["ONE"] = 1] = "ONE";
  102498. EBlendingFunction[EBlendingFunction["SRC_COLOR"] = 768] = "SRC_COLOR";
  102499. EBlendingFunction[EBlendingFunction["ONE_MINUS_SRC_COLOR"] = 769] = "ONE_MINUS_SRC_COLOR";
  102500. EBlendingFunction[EBlendingFunction["DST_COLOR"] = 774] = "DST_COLOR";
  102501. EBlendingFunction[EBlendingFunction["ONE_MINUS_DST_COLOR"] = 775] = "ONE_MINUS_DST_COLOR";
  102502. EBlendingFunction[EBlendingFunction["SRC_ALPHA"] = 770] = "SRC_ALPHA";
  102503. EBlendingFunction[EBlendingFunction["ONE_MINUS_SRC_ALPHA"] = 771] = "ONE_MINUS_SRC_ALPHA";
  102504. EBlendingFunction[EBlendingFunction["DST_ALPHA"] = 772] = "DST_ALPHA";
  102505. EBlendingFunction[EBlendingFunction["ONE_MINUS_DST_ALPHA"] = 773] = "ONE_MINUS_DST_ALPHA";
  102506. EBlendingFunction[EBlendingFunction["CONSTANT_COLOR"] = 32769] = "CONSTANT_COLOR";
  102507. EBlendingFunction[EBlendingFunction["ONE_MINUS_CONSTANT_COLOR"] = 32770] = "ONE_MINUS_CONSTANT_COLOR";
  102508. EBlendingFunction[EBlendingFunction["CONSTANT_ALPHA"] = 32771] = "CONSTANT_ALPHA";
  102509. EBlendingFunction[EBlendingFunction["ONE_MINUS_CONSTANT_ALPHA"] = 32772] = "ONE_MINUS_CONSTANT_ALPHA";
  102510. EBlendingFunction[EBlendingFunction["SRC_ALPHA_SATURATE"] = 776] = "SRC_ALPHA_SATURATE";
  102511. })(EBlendingFunction = GLTF1.EBlendingFunction || (GLTF1.EBlendingFunction = {}));
  102512. })(GLTF1 = BABYLON.GLTF1 || (BABYLON.GLTF1 = {}));
  102513. })(BABYLON || (BABYLON = {}));
  102514. //# sourceMappingURL=babylon.glTFLoaderInterfaces.js.map
  102515. var BABYLON;
  102516. (function (BABYLON) {
  102517. var GLTF1;
  102518. (function (GLTF1) {
  102519. /**
  102520. * Tokenizer. Used for shaders compatibility
  102521. * Automatically map world, view, projection, worldViewProjection, attributes and so on
  102522. */
  102523. var ETokenType;
  102524. (function (ETokenType) {
  102525. ETokenType[ETokenType["IDENTIFIER"] = 1] = "IDENTIFIER";
  102526. ETokenType[ETokenType["UNKNOWN"] = 2] = "UNKNOWN";
  102527. ETokenType[ETokenType["END_OF_INPUT"] = 3] = "END_OF_INPUT";
  102528. })(ETokenType || (ETokenType = {}));
  102529. var Tokenizer = /** @class */ (function () {
  102530. function Tokenizer(toParse) {
  102531. this._pos = 0;
  102532. this.currentToken = ETokenType.UNKNOWN;
  102533. this.currentIdentifier = "";
  102534. this.currentString = "";
  102535. this.isLetterOrDigitPattern = /^[a-zA-Z0-9]+$/;
  102536. this._toParse = toParse;
  102537. this._maxPos = toParse.length;
  102538. }
  102539. Tokenizer.prototype.getNextToken = function () {
  102540. if (this.isEnd())
  102541. return ETokenType.END_OF_INPUT;
  102542. this.currentString = this.read();
  102543. this.currentToken = ETokenType.UNKNOWN;
  102544. if (this.currentString === "_" || this.isLetterOrDigitPattern.test(this.currentString)) {
  102545. this.currentToken = ETokenType.IDENTIFIER;
  102546. this.currentIdentifier = this.currentString;
  102547. while (!this.isEnd() && (this.isLetterOrDigitPattern.test(this.currentString = this.peek()) || this.currentString === "_")) {
  102548. this.currentIdentifier += this.currentString;
  102549. this.forward();
  102550. }
  102551. }
  102552. return this.currentToken;
  102553. };
  102554. Tokenizer.prototype.peek = function () {
  102555. return this._toParse[this._pos];
  102556. };
  102557. Tokenizer.prototype.read = function () {
  102558. return this._toParse[this._pos++];
  102559. };
  102560. Tokenizer.prototype.forward = function () {
  102561. this._pos++;
  102562. };
  102563. Tokenizer.prototype.isEnd = function () {
  102564. return this._pos >= this._maxPos;
  102565. };
  102566. return Tokenizer;
  102567. }());
  102568. /**
  102569. * Values
  102570. */
  102571. var glTFTransforms = ["MODEL", "VIEW", "PROJECTION", "MODELVIEW", "MODELVIEWPROJECTION", "JOINTMATRIX"];
  102572. var babylonTransforms = ["world", "view", "projection", "worldView", "worldViewProjection", "mBones"];
  102573. var glTFAnimationPaths = ["translation", "rotation", "scale"];
  102574. var babylonAnimationPaths = ["position", "rotationQuaternion", "scaling"];
  102575. /**
  102576. * Parse
  102577. */
  102578. var parseBuffers = function (parsedBuffers, gltfRuntime) {
  102579. for (var buf in parsedBuffers) {
  102580. var parsedBuffer = parsedBuffers[buf];
  102581. gltfRuntime.buffers[buf] = parsedBuffer;
  102582. gltfRuntime.buffersCount++;
  102583. }
  102584. };
  102585. var parseShaders = function (parsedShaders, gltfRuntime) {
  102586. for (var sha in parsedShaders) {
  102587. var parsedShader = parsedShaders[sha];
  102588. gltfRuntime.shaders[sha] = parsedShader;
  102589. gltfRuntime.shaderscount++;
  102590. }
  102591. };
  102592. var parseObject = function (parsedObjects, runtimeProperty, gltfRuntime) {
  102593. for (var object in parsedObjects) {
  102594. var parsedObject = parsedObjects[object];
  102595. gltfRuntime[runtimeProperty][object] = parsedObject;
  102596. }
  102597. };
  102598. /**
  102599. * Utils
  102600. */
  102601. var normalizeUVs = function (buffer) {
  102602. if (!buffer) {
  102603. return;
  102604. }
  102605. for (var i = 0; i < buffer.length / 2; i++) {
  102606. buffer[i * 2 + 1] = 1.0 - buffer[i * 2 + 1];
  102607. }
  102608. };
  102609. var getAttribute = function (attributeParameter) {
  102610. if (attributeParameter.semantic === "NORMAL") {
  102611. return "normal";
  102612. }
  102613. else if (attributeParameter.semantic === "POSITION") {
  102614. return "position";
  102615. }
  102616. else if (attributeParameter.semantic === "JOINT") {
  102617. return "matricesIndices";
  102618. }
  102619. else if (attributeParameter.semantic === "WEIGHT") {
  102620. return "matricesWeights";
  102621. }
  102622. else if (attributeParameter.semantic === "COLOR") {
  102623. return "color";
  102624. }
  102625. else if (attributeParameter.semantic && attributeParameter.semantic.indexOf("TEXCOORD_") !== -1) {
  102626. var channel = Number(attributeParameter.semantic.split("_")[1]);
  102627. return "uv" + (channel === 0 ? "" : channel + 1);
  102628. }
  102629. return null;
  102630. };
  102631. /**
  102632. * Loads and creates animations
  102633. */
  102634. var loadAnimations = function (gltfRuntime) {
  102635. for (var anim in gltfRuntime.animations) {
  102636. var animation = gltfRuntime.animations[anim];
  102637. if (!animation.channels || !animation.samplers) {
  102638. continue;
  102639. }
  102640. var lastAnimation = null;
  102641. for (var i = 0; i < animation.channels.length; i++) {
  102642. // Get parameters and load buffers
  102643. var channel = animation.channels[i];
  102644. var sampler = animation.samplers[channel.sampler];
  102645. if (!sampler) {
  102646. continue;
  102647. }
  102648. var inputData = null;
  102649. var outputData = null;
  102650. if (animation.parameters) {
  102651. inputData = animation.parameters[sampler.input];
  102652. outputData = animation.parameters[sampler.output];
  102653. }
  102654. else {
  102655. inputData = sampler.input;
  102656. outputData = sampler.output;
  102657. }
  102658. var bufferInput = GLTF1.GLTFUtils.GetBufferFromAccessor(gltfRuntime, gltfRuntime.accessors[inputData]);
  102659. var bufferOutput = GLTF1.GLTFUtils.GetBufferFromAccessor(gltfRuntime, gltfRuntime.accessors[outputData]);
  102660. var targetID = channel.target.id;
  102661. var targetNode = gltfRuntime.scene.getNodeByID(targetID);
  102662. if (targetNode === null) {
  102663. targetNode = gltfRuntime.scene.getNodeByName(targetID);
  102664. }
  102665. if (targetNode === null) {
  102666. BABYLON.Tools.Warn("Creating animation named " + anim + ". But cannot find node named " + targetID + " to attach to");
  102667. continue;
  102668. }
  102669. var isBone = targetNode instanceof BABYLON.Bone;
  102670. // Get target path (position, rotation or scaling)
  102671. var targetPath = channel.target.path;
  102672. var targetPathIndex = glTFAnimationPaths.indexOf(targetPath);
  102673. if (targetPathIndex !== -1) {
  102674. targetPath = babylonAnimationPaths[targetPathIndex];
  102675. }
  102676. // Determine animation type
  102677. var animationType = BABYLON.Animation.ANIMATIONTYPE_MATRIX;
  102678. if (!isBone) {
  102679. if (targetPath === "rotationQuaternion") {
  102680. animationType = BABYLON.Animation.ANIMATIONTYPE_QUATERNION;
  102681. targetNode.rotationQuaternion = new BABYLON.Quaternion();
  102682. }
  102683. else {
  102684. animationType = BABYLON.Animation.ANIMATIONTYPE_VECTOR3;
  102685. }
  102686. }
  102687. // Create animation and key frames
  102688. var babylonAnimation = null;
  102689. var keys = [];
  102690. var arrayOffset = 0;
  102691. var modifyKey = false;
  102692. if (isBone && lastAnimation && lastAnimation.getKeys().length === bufferInput.length) {
  102693. babylonAnimation = lastAnimation;
  102694. modifyKey = true;
  102695. }
  102696. if (!modifyKey) {
  102697. babylonAnimation = new BABYLON.Animation(anim, isBone ? "_matrix" : targetPath, 1, animationType, BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE);
  102698. }
  102699. // For each frame
  102700. for (var j = 0; j < bufferInput.length; j++) {
  102701. var value = null;
  102702. if (targetPath === "rotationQuaternion") { // VEC4
  102703. value = BABYLON.Quaternion.FromArray([bufferOutput[arrayOffset], bufferOutput[arrayOffset + 1], bufferOutput[arrayOffset + 2], bufferOutput[arrayOffset + 3]]);
  102704. arrayOffset += 4;
  102705. }
  102706. else { // Position and scaling are VEC3
  102707. value = BABYLON.Vector3.FromArray([bufferOutput[arrayOffset], bufferOutput[arrayOffset + 1], bufferOutput[arrayOffset + 2]]);
  102708. arrayOffset += 3;
  102709. }
  102710. if (isBone) {
  102711. var bone = targetNode;
  102712. var translation = BABYLON.Vector3.Zero();
  102713. var rotationQuaternion = new BABYLON.Quaternion();
  102714. var scaling = BABYLON.Vector3.Zero();
  102715. // Warning on decompose
  102716. var mat = bone.getBaseMatrix();
  102717. if (modifyKey && lastAnimation) {
  102718. mat = lastAnimation.getKeys()[j].value;
  102719. }
  102720. mat.decompose(scaling, rotationQuaternion, translation);
  102721. if (targetPath === "position") {
  102722. translation = value;
  102723. }
  102724. else if (targetPath === "rotationQuaternion") {
  102725. rotationQuaternion = value;
  102726. }
  102727. else {
  102728. scaling = value;
  102729. }
  102730. value = BABYLON.Matrix.Compose(scaling, rotationQuaternion, translation);
  102731. }
  102732. if (!modifyKey) {
  102733. keys.push({
  102734. frame: bufferInput[j],
  102735. value: value
  102736. });
  102737. }
  102738. else if (lastAnimation) {
  102739. lastAnimation.getKeys()[j].value = value;
  102740. }
  102741. }
  102742. // Finish
  102743. if (!modifyKey && babylonAnimation) {
  102744. babylonAnimation.setKeys(keys);
  102745. targetNode.animations.push(babylonAnimation);
  102746. }
  102747. lastAnimation = babylonAnimation;
  102748. gltfRuntime.scene.stopAnimation(targetNode);
  102749. gltfRuntime.scene.beginAnimation(targetNode, 0, bufferInput[bufferInput.length - 1], true, 1.0);
  102750. }
  102751. }
  102752. };
  102753. /**
  102754. * Returns the bones transformation matrix
  102755. */
  102756. var configureBoneTransformation = function (node) {
  102757. var mat = null;
  102758. if (node.translation || node.rotation || node.scale) {
  102759. var scale = BABYLON.Vector3.FromArray(node.scale || [1, 1, 1]);
  102760. var rotation = BABYLON.Quaternion.FromArray(node.rotation || [0, 0, 0, 1]);
  102761. var position = BABYLON.Vector3.FromArray(node.translation || [0, 0, 0]);
  102762. mat = BABYLON.Matrix.Compose(scale, rotation, position);
  102763. }
  102764. else {
  102765. mat = BABYLON.Matrix.FromArray(node.matrix);
  102766. }
  102767. return mat;
  102768. };
  102769. /**
  102770. * Returns the parent bone
  102771. */
  102772. var getParentBone = function (gltfRuntime, skins, jointName, newSkeleton) {
  102773. // Try to find
  102774. for (var i = 0; i < newSkeleton.bones.length; i++) {
  102775. if (newSkeleton.bones[i].name === jointName) {
  102776. return newSkeleton.bones[i];
  102777. }
  102778. }
  102779. // Not found, search in gltf nodes
  102780. var nodes = gltfRuntime.nodes;
  102781. for (var nde in nodes) {
  102782. var node = nodes[nde];
  102783. if (!node.jointName) {
  102784. continue;
  102785. }
  102786. var children = node.children;
  102787. for (var i = 0; i < children.length; i++) {
  102788. var child = gltfRuntime.nodes[children[i]];
  102789. if (!child.jointName) {
  102790. continue;
  102791. }
  102792. if (child.jointName === jointName) {
  102793. var mat = configureBoneTransformation(node);
  102794. var bone = new BABYLON.Bone(node.name || "", newSkeleton, getParentBone(gltfRuntime, skins, node.jointName, newSkeleton), mat);
  102795. bone.id = nde;
  102796. return bone;
  102797. }
  102798. }
  102799. }
  102800. return null;
  102801. };
  102802. /**
  102803. * Returns the appropriate root node
  102804. */
  102805. var getNodeToRoot = function (nodesToRoot, id) {
  102806. for (var i = 0; i < nodesToRoot.length; i++) {
  102807. var nodeToRoot = nodesToRoot[i];
  102808. for (var j = 0; j < nodeToRoot.node.children.length; j++) {
  102809. var child = nodeToRoot.node.children[j];
  102810. if (child === id) {
  102811. return nodeToRoot.bone;
  102812. }
  102813. }
  102814. }
  102815. return null;
  102816. };
  102817. /**
  102818. * Returns the node with the joint name
  102819. */
  102820. var getJointNode = function (gltfRuntime, jointName) {
  102821. var nodes = gltfRuntime.nodes;
  102822. var node = nodes[jointName];
  102823. if (node) {
  102824. return {
  102825. node: node,
  102826. id: jointName
  102827. };
  102828. }
  102829. for (var nde in nodes) {
  102830. node = nodes[nde];
  102831. if (node.jointName === jointName) {
  102832. return {
  102833. node: node,
  102834. id: nde
  102835. };
  102836. }
  102837. }
  102838. return null;
  102839. };
  102840. /**
  102841. * Checks if a nodes is in joints
  102842. */
  102843. var nodeIsInJoints = function (skins, id) {
  102844. for (var i = 0; i < skins.jointNames.length; i++) {
  102845. if (skins.jointNames[i] === id) {
  102846. return true;
  102847. }
  102848. }
  102849. return false;
  102850. };
  102851. /**
  102852. * Fills the nodes to root for bones and builds hierarchy
  102853. */
  102854. var getNodesToRoot = function (gltfRuntime, newSkeleton, skins, nodesToRoot) {
  102855. // Creates nodes for root
  102856. for (var nde in gltfRuntime.nodes) {
  102857. var node = gltfRuntime.nodes[nde];
  102858. var id = nde;
  102859. if (!node.jointName || nodeIsInJoints(skins, node.jointName)) {
  102860. continue;
  102861. }
  102862. // Create node to root bone
  102863. var mat = configureBoneTransformation(node);
  102864. var bone = new BABYLON.Bone(node.name || "", newSkeleton, null, mat);
  102865. bone.id = id;
  102866. nodesToRoot.push({ bone: bone, node: node, id: id });
  102867. }
  102868. // Parenting
  102869. for (var i = 0; i < nodesToRoot.length; i++) {
  102870. var nodeToRoot = nodesToRoot[i];
  102871. var children = nodeToRoot.node.children;
  102872. for (var j = 0; j < children.length; j++) {
  102873. var child = null;
  102874. for (var k = 0; k < nodesToRoot.length; k++) {
  102875. if (nodesToRoot[k].id === children[j]) {
  102876. child = nodesToRoot[k];
  102877. break;
  102878. }
  102879. }
  102880. if (child) {
  102881. child.bone._parent = nodeToRoot.bone;
  102882. nodeToRoot.bone.children.push(child.bone);
  102883. }
  102884. }
  102885. }
  102886. };
  102887. /**
  102888. * Imports a skeleton
  102889. */
  102890. var importSkeleton = function (gltfRuntime, skins, mesh, newSkeleton, id) {
  102891. if (!newSkeleton) {
  102892. newSkeleton = new BABYLON.Skeleton(skins.name || "", "", gltfRuntime.scene);
  102893. }
  102894. if (!skins.babylonSkeleton) {
  102895. return newSkeleton;
  102896. }
  102897. // Find the root bones
  102898. var nodesToRoot = [];
  102899. var nodesToRootToAdd = [];
  102900. getNodesToRoot(gltfRuntime, newSkeleton, skins, nodesToRoot);
  102901. newSkeleton.bones = [];
  102902. // Joints
  102903. for (var i = 0; i < skins.jointNames.length; i++) {
  102904. var jointNode = getJointNode(gltfRuntime, skins.jointNames[i]);
  102905. if (!jointNode) {
  102906. continue;
  102907. }
  102908. var node = jointNode.node;
  102909. if (!node) {
  102910. BABYLON.Tools.Warn("Joint named " + skins.jointNames[i] + " does not exist");
  102911. continue;
  102912. }
  102913. var id = jointNode.id;
  102914. // Optimize, if the bone already exists...
  102915. var existingBone = gltfRuntime.scene.getBoneByID(id);
  102916. if (existingBone) {
  102917. newSkeleton.bones.push(existingBone);
  102918. continue;
  102919. }
  102920. // Search for parent bone
  102921. var foundBone = false;
  102922. var parentBone = null;
  102923. for (var j = 0; j < i; j++) {
  102924. var jointNode_1 = getJointNode(gltfRuntime, skins.jointNames[j]);
  102925. if (!jointNode_1) {
  102926. continue;
  102927. }
  102928. var joint = jointNode_1.node;
  102929. if (!joint) {
  102930. BABYLON.Tools.Warn("Joint named " + skins.jointNames[j] + " does not exist when looking for parent");
  102931. continue;
  102932. }
  102933. var children = joint.children;
  102934. if (!children) {
  102935. continue;
  102936. }
  102937. foundBone = false;
  102938. for (var k = 0; k < children.length; k++) {
  102939. if (children[k] === id) {
  102940. parentBone = getParentBone(gltfRuntime, skins, skins.jointNames[j], newSkeleton);
  102941. foundBone = true;
  102942. break;
  102943. }
  102944. }
  102945. if (foundBone) {
  102946. break;
  102947. }
  102948. }
  102949. // Create bone
  102950. var mat = configureBoneTransformation(node);
  102951. if (!parentBone && nodesToRoot.length > 0) {
  102952. parentBone = getNodeToRoot(nodesToRoot, id);
  102953. if (parentBone) {
  102954. if (nodesToRootToAdd.indexOf(parentBone) === -1) {
  102955. nodesToRootToAdd.push(parentBone);
  102956. }
  102957. }
  102958. }
  102959. var bone = new BABYLON.Bone(node.jointName || "", newSkeleton, parentBone, mat);
  102960. bone.id = id;
  102961. }
  102962. // Polish
  102963. var bones = newSkeleton.bones;
  102964. newSkeleton.bones = [];
  102965. for (var i = 0; i < skins.jointNames.length; i++) {
  102966. var jointNode = getJointNode(gltfRuntime, skins.jointNames[i]);
  102967. if (!jointNode) {
  102968. continue;
  102969. }
  102970. for (var j = 0; j < bones.length; j++) {
  102971. if (bones[j].id === jointNode.id) {
  102972. newSkeleton.bones.push(bones[j]);
  102973. break;
  102974. }
  102975. }
  102976. }
  102977. newSkeleton.prepare();
  102978. // Finish
  102979. for (var i = 0; i < nodesToRootToAdd.length; i++) {
  102980. newSkeleton.bones.push(nodesToRootToAdd[i]);
  102981. }
  102982. return newSkeleton;
  102983. };
  102984. /**
  102985. * Imports a mesh and its geometries
  102986. */
  102987. var importMesh = function (gltfRuntime, node, meshes, id, newMesh) {
  102988. if (!newMesh) {
  102989. newMesh = new BABYLON.Mesh(node.name || "", gltfRuntime.scene);
  102990. newMesh.id = id;
  102991. }
  102992. if (!node.babylonNode) {
  102993. return newMesh;
  102994. }
  102995. var subMaterials = [];
  102996. var vertexData = null;
  102997. var verticesStarts = new Array();
  102998. var verticesCounts = new Array();
  102999. var indexStarts = new Array();
  103000. var indexCounts = new Array();
  103001. for (var meshIndex = 0; meshIndex < meshes.length; meshIndex++) {
  103002. var meshID = meshes[meshIndex];
  103003. var mesh = gltfRuntime.meshes[meshID];
  103004. if (!mesh) {
  103005. continue;
  103006. }
  103007. // Positions, normals and UVs
  103008. for (var i = 0; i < mesh.primitives.length; i++) {
  103009. // Temporary vertex data
  103010. var tempVertexData = new BABYLON.VertexData();
  103011. var primitive = mesh.primitives[i];
  103012. if (primitive.mode !== 4) {
  103013. // continue;
  103014. }
  103015. var attributes = primitive.attributes;
  103016. var accessor = null;
  103017. var buffer = null;
  103018. // Set positions, normal and uvs
  103019. for (var semantic in attributes) {
  103020. // Link accessor and buffer view
  103021. accessor = gltfRuntime.accessors[attributes[semantic]];
  103022. buffer = GLTF1.GLTFUtils.GetBufferFromAccessor(gltfRuntime, accessor);
  103023. if (semantic === "NORMAL") {
  103024. tempVertexData.normals = new Float32Array(buffer.length);
  103025. tempVertexData.normals.set(buffer);
  103026. }
  103027. else if (semantic === "POSITION") {
  103028. if (BABYLON.GLTFFileLoader.HomogeneousCoordinates) {
  103029. tempVertexData.positions = new Float32Array(buffer.length - buffer.length / 4);
  103030. for (var j = 0; j < buffer.length; j += 4) {
  103031. tempVertexData.positions[j] = buffer[j];
  103032. tempVertexData.positions[j + 1] = buffer[j + 1];
  103033. tempVertexData.positions[j + 2] = buffer[j + 2];
  103034. }
  103035. }
  103036. else {
  103037. tempVertexData.positions = new Float32Array(buffer.length);
  103038. tempVertexData.positions.set(buffer);
  103039. }
  103040. verticesCounts.push(tempVertexData.positions.length);
  103041. }
  103042. else if (semantic.indexOf("TEXCOORD_") !== -1) {
  103043. var channel = Number(semantic.split("_")[1]);
  103044. var uvKind = BABYLON.VertexBuffer.UVKind + (channel === 0 ? "" : (channel + 1));
  103045. var uvs = new Float32Array(buffer.length);
  103046. uvs.set(buffer);
  103047. normalizeUVs(uvs);
  103048. tempVertexData.set(uvs, uvKind);
  103049. }
  103050. else if (semantic === "JOINT") {
  103051. tempVertexData.matricesIndices = new Float32Array(buffer.length);
  103052. tempVertexData.matricesIndices.set(buffer);
  103053. }
  103054. else if (semantic === "WEIGHT") {
  103055. tempVertexData.matricesWeights = new Float32Array(buffer.length);
  103056. tempVertexData.matricesWeights.set(buffer);
  103057. }
  103058. else if (semantic === "COLOR") {
  103059. tempVertexData.colors = new Float32Array(buffer.length);
  103060. tempVertexData.colors.set(buffer);
  103061. }
  103062. }
  103063. // Indices
  103064. accessor = gltfRuntime.accessors[primitive.indices];
  103065. if (accessor) {
  103066. buffer = GLTF1.GLTFUtils.GetBufferFromAccessor(gltfRuntime, accessor);
  103067. tempVertexData.indices = new Int32Array(buffer.length);
  103068. tempVertexData.indices.set(buffer);
  103069. indexCounts.push(tempVertexData.indices.length);
  103070. }
  103071. else {
  103072. // Set indices on the fly
  103073. var indices = [];
  103074. for (var j = 0; j < tempVertexData.positions.length / 3; j++) {
  103075. indices.push(j);
  103076. }
  103077. tempVertexData.indices = new Int32Array(indices);
  103078. indexCounts.push(tempVertexData.indices.length);
  103079. }
  103080. if (!vertexData) {
  103081. vertexData = tempVertexData;
  103082. }
  103083. else {
  103084. vertexData.merge(tempVertexData);
  103085. }
  103086. // Sub material
  103087. var material_1 = gltfRuntime.scene.getMaterialByID(primitive.material);
  103088. subMaterials.push(material_1 === null ? GLTF1.GLTFUtils.GetDefaultMaterial(gltfRuntime.scene) : material_1);
  103089. // Update vertices start and index start
  103090. verticesStarts.push(verticesStarts.length === 0 ? 0 : verticesStarts[verticesStarts.length - 1] + verticesCounts[verticesCounts.length - 2]);
  103091. indexStarts.push(indexStarts.length === 0 ? 0 : indexStarts[indexStarts.length - 1] + indexCounts[indexCounts.length - 2]);
  103092. }
  103093. }
  103094. var material;
  103095. if (subMaterials.length > 1) {
  103096. material = new BABYLON.MultiMaterial("multimat" + id, gltfRuntime.scene);
  103097. material.subMaterials = subMaterials;
  103098. }
  103099. else {
  103100. material = new BABYLON.StandardMaterial("multimat" + id, gltfRuntime.scene);
  103101. }
  103102. if (subMaterials.length === 1) {
  103103. material = subMaterials[0];
  103104. }
  103105. if (!newMesh.material) {
  103106. newMesh.material = material;
  103107. }
  103108. // Apply geometry
  103109. new BABYLON.Geometry(id, gltfRuntime.scene, vertexData, false, newMesh);
  103110. newMesh.computeWorldMatrix(true);
  103111. // Apply submeshes
  103112. newMesh.subMeshes = [];
  103113. var index = 0;
  103114. for (var meshIndex = 0; meshIndex < meshes.length; meshIndex++) {
  103115. var meshID = meshes[meshIndex];
  103116. var mesh = gltfRuntime.meshes[meshID];
  103117. if (!mesh) {
  103118. continue;
  103119. }
  103120. for (var i = 0; i < mesh.primitives.length; i++) {
  103121. if (mesh.primitives[i].mode !== 4) {
  103122. //continue;
  103123. }
  103124. BABYLON.SubMesh.AddToMesh(index, verticesStarts[index], verticesCounts[index], indexStarts[index], indexCounts[index], newMesh, newMesh, true);
  103125. index++;
  103126. }
  103127. }
  103128. // Finish
  103129. return newMesh;
  103130. };
  103131. /**
  103132. * Configure node transformation from position, rotation and scaling
  103133. */
  103134. var configureNode = function (newNode, position, rotation, scaling) {
  103135. if (newNode.position) {
  103136. newNode.position = position;
  103137. }
  103138. if (newNode.rotationQuaternion || newNode.rotation) {
  103139. newNode.rotationQuaternion = rotation;
  103140. }
  103141. if (newNode.scaling) {
  103142. newNode.scaling = scaling;
  103143. }
  103144. };
  103145. /**
  103146. * Configures node from transformation matrix
  103147. */
  103148. var configureNodeFromMatrix = function (newNode, node, parent) {
  103149. if (node.matrix) {
  103150. var position = new BABYLON.Vector3(0, 0, 0);
  103151. var rotation = new BABYLON.Quaternion();
  103152. var scaling = new BABYLON.Vector3(0, 0, 0);
  103153. var mat = BABYLON.Matrix.FromArray(node.matrix);
  103154. mat.decompose(scaling, rotation, position);
  103155. configureNode(newNode, position, rotation, scaling);
  103156. }
  103157. else if (node.translation && node.rotation && node.scale) {
  103158. configureNode(newNode, BABYLON.Vector3.FromArray(node.translation), BABYLON.Quaternion.FromArray(node.rotation), BABYLON.Vector3.FromArray(node.scale));
  103159. }
  103160. newNode.computeWorldMatrix(true);
  103161. };
  103162. /**
  103163. * Imports a node
  103164. */
  103165. var importNode = function (gltfRuntime, node, id, parent) {
  103166. var lastNode = null;
  103167. if (gltfRuntime.importOnlyMeshes && (node.skin || node.meshes)) {
  103168. if (gltfRuntime.importMeshesNames && gltfRuntime.importMeshesNames.length > 0 && gltfRuntime.importMeshesNames.indexOf(node.name || "") === -1) {
  103169. return null;
  103170. }
  103171. }
  103172. // Meshes
  103173. if (node.skin) {
  103174. if (node.meshes) {
  103175. var skin = gltfRuntime.skins[node.skin];
  103176. var newMesh = importMesh(gltfRuntime, node, node.meshes, id, node.babylonNode);
  103177. newMesh.skeleton = gltfRuntime.scene.getLastSkeletonByID(node.skin);
  103178. if (newMesh.skeleton === null) {
  103179. newMesh.skeleton = importSkeleton(gltfRuntime, skin, newMesh, skin.babylonSkeleton, node.skin);
  103180. if (!skin.babylonSkeleton) {
  103181. skin.babylonSkeleton = newMesh.skeleton;
  103182. }
  103183. }
  103184. lastNode = newMesh;
  103185. }
  103186. }
  103187. else if (node.meshes) {
  103188. /**
  103189. * Improve meshes property
  103190. */
  103191. var newMesh = importMesh(gltfRuntime, node, node.mesh ? [node.mesh] : node.meshes, id, node.babylonNode);
  103192. lastNode = newMesh;
  103193. }
  103194. // Lights
  103195. else if (node.light && !node.babylonNode && !gltfRuntime.importOnlyMeshes) {
  103196. var light = gltfRuntime.lights[node.light];
  103197. if (light) {
  103198. if (light.type === "ambient") {
  103199. var ambienLight = light[light.type];
  103200. var hemiLight = new BABYLON.HemisphericLight(node.light, BABYLON.Vector3.Zero(), gltfRuntime.scene);
  103201. hemiLight.name = node.name || "";
  103202. if (ambienLight.color) {
  103203. hemiLight.diffuse = BABYLON.Color3.FromArray(ambienLight.color);
  103204. }
  103205. lastNode = hemiLight;
  103206. }
  103207. else if (light.type === "directional") {
  103208. var directionalLight = light[light.type];
  103209. var dirLight = new BABYLON.DirectionalLight(node.light, BABYLON.Vector3.Zero(), gltfRuntime.scene);
  103210. dirLight.name = node.name || "";
  103211. if (directionalLight.color) {
  103212. dirLight.diffuse = BABYLON.Color3.FromArray(directionalLight.color);
  103213. }
  103214. lastNode = dirLight;
  103215. }
  103216. else if (light.type === "point") {
  103217. var pointLight = light[light.type];
  103218. var ptLight = new BABYLON.PointLight(node.light, BABYLON.Vector3.Zero(), gltfRuntime.scene);
  103219. ptLight.name = node.name || "";
  103220. if (pointLight.color) {
  103221. ptLight.diffuse = BABYLON.Color3.FromArray(pointLight.color);
  103222. }
  103223. lastNode = ptLight;
  103224. }
  103225. else if (light.type === "spot") {
  103226. var spotLight = light[light.type];
  103227. var spLight = new BABYLON.SpotLight(node.light, BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), 0, 0, gltfRuntime.scene);
  103228. spLight.name = node.name || "";
  103229. if (spotLight.color) {
  103230. spLight.diffuse = BABYLON.Color3.FromArray(spotLight.color);
  103231. }
  103232. if (spotLight.fallOfAngle) {
  103233. spLight.angle = spotLight.fallOfAngle;
  103234. }
  103235. if (spotLight.fallOffExponent) {
  103236. spLight.exponent = spotLight.fallOffExponent;
  103237. }
  103238. lastNode = spLight;
  103239. }
  103240. }
  103241. }
  103242. // Cameras
  103243. else if (node.camera && !node.babylonNode && !gltfRuntime.importOnlyMeshes) {
  103244. var camera = gltfRuntime.cameras[node.camera];
  103245. if (camera) {
  103246. if (camera.type === "orthographic") {
  103247. var orthoCamera = new BABYLON.FreeCamera(node.camera, BABYLON.Vector3.Zero(), gltfRuntime.scene, false);
  103248. orthoCamera.name = node.name || "";
  103249. orthoCamera.mode = BABYLON.Camera.ORTHOGRAPHIC_CAMERA;
  103250. orthoCamera.attachControl(gltfRuntime.scene.getEngine().getRenderingCanvas());
  103251. lastNode = orthoCamera;
  103252. }
  103253. else if (camera.type === "perspective") {
  103254. var perspectiveCamera = camera[camera.type];
  103255. var persCamera = new BABYLON.FreeCamera(node.camera, BABYLON.Vector3.Zero(), gltfRuntime.scene, false);
  103256. persCamera.name = node.name || "";
  103257. persCamera.attachControl(gltfRuntime.scene.getEngine().getRenderingCanvas());
  103258. if (!perspectiveCamera.aspectRatio) {
  103259. perspectiveCamera.aspectRatio = gltfRuntime.scene.getEngine().getRenderWidth() / gltfRuntime.scene.getEngine().getRenderHeight();
  103260. }
  103261. if (perspectiveCamera.znear && perspectiveCamera.zfar) {
  103262. persCamera.maxZ = perspectiveCamera.zfar;
  103263. persCamera.minZ = perspectiveCamera.znear;
  103264. }
  103265. lastNode = persCamera;
  103266. }
  103267. }
  103268. }
  103269. // Empty node
  103270. if (!node.jointName) {
  103271. if (node.babylonNode) {
  103272. return node.babylonNode;
  103273. }
  103274. else if (lastNode === null) {
  103275. var dummy = new BABYLON.Mesh(node.name || "", gltfRuntime.scene);
  103276. node.babylonNode = dummy;
  103277. lastNode = dummy;
  103278. }
  103279. }
  103280. if (lastNode !== null) {
  103281. if (node.matrix && lastNode instanceof BABYLON.Mesh) {
  103282. configureNodeFromMatrix(lastNode, node, parent);
  103283. }
  103284. else {
  103285. var translation = node.translation || [0, 0, 0];
  103286. var rotation = node.rotation || [0, 0, 0, 1];
  103287. var scale = node.scale || [1, 1, 1];
  103288. configureNode(lastNode, BABYLON.Vector3.FromArray(translation), BABYLON.Quaternion.FromArray(rotation), BABYLON.Vector3.FromArray(scale));
  103289. }
  103290. lastNode.updateCache(true);
  103291. node.babylonNode = lastNode;
  103292. }
  103293. return lastNode;
  103294. };
  103295. /**
  103296. * Traverses nodes and creates them
  103297. */
  103298. var traverseNodes = function (gltfRuntime, id, parent, meshIncluded) {
  103299. if (meshIncluded === void 0) { meshIncluded = false; }
  103300. var node = gltfRuntime.nodes[id];
  103301. var newNode = null;
  103302. if (gltfRuntime.importOnlyMeshes && !meshIncluded && gltfRuntime.importMeshesNames) {
  103303. if (gltfRuntime.importMeshesNames.indexOf(node.name || "") !== -1 || gltfRuntime.importMeshesNames.length === 0) {
  103304. meshIncluded = true;
  103305. }
  103306. else {
  103307. meshIncluded = false;
  103308. }
  103309. }
  103310. else {
  103311. meshIncluded = true;
  103312. }
  103313. if (!node.jointName && meshIncluded) {
  103314. newNode = importNode(gltfRuntime, node, id, parent);
  103315. if (newNode !== null) {
  103316. newNode.id = id;
  103317. newNode.parent = parent;
  103318. }
  103319. }
  103320. if (node.children) {
  103321. for (var i = 0; i < node.children.length; i++) {
  103322. traverseNodes(gltfRuntime, node.children[i], newNode, meshIncluded);
  103323. }
  103324. }
  103325. };
  103326. /**
  103327. * do stuff after buffers, shaders are loaded (e.g. hook up materials, load animations, etc.)
  103328. */
  103329. var postLoad = function (gltfRuntime) {
  103330. // Nodes
  103331. var currentScene = gltfRuntime.currentScene;
  103332. if (currentScene) {
  103333. for (var i = 0; i < currentScene.nodes.length; i++) {
  103334. traverseNodes(gltfRuntime, currentScene.nodes[i], null);
  103335. }
  103336. }
  103337. else {
  103338. for (var thing in gltfRuntime.scenes) {
  103339. currentScene = gltfRuntime.scenes[thing];
  103340. for (var i = 0; i < currentScene.nodes.length; i++) {
  103341. traverseNodes(gltfRuntime, currentScene.nodes[i], null);
  103342. }
  103343. }
  103344. }
  103345. // Set animations
  103346. loadAnimations(gltfRuntime);
  103347. for (var i = 0; i < gltfRuntime.scene.skeletons.length; i++) {
  103348. var skeleton = gltfRuntime.scene.skeletons[i];
  103349. gltfRuntime.scene.beginAnimation(skeleton, 0, Number.MAX_VALUE, true, 1.0);
  103350. }
  103351. };
  103352. /**
  103353. * onBind shaderrs callback to set uniforms and matrices
  103354. */
  103355. var onBindShaderMaterial = function (mesh, gltfRuntime, unTreatedUniforms, shaderMaterial, technique, material, onSuccess) {
  103356. var materialValues = material.values || technique.parameters;
  103357. for (var unif in unTreatedUniforms) {
  103358. var uniform = unTreatedUniforms[unif];
  103359. var type = uniform.type;
  103360. if (type === GLTF1.EParameterType.FLOAT_MAT2 || type === GLTF1.EParameterType.FLOAT_MAT3 || type === GLTF1.EParameterType.FLOAT_MAT4) {
  103361. if (uniform.semantic && !uniform.source && !uniform.node) {
  103362. GLTF1.GLTFUtils.SetMatrix(gltfRuntime.scene, mesh, uniform, unif, shaderMaterial.getEffect());
  103363. }
  103364. else if (uniform.semantic && (uniform.source || uniform.node)) {
  103365. var source = gltfRuntime.scene.getNodeByName(uniform.source || uniform.node || "");
  103366. if (source === null) {
  103367. source = gltfRuntime.scene.getNodeByID(uniform.source || uniform.node || "");
  103368. }
  103369. if (source === null) {
  103370. continue;
  103371. }
  103372. GLTF1.GLTFUtils.SetMatrix(gltfRuntime.scene, source, uniform, unif, shaderMaterial.getEffect());
  103373. }
  103374. }
  103375. else {
  103376. var value = materialValues[technique.uniforms[unif]];
  103377. if (!value) {
  103378. continue;
  103379. }
  103380. if (type === GLTF1.EParameterType.SAMPLER_2D) {
  103381. var texture = gltfRuntime.textures[material.values ? value : uniform.value].babylonTexture;
  103382. if (texture === null || texture === undefined) {
  103383. continue;
  103384. }
  103385. shaderMaterial.getEffect().setTexture(unif, texture);
  103386. }
  103387. else {
  103388. GLTF1.GLTFUtils.SetUniform((shaderMaterial.getEffect()), unif, value, type);
  103389. }
  103390. }
  103391. }
  103392. onSuccess(shaderMaterial);
  103393. };
  103394. /**
  103395. * Prepare uniforms to send the only one time
  103396. * Loads the appropriate textures
  103397. */
  103398. var prepareShaderMaterialUniforms = function (gltfRuntime, shaderMaterial, technique, material, unTreatedUniforms) {
  103399. var materialValues = material.values || technique.parameters;
  103400. var techniqueUniforms = technique.uniforms;
  103401. /**
  103402. * Prepare values here (not matrices)
  103403. */
  103404. for (var unif in unTreatedUniforms) {
  103405. var uniform = unTreatedUniforms[unif];
  103406. var type = uniform.type;
  103407. var value = materialValues[techniqueUniforms[unif]];
  103408. if (value === undefined) {
  103409. // In case the value is the same for all materials
  103410. value = uniform.value;
  103411. }
  103412. if (!value) {
  103413. continue;
  103414. }
  103415. var onLoadTexture = function (uniformName) {
  103416. return function (texture) {
  103417. if (uniform.value && uniformName) {
  103418. // Static uniform
  103419. shaderMaterial.setTexture(uniformName, texture);
  103420. delete unTreatedUniforms[uniformName];
  103421. }
  103422. };
  103423. };
  103424. // Texture (sampler2D)
  103425. if (type === GLTF1.EParameterType.SAMPLER_2D) {
  103426. GLTF1.GLTFLoaderExtension.LoadTextureAsync(gltfRuntime, material.values ? value : uniform.value, onLoadTexture(unif), function () { return onLoadTexture(null); });
  103427. }
  103428. // Others
  103429. else {
  103430. if (uniform.value && GLTF1.GLTFUtils.SetUniform(shaderMaterial, unif, material.values ? value : uniform.value, type)) {
  103431. // Static uniform
  103432. delete unTreatedUniforms[unif];
  103433. }
  103434. }
  103435. }
  103436. };
  103437. /**
  103438. * Shader compilation failed
  103439. */
  103440. var onShaderCompileError = function (program, shaderMaterial, onError) {
  103441. return function (effect, error) {
  103442. shaderMaterial.dispose(true);
  103443. onError("Cannot compile program named " + program.name + ". Error: " + error + ". Default material will be applied");
  103444. };
  103445. };
  103446. /**
  103447. * Shader compilation success
  103448. */
  103449. var onShaderCompileSuccess = function (gltfRuntime, shaderMaterial, technique, material, unTreatedUniforms, onSuccess) {
  103450. return function (_) {
  103451. prepareShaderMaterialUniforms(gltfRuntime, shaderMaterial, technique, material, unTreatedUniforms);
  103452. shaderMaterial.onBind = function (mesh) {
  103453. onBindShaderMaterial(mesh, gltfRuntime, unTreatedUniforms, shaderMaterial, technique, material, onSuccess);
  103454. };
  103455. };
  103456. };
  103457. /**
  103458. * Returns the appropriate uniform if already handled by babylon
  103459. */
  103460. var parseShaderUniforms = function (tokenizer, technique, unTreatedUniforms) {
  103461. for (var unif in technique.uniforms) {
  103462. var uniform = technique.uniforms[unif];
  103463. var uniformParameter = technique.parameters[uniform];
  103464. if (tokenizer.currentIdentifier === unif) {
  103465. if (uniformParameter.semantic && !uniformParameter.source && !uniformParameter.node) {
  103466. var transformIndex = glTFTransforms.indexOf(uniformParameter.semantic);
  103467. if (transformIndex !== -1) {
  103468. delete unTreatedUniforms[unif];
  103469. return babylonTransforms[transformIndex];
  103470. }
  103471. }
  103472. }
  103473. }
  103474. return tokenizer.currentIdentifier;
  103475. };
  103476. /**
  103477. * All shaders loaded. Create materials one by one
  103478. */
  103479. var importMaterials = function (gltfRuntime) {
  103480. // Create materials
  103481. for (var mat in gltfRuntime.materials) {
  103482. GLTF1.GLTFLoaderExtension.LoadMaterialAsync(gltfRuntime, mat, function (material) { }, function () { });
  103483. }
  103484. };
  103485. /**
  103486. * Implementation of the base glTF spec
  103487. */
  103488. var GLTFLoaderBase = /** @class */ (function () {
  103489. function GLTFLoaderBase() {
  103490. }
  103491. GLTFLoaderBase.CreateRuntime = function (parsedData, scene, rootUrl) {
  103492. var gltfRuntime = {
  103493. extensions: {},
  103494. accessors: {},
  103495. buffers: {},
  103496. bufferViews: {},
  103497. meshes: {},
  103498. lights: {},
  103499. cameras: {},
  103500. nodes: {},
  103501. images: {},
  103502. textures: {},
  103503. shaders: {},
  103504. programs: {},
  103505. samplers: {},
  103506. techniques: {},
  103507. materials: {},
  103508. animations: {},
  103509. skins: {},
  103510. extensionsUsed: [],
  103511. scenes: {},
  103512. buffersCount: 0,
  103513. shaderscount: 0,
  103514. scene: scene,
  103515. rootUrl: rootUrl,
  103516. loadedBufferCount: 0,
  103517. loadedBufferViews: {},
  103518. loadedShaderCount: 0,
  103519. importOnlyMeshes: false,
  103520. dummyNodes: []
  103521. };
  103522. // Parse
  103523. if (parsedData.extensions) {
  103524. parseObject(parsedData.extensions, "extensions", gltfRuntime);
  103525. }
  103526. if (parsedData.extensionsUsed) {
  103527. parseObject(parsedData.extensionsUsed, "extensionsUsed", gltfRuntime);
  103528. }
  103529. if (parsedData.buffers) {
  103530. parseBuffers(parsedData.buffers, gltfRuntime);
  103531. }
  103532. if (parsedData.bufferViews) {
  103533. parseObject(parsedData.bufferViews, "bufferViews", gltfRuntime);
  103534. }
  103535. if (parsedData.accessors) {
  103536. parseObject(parsedData.accessors, "accessors", gltfRuntime);
  103537. }
  103538. if (parsedData.meshes) {
  103539. parseObject(parsedData.meshes, "meshes", gltfRuntime);
  103540. }
  103541. if (parsedData.lights) {
  103542. parseObject(parsedData.lights, "lights", gltfRuntime);
  103543. }
  103544. if (parsedData.cameras) {
  103545. parseObject(parsedData.cameras, "cameras", gltfRuntime);
  103546. }
  103547. if (parsedData.nodes) {
  103548. parseObject(parsedData.nodes, "nodes", gltfRuntime);
  103549. }
  103550. if (parsedData.images) {
  103551. parseObject(parsedData.images, "images", gltfRuntime);
  103552. }
  103553. if (parsedData.textures) {
  103554. parseObject(parsedData.textures, "textures", gltfRuntime);
  103555. }
  103556. if (parsedData.shaders) {
  103557. parseShaders(parsedData.shaders, gltfRuntime);
  103558. }
  103559. if (parsedData.programs) {
  103560. parseObject(parsedData.programs, "programs", gltfRuntime);
  103561. }
  103562. if (parsedData.samplers) {
  103563. parseObject(parsedData.samplers, "samplers", gltfRuntime);
  103564. }
  103565. if (parsedData.techniques) {
  103566. parseObject(parsedData.techniques, "techniques", gltfRuntime);
  103567. }
  103568. if (parsedData.materials) {
  103569. parseObject(parsedData.materials, "materials", gltfRuntime);
  103570. }
  103571. if (parsedData.animations) {
  103572. parseObject(parsedData.animations, "animations", gltfRuntime);
  103573. }
  103574. if (parsedData.skins) {
  103575. parseObject(parsedData.skins, "skins", gltfRuntime);
  103576. }
  103577. if (parsedData.scenes) {
  103578. gltfRuntime.scenes = parsedData.scenes;
  103579. }
  103580. if (parsedData.scene && parsedData.scenes) {
  103581. gltfRuntime.currentScene = parsedData.scenes[parsedData.scene];
  103582. }
  103583. return gltfRuntime;
  103584. };
  103585. GLTFLoaderBase.LoadBufferAsync = function (gltfRuntime, id, onSuccess, onError, onProgress) {
  103586. var buffer = gltfRuntime.buffers[id];
  103587. if (BABYLON.Tools.IsBase64(buffer.uri)) {
  103588. setTimeout(function () { return onSuccess(new Uint8Array(BABYLON.Tools.DecodeBase64(buffer.uri))); });
  103589. }
  103590. else {
  103591. BABYLON.Tools.LoadFile(gltfRuntime.rootUrl + buffer.uri, function (data) { return onSuccess(new Uint8Array(data)); }, onProgress, undefined, true, function (request) {
  103592. if (request) {
  103593. onError(request.status + " " + request.statusText);
  103594. }
  103595. });
  103596. }
  103597. };
  103598. GLTFLoaderBase.LoadTextureBufferAsync = function (gltfRuntime, id, onSuccess, onError) {
  103599. var texture = gltfRuntime.textures[id];
  103600. if (!texture || !texture.source) {
  103601. onError("");
  103602. return;
  103603. }
  103604. if (texture.babylonTexture) {
  103605. onSuccess(null);
  103606. return;
  103607. }
  103608. var source = gltfRuntime.images[texture.source];
  103609. if (BABYLON.Tools.IsBase64(source.uri)) {
  103610. setTimeout(function () { return onSuccess(new Uint8Array(BABYLON.Tools.DecodeBase64(source.uri))); });
  103611. }
  103612. else {
  103613. BABYLON.Tools.LoadFile(gltfRuntime.rootUrl + source.uri, function (data) { return onSuccess(new Uint8Array(data)); }, undefined, undefined, true, function (request) {
  103614. if (request) {
  103615. onError(request.status + " " + request.statusText);
  103616. }
  103617. });
  103618. }
  103619. };
  103620. GLTFLoaderBase.CreateTextureAsync = function (gltfRuntime, id, buffer, onSuccess, onError) {
  103621. var texture = gltfRuntime.textures[id];
  103622. if (texture.babylonTexture) {
  103623. onSuccess(texture.babylonTexture);
  103624. return;
  103625. }
  103626. var sampler = gltfRuntime.samplers[texture.sampler];
  103627. var createMipMaps = (sampler.minFilter === GLTF1.ETextureFilterType.NEAREST_MIPMAP_NEAREST) ||
  103628. (sampler.minFilter === GLTF1.ETextureFilterType.NEAREST_MIPMAP_LINEAR) ||
  103629. (sampler.minFilter === GLTF1.ETextureFilterType.LINEAR_MIPMAP_NEAREST) ||
  103630. (sampler.minFilter === GLTF1.ETextureFilterType.LINEAR_MIPMAP_LINEAR);
  103631. var samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE;
  103632. var blob = new Blob([buffer]);
  103633. var blobURL = URL.createObjectURL(blob);
  103634. var revokeBlobURL = function () { return URL.revokeObjectURL(blobURL); };
  103635. var newTexture = new BABYLON.Texture(blobURL, gltfRuntime.scene, !createMipMaps, true, samplingMode, revokeBlobURL, revokeBlobURL);
  103636. if (sampler.wrapS !== undefined) {
  103637. newTexture.wrapU = GLTF1.GLTFUtils.GetWrapMode(sampler.wrapS);
  103638. }
  103639. if (sampler.wrapT !== undefined) {
  103640. newTexture.wrapV = GLTF1.GLTFUtils.GetWrapMode(sampler.wrapT);
  103641. }
  103642. newTexture.name = id;
  103643. texture.babylonTexture = newTexture;
  103644. onSuccess(newTexture);
  103645. };
  103646. GLTFLoaderBase.LoadShaderStringAsync = function (gltfRuntime, id, onSuccess, onError) {
  103647. var shader = gltfRuntime.shaders[id];
  103648. if (BABYLON.Tools.IsBase64(shader.uri)) {
  103649. var shaderString = atob(shader.uri.split(",")[1]);
  103650. if (onSuccess) {
  103651. onSuccess(shaderString);
  103652. }
  103653. }
  103654. else {
  103655. BABYLON.Tools.LoadFile(gltfRuntime.rootUrl + shader.uri, onSuccess, undefined, undefined, false, function (request) {
  103656. if (request && onError) {
  103657. onError(request.status + " " + request.statusText);
  103658. }
  103659. });
  103660. }
  103661. };
  103662. GLTFLoaderBase.LoadMaterialAsync = function (gltfRuntime, id, onSuccess, onError) {
  103663. var material = gltfRuntime.materials[id];
  103664. if (!material.technique) {
  103665. if (onError) {
  103666. onError("No technique found.");
  103667. }
  103668. return;
  103669. }
  103670. var technique = gltfRuntime.techniques[material.technique];
  103671. if (!technique) {
  103672. var defaultMaterial = new BABYLON.StandardMaterial(id, gltfRuntime.scene);
  103673. defaultMaterial.diffuseColor = new BABYLON.Color3(0.5, 0.5, 0.5);
  103674. defaultMaterial.sideOrientation = BABYLON.Material.CounterClockWiseSideOrientation;
  103675. onSuccess(defaultMaterial);
  103676. return;
  103677. }
  103678. var program = gltfRuntime.programs[technique.program];
  103679. var states = technique.states;
  103680. var vertexShader = BABYLON.Effect.ShadersStore[program.vertexShader + "VertexShader"];
  103681. var pixelShader = BABYLON.Effect.ShadersStore[program.fragmentShader + "PixelShader"];
  103682. var newVertexShader = "";
  103683. var newPixelShader = "";
  103684. var vertexTokenizer = new Tokenizer(vertexShader);
  103685. var pixelTokenizer = new Tokenizer(pixelShader);
  103686. var unTreatedUniforms = {};
  103687. var uniforms = [];
  103688. var attributes = [];
  103689. var samplers = [];
  103690. // Fill uniform, sampler2D and attributes
  103691. for (var unif in technique.uniforms) {
  103692. var uniform = technique.uniforms[unif];
  103693. var uniformParameter = technique.parameters[uniform];
  103694. unTreatedUniforms[unif] = uniformParameter;
  103695. if (uniformParameter.semantic && !uniformParameter.node && !uniformParameter.source) {
  103696. var transformIndex = glTFTransforms.indexOf(uniformParameter.semantic);
  103697. if (transformIndex !== -1) {
  103698. uniforms.push(babylonTransforms[transformIndex]);
  103699. delete unTreatedUniforms[unif];
  103700. }
  103701. else {
  103702. uniforms.push(unif);
  103703. }
  103704. }
  103705. else if (uniformParameter.type === GLTF1.EParameterType.SAMPLER_2D) {
  103706. samplers.push(unif);
  103707. }
  103708. else {
  103709. uniforms.push(unif);
  103710. }
  103711. }
  103712. for (var attr in technique.attributes) {
  103713. var attribute = technique.attributes[attr];
  103714. var attributeParameter = technique.parameters[attribute];
  103715. if (attributeParameter.semantic) {
  103716. attributes.push(getAttribute(attributeParameter));
  103717. }
  103718. }
  103719. // Configure vertex shader
  103720. while (!vertexTokenizer.isEnd() && vertexTokenizer.getNextToken()) {
  103721. var tokenType = vertexTokenizer.currentToken;
  103722. if (tokenType !== ETokenType.IDENTIFIER) {
  103723. newVertexShader += vertexTokenizer.currentString;
  103724. continue;
  103725. }
  103726. var foundAttribute = false;
  103727. for (var attr in technique.attributes) {
  103728. var attribute = technique.attributes[attr];
  103729. var attributeParameter = technique.parameters[attribute];
  103730. if (vertexTokenizer.currentIdentifier === attr && attributeParameter.semantic) {
  103731. newVertexShader += getAttribute(attributeParameter);
  103732. foundAttribute = true;
  103733. break;
  103734. }
  103735. }
  103736. if (foundAttribute) {
  103737. continue;
  103738. }
  103739. newVertexShader += parseShaderUniforms(vertexTokenizer, technique, unTreatedUniforms);
  103740. }
  103741. // Configure pixel shader
  103742. while (!pixelTokenizer.isEnd() && pixelTokenizer.getNextToken()) {
  103743. var tokenType = pixelTokenizer.currentToken;
  103744. if (tokenType !== ETokenType.IDENTIFIER) {
  103745. newPixelShader += pixelTokenizer.currentString;
  103746. continue;
  103747. }
  103748. newPixelShader += parseShaderUniforms(pixelTokenizer, technique, unTreatedUniforms);
  103749. }
  103750. // Create shader material
  103751. var shaderPath = {
  103752. vertex: program.vertexShader + id,
  103753. fragment: program.fragmentShader + id
  103754. };
  103755. var options = {
  103756. attributes: attributes,
  103757. uniforms: uniforms,
  103758. samplers: samplers,
  103759. needAlphaBlending: states && states.enable && states.enable.indexOf(3042) !== -1
  103760. };
  103761. BABYLON.Effect.ShadersStore[program.vertexShader + id + "VertexShader"] = newVertexShader;
  103762. BABYLON.Effect.ShadersStore[program.fragmentShader + id + "PixelShader"] = newPixelShader;
  103763. var shaderMaterial = new BABYLON.ShaderMaterial(id, gltfRuntime.scene, shaderPath, options);
  103764. shaderMaterial.onError = onShaderCompileError(program, shaderMaterial, onError);
  103765. shaderMaterial.onCompiled = onShaderCompileSuccess(gltfRuntime, shaderMaterial, technique, material, unTreatedUniforms, onSuccess);
  103766. shaderMaterial.sideOrientation = BABYLON.Material.CounterClockWiseSideOrientation;
  103767. if (states && states.functions) {
  103768. var functions = states.functions;
  103769. if (functions.cullFace && functions.cullFace[0] !== GLTF1.ECullingType.BACK) {
  103770. shaderMaterial.backFaceCulling = false;
  103771. }
  103772. var blendFunc = functions.blendFuncSeparate;
  103773. if (blendFunc) {
  103774. 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) {
  103775. shaderMaterial.alphaMode = BABYLON.Engine.ALPHA_COMBINE;
  103776. }
  103777. else if (blendFunc[0] === GLTF1.EBlendingFunction.ONE && blendFunc[1] === GLTF1.EBlendingFunction.ONE && blendFunc[2] === GLTF1.EBlendingFunction.ZERO && blendFunc[3] === GLTF1.EBlendingFunction.ONE) {
  103778. shaderMaterial.alphaMode = BABYLON.Engine.ALPHA_ONEONE;
  103779. }
  103780. else if (blendFunc[0] === GLTF1.EBlendingFunction.SRC_ALPHA && blendFunc[1] === GLTF1.EBlendingFunction.ONE && blendFunc[2] === GLTF1.EBlendingFunction.ZERO && blendFunc[3] === GLTF1.EBlendingFunction.ONE) {
  103781. shaderMaterial.alphaMode = BABYLON.Engine.ALPHA_ADD;
  103782. }
  103783. 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) {
  103784. shaderMaterial.alphaMode = BABYLON.Engine.ALPHA_SUBTRACT;
  103785. }
  103786. else if (blendFunc[0] === GLTF1.EBlendingFunction.DST_COLOR && blendFunc[1] === GLTF1.EBlendingFunction.ZERO && blendFunc[2] === GLTF1.EBlendingFunction.ONE && blendFunc[3] === GLTF1.EBlendingFunction.ONE) {
  103787. shaderMaterial.alphaMode = BABYLON.Engine.ALPHA_MULTIPLY;
  103788. }
  103789. 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) {
  103790. shaderMaterial.alphaMode = BABYLON.Engine.ALPHA_MAXIMIZED;
  103791. }
  103792. }
  103793. }
  103794. };
  103795. return GLTFLoaderBase;
  103796. }());
  103797. GLTF1.GLTFLoaderBase = GLTFLoaderBase;
  103798. /**
  103799. * glTF V1 Loader
  103800. */
  103801. var GLTFLoader = /** @class */ (function () {
  103802. function GLTFLoader() {
  103803. // #region Stubs for IGLTFLoader interface
  103804. this.coordinateSystemMode = BABYLON.GLTFLoaderCoordinateSystemMode.AUTO;
  103805. this.animationStartMode = BABYLON.GLTFLoaderAnimationStartMode.FIRST;
  103806. this.compileMaterials = false;
  103807. this.useClipPlane = false;
  103808. this.compileShadowGenerators = false;
  103809. this.preprocessUrlAsync = function (url) { return Promise.resolve(url); };
  103810. this.onMeshLoadedObservable = new BABYLON.Observable();
  103811. this.onTextureLoadedObservable = new BABYLON.Observable();
  103812. this.onMaterialLoadedObservable = new BABYLON.Observable();
  103813. this.onCameraLoadedObservable = new BABYLON.Observable();
  103814. this.onCompleteObservable = new BABYLON.Observable();
  103815. this.onDisposeObservable = new BABYLON.Observable();
  103816. this.onExtensionLoadedObservable = new BABYLON.Observable();
  103817. this.state = null;
  103818. }
  103819. GLTFLoader.RegisterExtension = function (extension) {
  103820. if (GLTFLoader.Extensions[extension.name]) {
  103821. BABYLON.Tools.Error("Tool with the same name \"" + extension.name + "\" already exists");
  103822. return;
  103823. }
  103824. GLTFLoader.Extensions[extension.name] = extension;
  103825. };
  103826. GLTFLoader.prototype.dispose = function () { };
  103827. // #endregion
  103828. GLTFLoader.prototype._importMeshAsync = function (meshesNames, scene, data, rootUrl, onSuccess, onProgress, onError) {
  103829. var _this = this;
  103830. scene.useRightHandedSystem = true;
  103831. GLTF1.GLTFLoaderExtension.LoadRuntimeAsync(scene, data, rootUrl, function (gltfRuntime) {
  103832. gltfRuntime.importOnlyMeshes = true;
  103833. if (meshesNames === "") {
  103834. gltfRuntime.importMeshesNames = [];
  103835. }
  103836. else if (typeof meshesNames === "string") {
  103837. gltfRuntime.importMeshesNames = [meshesNames];
  103838. }
  103839. else if (meshesNames && !(meshesNames instanceof Array)) {
  103840. gltfRuntime.importMeshesNames = [meshesNames];
  103841. }
  103842. else {
  103843. gltfRuntime.importMeshesNames = [];
  103844. BABYLON.Tools.Warn("Argument meshesNames must be of type string or string[]");
  103845. }
  103846. // Create nodes
  103847. _this._createNodes(gltfRuntime);
  103848. var meshes = new Array();
  103849. var skeletons = new Array();
  103850. // Fill arrays of meshes and skeletons
  103851. for (var nde in gltfRuntime.nodes) {
  103852. var node = gltfRuntime.nodes[nde];
  103853. if (node.babylonNode instanceof BABYLON.AbstractMesh) {
  103854. meshes.push(node.babylonNode);
  103855. }
  103856. }
  103857. for (var skl in gltfRuntime.skins) {
  103858. var skin = gltfRuntime.skins[skl];
  103859. if (skin.babylonSkeleton instanceof BABYLON.Skeleton) {
  103860. skeletons.push(skin.babylonSkeleton);
  103861. }
  103862. }
  103863. // Load buffers, shaders, materials, etc.
  103864. _this._loadBuffersAsync(gltfRuntime, function () {
  103865. _this._loadShadersAsync(gltfRuntime, function () {
  103866. importMaterials(gltfRuntime);
  103867. postLoad(gltfRuntime);
  103868. if (!BABYLON.GLTFFileLoader.IncrementalLoading && onSuccess) {
  103869. onSuccess(meshes, skeletons);
  103870. }
  103871. });
  103872. }, onProgress);
  103873. if (BABYLON.GLTFFileLoader.IncrementalLoading && onSuccess) {
  103874. onSuccess(meshes, skeletons);
  103875. }
  103876. }, onError);
  103877. return true;
  103878. };
  103879. /**
  103880. * Imports one or more meshes from a loaded gltf file and adds them to the scene
  103881. * @param meshesNames a string or array of strings of the mesh names that should be loaded from the file
  103882. * @param scene the scene the meshes should be added to
  103883. * @param data gltf data containing information of the meshes in a loaded file
  103884. * @param rootUrl root url to load from
  103885. * @param onProgress event that fires when loading progress has occured
  103886. * @returns a promise containg the loaded meshes, particles, skeletons and animations
  103887. */
  103888. GLTFLoader.prototype.importMeshAsync = function (meshesNames, scene, data, rootUrl, onProgress) {
  103889. var _this = this;
  103890. return new Promise(function (resolve, reject) {
  103891. _this._importMeshAsync(meshesNames, scene, data, rootUrl, function (meshes, skeletons) {
  103892. resolve({
  103893. meshes: meshes,
  103894. particleSystems: [],
  103895. skeletons: skeletons,
  103896. animationGroups: []
  103897. });
  103898. }, onProgress, function (message) {
  103899. reject(new Error(message));
  103900. });
  103901. });
  103902. };
  103903. GLTFLoader.prototype._loadAsync = function (scene, data, rootUrl, onSuccess, onProgress, onError) {
  103904. var _this = this;
  103905. scene.useRightHandedSystem = true;
  103906. GLTF1.GLTFLoaderExtension.LoadRuntimeAsync(scene, data, rootUrl, function (gltfRuntime) {
  103907. // Load runtime extensios
  103908. GLTF1.GLTFLoaderExtension.LoadRuntimeExtensionsAsync(gltfRuntime, function () {
  103909. // Create nodes
  103910. _this._createNodes(gltfRuntime);
  103911. // Load buffers, shaders, materials, etc.
  103912. _this._loadBuffersAsync(gltfRuntime, function () {
  103913. _this._loadShadersAsync(gltfRuntime, function () {
  103914. importMaterials(gltfRuntime);
  103915. postLoad(gltfRuntime);
  103916. if (!BABYLON.GLTFFileLoader.IncrementalLoading) {
  103917. onSuccess();
  103918. }
  103919. });
  103920. });
  103921. if (BABYLON.GLTFFileLoader.IncrementalLoading) {
  103922. onSuccess();
  103923. }
  103924. }, onError);
  103925. }, onError);
  103926. };
  103927. /**
  103928. * Imports all objects from a loaded gltf file and adds them to the scene
  103929. * @param scene the scene the objects should be added to
  103930. * @param data gltf data containing information of the meshes in a loaded file
  103931. * @param rootUrl root url to load from
  103932. * @param onProgress event that fires when loading progress has occured
  103933. * @returns a promise which completes when objects have been loaded to the scene
  103934. */
  103935. GLTFLoader.prototype.loadAsync = function (scene, data, rootUrl, onProgress) {
  103936. var _this = this;
  103937. return new Promise(function (resolve, reject) {
  103938. _this._loadAsync(scene, data, rootUrl, function () {
  103939. resolve();
  103940. }, onProgress, function (message) {
  103941. reject(new Error(message));
  103942. });
  103943. });
  103944. };
  103945. GLTFLoader.prototype._loadShadersAsync = function (gltfRuntime, onload) {
  103946. var hasShaders = false;
  103947. var processShader = function (sha, shader) {
  103948. GLTF1.GLTFLoaderExtension.LoadShaderStringAsync(gltfRuntime, sha, function (shaderString) {
  103949. if (shaderString instanceof ArrayBuffer) {
  103950. return;
  103951. }
  103952. gltfRuntime.loadedShaderCount++;
  103953. if (shaderString) {
  103954. BABYLON.Effect.ShadersStore[sha + (shader.type === GLTF1.EShaderType.VERTEX ? "VertexShader" : "PixelShader")] = shaderString;
  103955. }
  103956. if (gltfRuntime.loadedShaderCount === gltfRuntime.shaderscount) {
  103957. onload();
  103958. }
  103959. }, function () {
  103960. BABYLON.Tools.Error("Error when loading shader program named " + sha + " located at " + shader.uri);
  103961. });
  103962. };
  103963. for (var sha in gltfRuntime.shaders) {
  103964. hasShaders = true;
  103965. var shader = gltfRuntime.shaders[sha];
  103966. if (shader) {
  103967. processShader.bind(this, sha, shader)();
  103968. }
  103969. else {
  103970. BABYLON.Tools.Error("No shader named: " + sha);
  103971. }
  103972. }
  103973. if (!hasShaders) {
  103974. onload();
  103975. }
  103976. };
  103977. ;
  103978. GLTFLoader.prototype._loadBuffersAsync = function (gltfRuntime, onLoad, onProgress) {
  103979. var hasBuffers = false;
  103980. var processBuffer = function (buf, buffer) {
  103981. GLTF1.GLTFLoaderExtension.LoadBufferAsync(gltfRuntime, buf, function (bufferView) {
  103982. gltfRuntime.loadedBufferCount++;
  103983. if (bufferView) {
  103984. if (bufferView.byteLength != gltfRuntime.buffers[buf].byteLength) {
  103985. BABYLON.Tools.Error("Buffer named " + buf + " is length " + bufferView.byteLength + ". Expected: " + buffer.byteLength); // Improve error message
  103986. }
  103987. gltfRuntime.loadedBufferViews[buf] = bufferView;
  103988. }
  103989. if (gltfRuntime.loadedBufferCount === gltfRuntime.buffersCount) {
  103990. onLoad();
  103991. }
  103992. }, function () {
  103993. BABYLON.Tools.Error("Error when loading buffer named " + buf + " located at " + buffer.uri);
  103994. });
  103995. };
  103996. for (var buf in gltfRuntime.buffers) {
  103997. hasBuffers = true;
  103998. var buffer = gltfRuntime.buffers[buf];
  103999. if (buffer) {
  104000. processBuffer.bind(this, buf, buffer)();
  104001. }
  104002. else {
  104003. BABYLON.Tools.Error("No buffer named: " + buf);
  104004. }
  104005. }
  104006. if (!hasBuffers) {
  104007. onLoad();
  104008. }
  104009. };
  104010. GLTFLoader.prototype._createNodes = function (gltfRuntime) {
  104011. var currentScene = gltfRuntime.currentScene;
  104012. if (currentScene) {
  104013. // Only one scene even if multiple scenes are defined
  104014. for (var i = 0; i < currentScene.nodes.length; i++) {
  104015. traverseNodes(gltfRuntime, currentScene.nodes[i], null);
  104016. }
  104017. }
  104018. else {
  104019. // Load all scenes
  104020. for (var thing in gltfRuntime.scenes) {
  104021. currentScene = gltfRuntime.scenes[thing];
  104022. for (var i = 0; i < currentScene.nodes.length; i++) {
  104023. traverseNodes(gltfRuntime, currentScene.nodes[i], null);
  104024. }
  104025. }
  104026. }
  104027. };
  104028. GLTFLoader.Extensions = {};
  104029. return GLTFLoader;
  104030. }());
  104031. GLTF1.GLTFLoader = GLTFLoader;
  104032. ;
  104033. BABYLON.GLTFFileLoader.CreateGLTFLoaderV1 = function () { return new GLTFLoader(); };
  104034. })(GLTF1 = BABYLON.GLTF1 || (BABYLON.GLTF1 = {}));
  104035. })(BABYLON || (BABYLON = {}));
  104036. //# sourceMappingURL=babylon.glTFLoader.js.map
  104037. var BABYLON;
  104038. (function (BABYLON) {
  104039. var GLTF1;
  104040. (function (GLTF1) {
  104041. /**
  104042. * Utils functions for GLTF
  104043. */
  104044. var GLTFUtils = /** @class */ (function () {
  104045. function GLTFUtils() {
  104046. }
  104047. /**
  104048. * Sets the given "parameter" matrix
  104049. * @param scene: the {BABYLON.Scene} object
  104050. * @param source: the source node where to pick the matrix
  104051. * @param parameter: the GLTF technique parameter
  104052. * @param uniformName: the name of the shader's uniform
  104053. * @param shaderMaterial: the shader material
  104054. */
  104055. GLTFUtils.SetMatrix = function (scene, source, parameter, uniformName, shaderMaterial) {
  104056. var mat = null;
  104057. if (parameter.semantic === "MODEL") {
  104058. mat = source.getWorldMatrix();
  104059. }
  104060. else if (parameter.semantic === "PROJECTION") {
  104061. mat = scene.getProjectionMatrix();
  104062. }
  104063. else if (parameter.semantic === "VIEW") {
  104064. mat = scene.getViewMatrix();
  104065. }
  104066. else if (parameter.semantic === "MODELVIEWINVERSETRANSPOSE") {
  104067. mat = BABYLON.Matrix.Transpose(source.getWorldMatrix().multiply(scene.getViewMatrix()).invert());
  104068. }
  104069. else if (parameter.semantic === "MODELVIEW") {
  104070. mat = source.getWorldMatrix().multiply(scene.getViewMatrix());
  104071. }
  104072. else if (parameter.semantic === "MODELVIEWPROJECTION") {
  104073. mat = source.getWorldMatrix().multiply(scene.getTransformMatrix());
  104074. }
  104075. else if (parameter.semantic === "MODELINVERSE") {
  104076. mat = source.getWorldMatrix().invert();
  104077. }
  104078. else if (parameter.semantic === "VIEWINVERSE") {
  104079. mat = scene.getViewMatrix().invert();
  104080. }
  104081. else if (parameter.semantic === "PROJECTIONINVERSE") {
  104082. mat = scene.getProjectionMatrix().invert();
  104083. }
  104084. else if (parameter.semantic === "MODELVIEWINVERSE") {
  104085. mat = source.getWorldMatrix().multiply(scene.getViewMatrix()).invert();
  104086. }
  104087. else if (parameter.semantic === "MODELVIEWPROJECTIONINVERSE") {
  104088. mat = source.getWorldMatrix().multiply(scene.getTransformMatrix()).invert();
  104089. }
  104090. else if (parameter.semantic === "MODELINVERSETRANSPOSE") {
  104091. mat = BABYLON.Matrix.Transpose(source.getWorldMatrix().invert());
  104092. }
  104093. else {
  104094. debugger;
  104095. }
  104096. if (mat) {
  104097. switch (parameter.type) {
  104098. case GLTF1.EParameterType.FLOAT_MAT2:
  104099. shaderMaterial.setMatrix2x2(uniformName, BABYLON.Matrix.GetAsMatrix2x2(mat));
  104100. break;
  104101. case GLTF1.EParameterType.FLOAT_MAT3:
  104102. shaderMaterial.setMatrix3x3(uniformName, BABYLON.Matrix.GetAsMatrix3x3(mat));
  104103. break;
  104104. case GLTF1.EParameterType.FLOAT_MAT4:
  104105. shaderMaterial.setMatrix(uniformName, mat);
  104106. break;
  104107. default: break;
  104108. }
  104109. }
  104110. };
  104111. /**
  104112. * Sets the given "parameter" matrix
  104113. * @param shaderMaterial: the shader material
  104114. * @param uniform: the name of the shader's uniform
  104115. * @param value: the value of the uniform
  104116. * @param type: the uniform's type (EParameterType FLOAT, VEC2, VEC3 or VEC4)
  104117. */
  104118. GLTFUtils.SetUniform = function (shaderMaterial, uniform, value, type) {
  104119. switch (type) {
  104120. case GLTF1.EParameterType.FLOAT:
  104121. shaderMaterial.setFloat(uniform, value);
  104122. return true;
  104123. case GLTF1.EParameterType.FLOAT_VEC2:
  104124. shaderMaterial.setVector2(uniform, BABYLON.Vector2.FromArray(value));
  104125. return true;
  104126. case GLTF1.EParameterType.FLOAT_VEC3:
  104127. shaderMaterial.setVector3(uniform, BABYLON.Vector3.FromArray(value));
  104128. return true;
  104129. case GLTF1.EParameterType.FLOAT_VEC4:
  104130. shaderMaterial.setVector4(uniform, BABYLON.Vector4.FromArray(value));
  104131. return true;
  104132. default: return false;
  104133. }
  104134. };
  104135. /**
  104136. * Returns the wrap mode of the texture
  104137. * @param mode: the mode value
  104138. */
  104139. GLTFUtils.GetWrapMode = function (mode) {
  104140. switch (mode) {
  104141. case GLTF1.ETextureWrapMode.CLAMP_TO_EDGE: return BABYLON.Texture.CLAMP_ADDRESSMODE;
  104142. case GLTF1.ETextureWrapMode.MIRRORED_REPEAT: return BABYLON.Texture.MIRROR_ADDRESSMODE;
  104143. case GLTF1.ETextureWrapMode.REPEAT: return BABYLON.Texture.WRAP_ADDRESSMODE;
  104144. default: return BABYLON.Texture.WRAP_ADDRESSMODE;
  104145. }
  104146. };
  104147. /**
  104148. * Returns the byte stride giving an accessor
  104149. * @param accessor: the GLTF accessor objet
  104150. */
  104151. GLTFUtils.GetByteStrideFromType = function (accessor) {
  104152. // Needs this function since "byteStride" isn't requiered in glTF format
  104153. var type = accessor.type;
  104154. switch (type) {
  104155. case "VEC2": return 2;
  104156. case "VEC3": return 3;
  104157. case "VEC4": return 4;
  104158. case "MAT2": return 4;
  104159. case "MAT3": return 9;
  104160. case "MAT4": return 16;
  104161. default: return 1;
  104162. }
  104163. };
  104164. /**
  104165. * Returns the texture filter mode giving a mode value
  104166. * @param mode: the filter mode value
  104167. */
  104168. GLTFUtils.GetTextureFilterMode = function (mode) {
  104169. switch (mode) {
  104170. case GLTF1.ETextureFilterType.LINEAR:
  104171. case GLTF1.ETextureFilterType.LINEAR_MIPMAP_NEAREST:
  104172. case GLTF1.ETextureFilterType.LINEAR_MIPMAP_LINEAR: return BABYLON.Texture.TRILINEAR_SAMPLINGMODE;
  104173. case GLTF1.ETextureFilterType.NEAREST:
  104174. case GLTF1.ETextureFilterType.NEAREST_MIPMAP_NEAREST: return BABYLON.Texture.NEAREST_SAMPLINGMODE;
  104175. default: return BABYLON.Texture.BILINEAR_SAMPLINGMODE;
  104176. }
  104177. };
  104178. GLTFUtils.GetBufferFromBufferView = function (gltfRuntime, bufferView, byteOffset, byteLength, componentType) {
  104179. var byteOffset = bufferView.byteOffset + byteOffset;
  104180. var loadedBufferView = gltfRuntime.loadedBufferViews[bufferView.buffer];
  104181. if (byteOffset + byteLength > loadedBufferView.byteLength) {
  104182. throw new Error("Buffer access is out of range");
  104183. }
  104184. var buffer = loadedBufferView.buffer;
  104185. byteOffset += loadedBufferView.byteOffset;
  104186. switch (componentType) {
  104187. case GLTF1.EComponentType.BYTE: return new Int8Array(buffer, byteOffset, byteLength);
  104188. case GLTF1.EComponentType.UNSIGNED_BYTE: return new Uint8Array(buffer, byteOffset, byteLength);
  104189. case GLTF1.EComponentType.SHORT: return new Int16Array(buffer, byteOffset, byteLength);
  104190. case GLTF1.EComponentType.UNSIGNED_SHORT: return new Uint16Array(buffer, byteOffset, byteLength);
  104191. default: return new Float32Array(buffer, byteOffset, byteLength);
  104192. }
  104193. };
  104194. /**
  104195. * Returns a buffer from its accessor
  104196. * @param gltfRuntime: the GLTF runtime
  104197. * @param accessor: the GLTF accessor
  104198. */
  104199. GLTFUtils.GetBufferFromAccessor = function (gltfRuntime, accessor) {
  104200. var bufferView = gltfRuntime.bufferViews[accessor.bufferView];
  104201. var byteLength = accessor.count * GLTFUtils.GetByteStrideFromType(accessor);
  104202. return GLTFUtils.GetBufferFromBufferView(gltfRuntime, bufferView, accessor.byteOffset, byteLength, accessor.componentType);
  104203. };
  104204. /**
  104205. * Decodes a buffer view into a string
  104206. * @param view: the buffer view
  104207. */
  104208. GLTFUtils.DecodeBufferToText = function (view) {
  104209. var result = "";
  104210. var length = view.byteLength;
  104211. for (var i = 0; i < length; ++i) {
  104212. result += String.fromCharCode(view[i]);
  104213. }
  104214. return result;
  104215. };
  104216. /**
  104217. * Returns the default material of gltf. Related to
  104218. * https://github.com/KhronosGroup/glTF/tree/master/specification/1.0#appendix-a-default-material
  104219. * @param scene: the Babylon.js scene
  104220. */
  104221. GLTFUtils.GetDefaultMaterial = function (scene) {
  104222. if (!GLTFUtils._DefaultMaterial) {
  104223. BABYLON.Effect.ShadersStore["GLTFDefaultMaterialVertexShader"] = [
  104224. "precision highp float;",
  104225. "",
  104226. "uniform mat4 worldView;",
  104227. "uniform mat4 projection;",
  104228. "",
  104229. "attribute vec3 position;",
  104230. "",
  104231. "void main(void)",
  104232. "{",
  104233. " gl_Position = projection * worldView * vec4(position, 1.0);",
  104234. "}"
  104235. ].join("\n");
  104236. BABYLON.Effect.ShadersStore["GLTFDefaultMaterialPixelShader"] = [
  104237. "precision highp float;",
  104238. "",
  104239. "uniform vec4 u_emission;",
  104240. "",
  104241. "void main(void)",
  104242. "{",
  104243. " gl_FragColor = u_emission;",
  104244. "}"
  104245. ].join("\n");
  104246. var shaderPath = {
  104247. vertex: "GLTFDefaultMaterial",
  104248. fragment: "GLTFDefaultMaterial"
  104249. };
  104250. var options = {
  104251. attributes: ["position"],
  104252. uniforms: ["worldView", "projection", "u_emission"],
  104253. samplers: new Array(),
  104254. needAlphaBlending: false
  104255. };
  104256. GLTFUtils._DefaultMaterial = new BABYLON.ShaderMaterial("GLTFDefaultMaterial", scene, shaderPath, options);
  104257. GLTFUtils._DefaultMaterial.setColor4("u_emission", new BABYLON.Color4(0.5, 0.5, 0.5, 1.0));
  104258. }
  104259. return GLTFUtils._DefaultMaterial;
  104260. };
  104261. // The GLTF default material
  104262. GLTFUtils._DefaultMaterial = null;
  104263. return GLTFUtils;
  104264. }());
  104265. GLTF1.GLTFUtils = GLTFUtils;
  104266. })(GLTF1 = BABYLON.GLTF1 || (BABYLON.GLTF1 = {}));
  104267. })(BABYLON || (BABYLON = {}));
  104268. //# sourceMappingURL=babylon.glTFLoaderUtils.js.map
  104269. var BABYLON;
  104270. (function (BABYLON) {
  104271. var GLTF1;
  104272. (function (GLTF1) {
  104273. var GLTFLoaderExtension = /** @class */ (function () {
  104274. function GLTFLoaderExtension(name) {
  104275. this._name = name;
  104276. }
  104277. Object.defineProperty(GLTFLoaderExtension.prototype, "name", {
  104278. get: function () {
  104279. return this._name;
  104280. },
  104281. enumerable: true,
  104282. configurable: true
  104283. });
  104284. /**
  104285. * Defines an override for loading the runtime
  104286. * Return true to stop further extensions from loading the runtime
  104287. */
  104288. GLTFLoaderExtension.prototype.loadRuntimeAsync = function (scene, data, rootUrl, onSuccess, onError) {
  104289. return false;
  104290. };
  104291. /**
  104292. * Defines an onverride for creating gltf runtime
  104293. * Return true to stop further extensions from creating the runtime
  104294. */
  104295. GLTFLoaderExtension.prototype.loadRuntimeExtensionsAsync = function (gltfRuntime, onSuccess, onError) {
  104296. return false;
  104297. };
  104298. /**
  104299. * Defines an override for loading buffers
  104300. * Return true to stop further extensions from loading this buffer
  104301. */
  104302. GLTFLoaderExtension.prototype.loadBufferAsync = function (gltfRuntime, id, onSuccess, onError, onProgress) {
  104303. return false;
  104304. };
  104305. /**
  104306. * Defines an override for loading texture buffers
  104307. * Return true to stop further extensions from loading this texture data
  104308. */
  104309. GLTFLoaderExtension.prototype.loadTextureBufferAsync = function (gltfRuntime, id, onSuccess, onError) {
  104310. return false;
  104311. };
  104312. /**
  104313. * Defines an override for creating textures
  104314. * Return true to stop further extensions from loading this texture
  104315. */
  104316. GLTFLoaderExtension.prototype.createTextureAsync = function (gltfRuntime, id, buffer, onSuccess, onError) {
  104317. return false;
  104318. };
  104319. /**
  104320. * Defines an override for loading shader strings
  104321. * Return true to stop further extensions from loading this shader data
  104322. */
  104323. GLTFLoaderExtension.prototype.loadShaderStringAsync = function (gltfRuntime, id, onSuccess, onError) {
  104324. return false;
  104325. };
  104326. /**
  104327. * Defines an override for loading materials
  104328. * Return true to stop further extensions from loading this material
  104329. */
  104330. GLTFLoaderExtension.prototype.loadMaterialAsync = function (gltfRuntime, id, onSuccess, onError) {
  104331. return false;
  104332. };
  104333. // ---------
  104334. // Utilities
  104335. // ---------
  104336. GLTFLoaderExtension.LoadRuntimeAsync = function (scene, data, rootUrl, onSuccess, onError) {
  104337. GLTFLoaderExtension.ApplyExtensions(function (loaderExtension) {
  104338. return loaderExtension.loadRuntimeAsync(scene, data, rootUrl, onSuccess, onError);
  104339. }, function () {
  104340. setTimeout(function () {
  104341. if (!onSuccess) {
  104342. return;
  104343. }
  104344. onSuccess(GLTF1.GLTFLoaderBase.CreateRuntime(data.json, scene, rootUrl));
  104345. });
  104346. });
  104347. };
  104348. GLTFLoaderExtension.LoadRuntimeExtensionsAsync = function (gltfRuntime, onSuccess, onError) {
  104349. GLTFLoaderExtension.ApplyExtensions(function (loaderExtension) {
  104350. return loaderExtension.loadRuntimeExtensionsAsync(gltfRuntime, onSuccess, onError);
  104351. }, function () {
  104352. setTimeout(function () {
  104353. onSuccess();
  104354. });
  104355. });
  104356. };
  104357. GLTFLoaderExtension.LoadBufferAsync = function (gltfRuntime, id, onSuccess, onError, onProgress) {
  104358. GLTFLoaderExtension.ApplyExtensions(function (loaderExtension) {
  104359. return loaderExtension.loadBufferAsync(gltfRuntime, id, onSuccess, onError, onProgress);
  104360. }, function () {
  104361. GLTF1.GLTFLoaderBase.LoadBufferAsync(gltfRuntime, id, onSuccess, onError, onProgress);
  104362. });
  104363. };
  104364. GLTFLoaderExtension.LoadTextureAsync = function (gltfRuntime, id, onSuccess, onError) {
  104365. GLTFLoaderExtension.LoadTextureBufferAsync(gltfRuntime, id, function (buffer) {
  104366. if (buffer) {
  104367. GLTFLoaderExtension.CreateTextureAsync(gltfRuntime, id, buffer, onSuccess, onError);
  104368. }
  104369. }, onError);
  104370. };
  104371. GLTFLoaderExtension.LoadShaderStringAsync = function (gltfRuntime, id, onSuccess, onError) {
  104372. GLTFLoaderExtension.ApplyExtensions(function (loaderExtension) {
  104373. return loaderExtension.loadShaderStringAsync(gltfRuntime, id, onSuccess, onError);
  104374. }, function () {
  104375. GLTF1.GLTFLoaderBase.LoadShaderStringAsync(gltfRuntime, id, onSuccess, onError);
  104376. });
  104377. };
  104378. GLTFLoaderExtension.LoadMaterialAsync = function (gltfRuntime, id, onSuccess, onError) {
  104379. GLTFLoaderExtension.ApplyExtensions(function (loaderExtension) {
  104380. return loaderExtension.loadMaterialAsync(gltfRuntime, id, onSuccess, onError);
  104381. }, function () {
  104382. GLTF1.GLTFLoaderBase.LoadMaterialAsync(gltfRuntime, id, onSuccess, onError);
  104383. });
  104384. };
  104385. GLTFLoaderExtension.LoadTextureBufferAsync = function (gltfRuntime, id, onSuccess, onError) {
  104386. GLTFLoaderExtension.ApplyExtensions(function (loaderExtension) {
  104387. return loaderExtension.loadTextureBufferAsync(gltfRuntime, id, onSuccess, onError);
  104388. }, function () {
  104389. GLTF1.GLTFLoaderBase.LoadTextureBufferAsync(gltfRuntime, id, onSuccess, onError);
  104390. });
  104391. };
  104392. GLTFLoaderExtension.CreateTextureAsync = function (gltfRuntime, id, buffer, onSuccess, onError) {
  104393. GLTFLoaderExtension.ApplyExtensions(function (loaderExtension) {
  104394. return loaderExtension.createTextureAsync(gltfRuntime, id, buffer, onSuccess, onError);
  104395. }, function () {
  104396. GLTF1.GLTFLoaderBase.CreateTextureAsync(gltfRuntime, id, buffer, onSuccess, onError);
  104397. });
  104398. };
  104399. GLTFLoaderExtension.ApplyExtensions = function (func, defaultFunc) {
  104400. for (var extensionName in GLTF1.GLTFLoader.Extensions) {
  104401. var loaderExtension = GLTF1.GLTFLoader.Extensions[extensionName];
  104402. if (func(loaderExtension)) {
  104403. return;
  104404. }
  104405. }
  104406. defaultFunc();
  104407. };
  104408. return GLTFLoaderExtension;
  104409. }());
  104410. GLTF1.GLTFLoaderExtension = GLTFLoaderExtension;
  104411. })(GLTF1 = BABYLON.GLTF1 || (BABYLON.GLTF1 = {}));
  104412. })(BABYLON || (BABYLON = {}));
  104413. //# sourceMappingURL=babylon.glTFLoaderExtension.js.map
  104414. var BABYLON;
  104415. (function (BABYLON) {
  104416. var GLTF1;
  104417. (function (GLTF1) {
  104418. var BinaryExtensionBufferName = "binary_glTF";
  104419. ;
  104420. ;
  104421. var GLTFBinaryExtension = /** @class */ (function (_super) {
  104422. __extends(GLTFBinaryExtension, _super);
  104423. function GLTFBinaryExtension() {
  104424. return _super.call(this, "KHR_binary_glTF") || this;
  104425. }
  104426. GLTFBinaryExtension.prototype.loadRuntimeAsync = function (scene, data, rootUrl, onSuccess, onError) {
  104427. var extensionsUsed = data.json.extensionsUsed;
  104428. if (!extensionsUsed || extensionsUsed.indexOf(this.name) === -1 || !data.bin) {
  104429. return false;
  104430. }
  104431. this._bin = data.bin;
  104432. onSuccess(GLTF1.GLTFLoaderBase.CreateRuntime(data.json, scene, rootUrl));
  104433. return true;
  104434. };
  104435. GLTFBinaryExtension.prototype.loadBufferAsync = function (gltfRuntime, id, onSuccess, onError) {
  104436. if (gltfRuntime.extensionsUsed.indexOf(this.name) === -1) {
  104437. return false;
  104438. }
  104439. if (id !== BinaryExtensionBufferName) {
  104440. return false;
  104441. }
  104442. onSuccess(this._bin);
  104443. return true;
  104444. };
  104445. GLTFBinaryExtension.prototype.loadTextureBufferAsync = function (gltfRuntime, id, onSuccess, onError) {
  104446. var texture = gltfRuntime.textures[id];
  104447. var source = gltfRuntime.images[texture.source];
  104448. if (!source.extensions || !(this.name in source.extensions)) {
  104449. return false;
  104450. }
  104451. var sourceExt = source.extensions[this.name];
  104452. var bufferView = gltfRuntime.bufferViews[sourceExt.bufferView];
  104453. var buffer = GLTF1.GLTFUtils.GetBufferFromBufferView(gltfRuntime, bufferView, 0, bufferView.byteLength, GLTF1.EComponentType.UNSIGNED_BYTE);
  104454. onSuccess(buffer);
  104455. return true;
  104456. };
  104457. GLTFBinaryExtension.prototype.loadShaderStringAsync = function (gltfRuntime, id, onSuccess, onError) {
  104458. var shader = gltfRuntime.shaders[id];
  104459. if (!shader.extensions || !(this.name in shader.extensions)) {
  104460. return false;
  104461. }
  104462. var binaryExtensionShader = shader.extensions[this.name];
  104463. var bufferView = gltfRuntime.bufferViews[binaryExtensionShader.bufferView];
  104464. var shaderBytes = GLTF1.GLTFUtils.GetBufferFromBufferView(gltfRuntime, bufferView, 0, bufferView.byteLength, GLTF1.EComponentType.UNSIGNED_BYTE);
  104465. setTimeout(function () {
  104466. var shaderString = GLTF1.GLTFUtils.DecodeBufferToText(shaderBytes);
  104467. onSuccess(shaderString);
  104468. });
  104469. return true;
  104470. };
  104471. return GLTFBinaryExtension;
  104472. }(GLTF1.GLTFLoaderExtension));
  104473. GLTF1.GLTFBinaryExtension = GLTFBinaryExtension;
  104474. GLTF1.GLTFLoader.RegisterExtension(new GLTFBinaryExtension());
  104475. })(GLTF1 = BABYLON.GLTF1 || (BABYLON.GLTF1 = {}));
  104476. })(BABYLON || (BABYLON = {}));
  104477. //# sourceMappingURL=babylon.glTFBinaryExtension.js.map
  104478. var BABYLON;
  104479. (function (BABYLON) {
  104480. var GLTF1;
  104481. (function (GLTF1) {
  104482. ;
  104483. ;
  104484. ;
  104485. var GLTFMaterialsCommonExtension = /** @class */ (function (_super) {
  104486. __extends(GLTFMaterialsCommonExtension, _super);
  104487. function GLTFMaterialsCommonExtension() {
  104488. return _super.call(this, "KHR_materials_common") || this;
  104489. }
  104490. GLTFMaterialsCommonExtension.prototype.loadRuntimeExtensionsAsync = function (gltfRuntime, onSuccess, onError) {
  104491. if (!gltfRuntime.extensions)
  104492. return false;
  104493. var extension = gltfRuntime.extensions[this.name];
  104494. if (!extension)
  104495. return false;
  104496. // Create lights
  104497. var lights = extension.lights;
  104498. if (lights) {
  104499. for (var thing in lights) {
  104500. var light = lights[thing];
  104501. switch (light.type) {
  104502. case "ambient":
  104503. var ambientLight = new BABYLON.HemisphericLight(light.name, new BABYLON.Vector3(0, 1, 0), gltfRuntime.scene);
  104504. var ambient = light.ambient;
  104505. if (ambient) {
  104506. ambientLight.diffuse = BABYLON.Color3.FromArray(ambient.color || [1, 1, 1]);
  104507. }
  104508. break;
  104509. case "point":
  104510. var pointLight = new BABYLON.PointLight(light.name, new BABYLON.Vector3(10, 10, 10), gltfRuntime.scene);
  104511. var point = light.point;
  104512. if (point) {
  104513. pointLight.diffuse = BABYLON.Color3.FromArray(point.color || [1, 1, 1]);
  104514. }
  104515. break;
  104516. case "directional":
  104517. var dirLight = new BABYLON.DirectionalLight(light.name, new BABYLON.Vector3(0, -1, 0), gltfRuntime.scene);
  104518. var directional = light.directional;
  104519. if (directional) {
  104520. dirLight.diffuse = BABYLON.Color3.FromArray(directional.color || [1, 1, 1]);
  104521. }
  104522. break;
  104523. case "spot":
  104524. var spot = light.spot;
  104525. if (spot) {
  104526. 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);
  104527. spotLight.diffuse = BABYLON.Color3.FromArray(spot.color || [1, 1, 1]);
  104528. }
  104529. break;
  104530. default:
  104531. BABYLON.Tools.Warn("GLTF Material Common extension: light type \"" + light.type + "\” not supported");
  104532. break;
  104533. }
  104534. }
  104535. }
  104536. return false;
  104537. };
  104538. GLTFMaterialsCommonExtension.prototype.loadMaterialAsync = function (gltfRuntime, id, onSuccess, onError) {
  104539. var material = gltfRuntime.materials[id];
  104540. if (!material || !material.extensions)
  104541. return false;
  104542. var extension = material.extensions[this.name];
  104543. if (!extension)
  104544. return false;
  104545. var standardMaterial = new BABYLON.StandardMaterial(id, gltfRuntime.scene);
  104546. standardMaterial.sideOrientation = BABYLON.Material.CounterClockWiseSideOrientation;
  104547. if (extension.technique === "CONSTANT") {
  104548. standardMaterial.disableLighting = true;
  104549. }
  104550. standardMaterial.backFaceCulling = extension.doubleSided === undefined ? false : !extension.doubleSided;
  104551. standardMaterial.alpha = extension.values.transparency === undefined ? 1.0 : extension.values.transparency;
  104552. standardMaterial.specularPower = extension.values.shininess === undefined ? 0.0 : extension.values.shininess;
  104553. // Ambient
  104554. if (typeof extension.values.ambient === "string") {
  104555. this._loadTexture(gltfRuntime, extension.values.ambient, standardMaterial, "ambientTexture", onError);
  104556. }
  104557. else {
  104558. standardMaterial.ambientColor = BABYLON.Color3.FromArray(extension.values.ambient || [0, 0, 0]);
  104559. }
  104560. // Diffuse
  104561. if (typeof extension.values.diffuse === "string") {
  104562. this._loadTexture(gltfRuntime, extension.values.diffuse, standardMaterial, "diffuseTexture", onError);
  104563. }
  104564. else {
  104565. standardMaterial.diffuseColor = BABYLON.Color3.FromArray(extension.values.diffuse || [0, 0, 0]);
  104566. }
  104567. // Emission
  104568. if (typeof extension.values.emission === "string") {
  104569. this._loadTexture(gltfRuntime, extension.values.emission, standardMaterial, "emissiveTexture", onError);
  104570. }
  104571. else {
  104572. standardMaterial.emissiveColor = BABYLON.Color3.FromArray(extension.values.emission || [0, 0, 0]);
  104573. }
  104574. // Specular
  104575. if (typeof extension.values.specular === "string") {
  104576. this._loadTexture(gltfRuntime, extension.values.specular, standardMaterial, "specularTexture", onError);
  104577. }
  104578. else {
  104579. standardMaterial.specularColor = BABYLON.Color3.FromArray(extension.values.specular || [0, 0, 0]);
  104580. }
  104581. return true;
  104582. };
  104583. GLTFMaterialsCommonExtension.prototype._loadTexture = function (gltfRuntime, id, material, propertyPath, onError) {
  104584. // Create buffer from texture url
  104585. GLTF1.GLTFLoaderBase.LoadTextureBufferAsync(gltfRuntime, id, function (buffer) {
  104586. // Create texture from buffer
  104587. GLTF1.GLTFLoaderBase.CreateTextureAsync(gltfRuntime, id, buffer, function (texture) { return material[propertyPath] = texture; }, onError);
  104588. }, onError);
  104589. };
  104590. return GLTFMaterialsCommonExtension;
  104591. }(GLTF1.GLTFLoaderExtension));
  104592. GLTF1.GLTFMaterialsCommonExtension = GLTFMaterialsCommonExtension;
  104593. GLTF1.GLTFLoader.RegisterExtension(new GLTFMaterialsCommonExtension());
  104594. })(GLTF1 = BABYLON.GLTF1 || (BABYLON.GLTF1 = {}));
  104595. })(BABYLON || (BABYLON = {}));
  104596. //# sourceMappingURL=babylon.glTFMaterialsCommonExtension.js.map
  104597. var BABYLON;
  104598. (function (BABYLON) {
  104599. var GLTF2;
  104600. (function (GLTF2) {
  104601. /** @hidden */
  104602. var _ArrayItem = /** @class */ (function () {
  104603. function _ArrayItem() {
  104604. }
  104605. /** @hidden */
  104606. _ArrayItem.Assign = function (values) {
  104607. if (values) {
  104608. for (var index = 0; index < values.length; index++) {
  104609. values[index]._index = index;
  104610. }
  104611. }
  104612. };
  104613. return _ArrayItem;
  104614. }());
  104615. GLTF2._ArrayItem = _ArrayItem;
  104616. })(GLTF2 = BABYLON.GLTF2 || (BABYLON.GLTF2 = {}));
  104617. })(BABYLON || (BABYLON = {}));
  104618. //# sourceMappingURL=babylon.glTFLoaderUtilities.js.map
  104619. //# sourceMappingURL=babylon.glTFLoaderInterfaces.js.map
  104620. /**
  104621. * Defines the module used to import/export glTF 2.0 assets
  104622. */
  104623. var BABYLON;
  104624. (function (BABYLON) {
  104625. var GLTF2;
  104626. (function (GLTF2) {
  104627. /**
  104628. * Loader for loading a glTF 2.0 asset
  104629. */
  104630. var GLTFLoader = /** @class */ (function () {
  104631. function GLTFLoader() {
  104632. /** @hidden */
  104633. this._completePromises = new Array();
  104634. this._disposed = false;
  104635. this._state = null;
  104636. this._extensions = {};
  104637. this._defaultSampler = {};
  104638. this._defaultBabylonMaterials = {};
  104639. this._requests = new Array();
  104640. /**
  104641. * Mode that determines the coordinate system to use.
  104642. */
  104643. this.coordinateSystemMode = BABYLON.GLTFLoaderCoordinateSystemMode.AUTO;
  104644. /**
  104645. * Mode that determines what animations will start.
  104646. */
  104647. this.animationStartMode = BABYLON.GLTFLoaderAnimationStartMode.FIRST;
  104648. /**
  104649. * Defines if the loader should compile materials.
  104650. */
  104651. this.compileMaterials = false;
  104652. /**
  104653. * Defines if the loader should also compile materials with clip planes.
  104654. */
  104655. this.useClipPlane = false;
  104656. /**
  104657. * Defines if the loader should compile shadow generators.
  104658. */
  104659. this.compileShadowGenerators = false;
  104660. /**
  104661. * Function called before loading a url referenced by the asset.
  104662. */
  104663. this.preprocessUrlAsync = function (url) { return Promise.resolve(url); };
  104664. /**
  104665. * Observable raised when the loader creates a mesh after parsing the glTF properties of the mesh.
  104666. */
  104667. this.onMeshLoadedObservable = new BABYLON.Observable();
  104668. /**
  104669. * Observable raised when the loader creates a texture after parsing the glTF properties of the texture.
  104670. */
  104671. this.onTextureLoadedObservable = new BABYLON.Observable();
  104672. /**
  104673. * Observable raised when the loader creates a material after parsing the glTF properties of the material.
  104674. */
  104675. this.onMaterialLoadedObservable = new BABYLON.Observable();
  104676. /**
  104677. * Observable raised when the loader creates a camera after parsing the glTF properties of the camera.
  104678. */
  104679. this.onCameraLoadedObservable = new BABYLON.Observable();
  104680. /**
  104681. * Observable raised when the asset is completely loaded, immediately before the loader is disposed.
  104682. * For assets with LODs, raised when all of the LODs are complete.
  104683. * For assets without LODs, raised when the model is complete, immediately after the loader resolves the returned promise.
  104684. */
  104685. this.onCompleteObservable = new BABYLON.Observable();
  104686. /**
  104687. * Observable raised after the loader is disposed.
  104688. */
  104689. this.onDisposeObservable = new BABYLON.Observable();
  104690. /**
  104691. * Observable raised after a loader extension is created.
  104692. * Set additional options for a loader extension in this event.
  104693. */
  104694. this.onExtensionLoadedObservable = new BABYLON.Observable();
  104695. }
  104696. /** @hidden */
  104697. GLTFLoader._Register = function (name, factory) {
  104698. if (GLTFLoader._ExtensionFactories[name]) {
  104699. BABYLON.Tools.Error("Extension with the name '" + name + "' already exists");
  104700. return;
  104701. }
  104702. GLTFLoader._ExtensionFactories[name] = factory;
  104703. // Keep the order of registration so that extensions registered first are called first.
  104704. GLTFLoader._ExtensionNames.push(name);
  104705. };
  104706. Object.defineProperty(GLTFLoader.prototype, "state", {
  104707. /**
  104708. * Loader state or null if the loader is not active.
  104709. */
  104710. get: function () {
  104711. return this._state;
  104712. },
  104713. enumerable: true,
  104714. configurable: true
  104715. });
  104716. /**
  104717. * Disposes the loader, releases resources during load, and cancels any outstanding requests.
  104718. */
  104719. GLTFLoader.prototype.dispose = function () {
  104720. if (this._disposed) {
  104721. return;
  104722. }
  104723. this._disposed = true;
  104724. this.onDisposeObservable.notifyObservers(this);
  104725. this.onDisposeObservable.clear();
  104726. this._clear();
  104727. };
  104728. /**
  104729. * Imports one or more meshes from the loaded glTF data and adds them to the scene
  104730. * @param meshesNames a string or array of strings of the mesh names that should be loaded from the file
  104731. * @param scene the scene the meshes should be added to
  104732. * @param data the glTF data to load
  104733. * @param rootUrl root url to load from
  104734. * @param onProgress event that fires when loading progress has occured
  104735. * @returns a promise containg the loaded meshes, particles, skeletons and animations
  104736. */
  104737. GLTFLoader.prototype.importMeshAsync = function (meshesNames, scene, data, rootUrl, onProgress) {
  104738. var _this = this;
  104739. return Promise.resolve().then(function () {
  104740. var nodes = null;
  104741. if (meshesNames) {
  104742. var nodeMap_1 = {};
  104743. if (_this._gltf.nodes) {
  104744. for (var _i = 0, _a = _this._gltf.nodes; _i < _a.length; _i++) {
  104745. var node = _a[_i];
  104746. if (node.name) {
  104747. nodeMap_1[node.name] = node;
  104748. }
  104749. }
  104750. }
  104751. var names = (meshesNames instanceof Array) ? meshesNames : [meshesNames];
  104752. nodes = names.map(function (name) {
  104753. var node = nodeMap_1[name];
  104754. if (!node) {
  104755. throw new Error("Failed to find node '" + name + "'");
  104756. }
  104757. return node;
  104758. });
  104759. }
  104760. return _this._loadAsync(nodes, scene, data, rootUrl, onProgress).then(function () {
  104761. return {
  104762. meshes: _this._getMeshes(),
  104763. particleSystems: [],
  104764. skeletons: _this._getSkeletons(),
  104765. animationGroups: _this._getAnimationGroups()
  104766. };
  104767. });
  104768. });
  104769. };
  104770. /**
  104771. * Imports all objects from the loaded glTF data and adds them to the scene
  104772. * @param scene the scene the objects should be added to
  104773. * @param data the glTF data to load
  104774. * @param rootUrl root url to load from
  104775. * @param onProgress event that fires when loading progress has occured
  104776. * @returns a promise which completes when objects have been loaded to the scene
  104777. */
  104778. GLTFLoader.prototype.loadAsync = function (scene, data, rootUrl, onProgress) {
  104779. return this._loadAsync(null, scene, data, rootUrl, onProgress);
  104780. };
  104781. GLTFLoader.prototype._loadAsync = function (nodes, scene, data, rootUrl, onProgress) {
  104782. var _this = this;
  104783. return Promise.resolve().then(function () {
  104784. _this._babylonScene = scene;
  104785. _this._rootUrl = rootUrl;
  104786. _this._progressCallback = onProgress;
  104787. _this._state = BABYLON.GLTFLoaderState.LOADING;
  104788. _this._loadData(data);
  104789. _this._loadExtensions();
  104790. _this._checkExtensions();
  104791. var promises = new Array();
  104792. if (nodes) {
  104793. promises.push(_this._loadNodesAsync(nodes));
  104794. }
  104795. else {
  104796. var scene_1 = GLTFLoader._GetProperty("#/scene", _this._gltf.scenes, _this._gltf.scene || 0);
  104797. promises.push(_this._loadSceneAsync("#/scenes/" + scene_1._index, scene_1));
  104798. }
  104799. if (_this.compileMaterials) {
  104800. promises.push(_this._compileMaterialsAsync());
  104801. }
  104802. if (_this.compileShadowGenerators) {
  104803. promises.push(_this._compileShadowGeneratorsAsync());
  104804. }
  104805. var resultPromise = Promise.all(promises).then(function () {
  104806. _this._state = BABYLON.GLTFLoaderState.READY;
  104807. _this._startAnimations();
  104808. });
  104809. resultPromise.then(function () {
  104810. _this._rootBabylonMesh.setEnabled(true);
  104811. BABYLON.Tools.SetImmediate(function () {
  104812. if (!_this._disposed) {
  104813. Promise.all(_this._completePromises).then(function () {
  104814. _this._state = BABYLON.GLTFLoaderState.COMPLETE;
  104815. _this.onCompleteObservable.notifyObservers(_this);
  104816. _this.onCompleteObservable.clear();
  104817. _this._clear();
  104818. }).catch(function (error) {
  104819. BABYLON.Tools.Error("glTF Loader: " + error.message);
  104820. _this._clear();
  104821. });
  104822. }
  104823. });
  104824. });
  104825. return resultPromise;
  104826. }).catch(function (error) {
  104827. if (!_this._disposed) {
  104828. BABYLON.Tools.Error("glTF Loader: " + error.message);
  104829. _this._clear();
  104830. throw error;
  104831. }
  104832. });
  104833. };
  104834. GLTFLoader.prototype._loadData = function (data) {
  104835. this._gltf = data.json;
  104836. this._setupData();
  104837. if (data.bin) {
  104838. var buffers = this._gltf.buffers;
  104839. if (buffers && buffers[0] && !buffers[0].uri) {
  104840. var binaryBuffer = buffers[0];
  104841. if (binaryBuffer.byteLength < data.bin.byteLength - 3 || binaryBuffer.byteLength > data.bin.byteLength) {
  104842. BABYLON.Tools.Warn("Binary buffer length (" + binaryBuffer.byteLength + ") from JSON does not match chunk length (" + data.bin.byteLength + ")");
  104843. }
  104844. binaryBuffer._data = Promise.resolve(data.bin);
  104845. }
  104846. else {
  104847. BABYLON.Tools.Warn("Unexpected BIN chunk");
  104848. }
  104849. }
  104850. };
  104851. GLTFLoader.prototype._setupData = function () {
  104852. GLTF2._ArrayItem.Assign(this._gltf.accessors);
  104853. GLTF2._ArrayItem.Assign(this._gltf.animations);
  104854. GLTF2._ArrayItem.Assign(this._gltf.buffers);
  104855. GLTF2._ArrayItem.Assign(this._gltf.bufferViews);
  104856. GLTF2._ArrayItem.Assign(this._gltf.cameras);
  104857. GLTF2._ArrayItem.Assign(this._gltf.images);
  104858. GLTF2._ArrayItem.Assign(this._gltf.materials);
  104859. GLTF2._ArrayItem.Assign(this._gltf.meshes);
  104860. GLTF2._ArrayItem.Assign(this._gltf.nodes);
  104861. GLTF2._ArrayItem.Assign(this._gltf.samplers);
  104862. GLTF2._ArrayItem.Assign(this._gltf.scenes);
  104863. GLTF2._ArrayItem.Assign(this._gltf.skins);
  104864. GLTF2._ArrayItem.Assign(this._gltf.textures);
  104865. if (this._gltf.nodes) {
  104866. var nodeParents = {};
  104867. for (var _i = 0, _a = this._gltf.nodes; _i < _a.length; _i++) {
  104868. var node = _a[_i];
  104869. if (node.children) {
  104870. for (var _b = 0, _c = node.children; _b < _c.length; _b++) {
  104871. var index = _c[_b];
  104872. nodeParents[index] = node._index;
  104873. }
  104874. }
  104875. }
  104876. var rootNode = this._createRootNode();
  104877. for (var _d = 0, _e = this._gltf.nodes; _d < _e.length; _d++) {
  104878. var node = _e[_d];
  104879. var parentIndex = nodeParents[node._index];
  104880. node._parent = parentIndex === undefined ? rootNode : this._gltf.nodes[parentIndex];
  104881. }
  104882. }
  104883. };
  104884. GLTFLoader.prototype._loadExtensions = function () {
  104885. for (var _i = 0, _a = GLTFLoader._ExtensionNames; _i < _a.length; _i++) {
  104886. var name_1 = _a[_i];
  104887. var extension = GLTFLoader._ExtensionFactories[name_1](this);
  104888. this._extensions[name_1] = extension;
  104889. this.onExtensionLoadedObservable.notifyObservers(extension);
  104890. }
  104891. this.onExtensionLoadedObservable.clear();
  104892. };
  104893. GLTFLoader.prototype._checkExtensions = function () {
  104894. if (this._gltf.extensionsRequired) {
  104895. for (var _i = 0, _a = this._gltf.extensionsRequired; _i < _a.length; _i++) {
  104896. var name_2 = _a[_i];
  104897. var extension = this._extensions[name_2];
  104898. if (!extension || !extension.enabled) {
  104899. throw new Error("Require extension " + name_2 + " is not available");
  104900. }
  104901. }
  104902. }
  104903. };
  104904. GLTFLoader.prototype._createRootNode = function () {
  104905. this._rootBabylonMesh = new BABYLON.Mesh("__root__", this._babylonScene);
  104906. this._rootBabylonMesh.setEnabled(false);
  104907. var rootNode = { _babylonMesh: this._rootBabylonMesh };
  104908. switch (this.coordinateSystemMode) {
  104909. case BABYLON.GLTFLoaderCoordinateSystemMode.AUTO: {
  104910. if (!this._babylonScene.useRightHandedSystem) {
  104911. rootNode.rotation = [0, 1, 0, 0];
  104912. rootNode.scale = [1, 1, -1];
  104913. GLTFLoader._LoadTransform(rootNode, this._rootBabylonMesh);
  104914. }
  104915. break;
  104916. }
  104917. case BABYLON.GLTFLoaderCoordinateSystemMode.FORCE_RIGHT_HANDED: {
  104918. this._babylonScene.useRightHandedSystem = true;
  104919. break;
  104920. }
  104921. default: {
  104922. throw new Error("Invalid coordinate system mode (" + this.coordinateSystemMode + ")");
  104923. }
  104924. }
  104925. this.onMeshLoadedObservable.notifyObservers(this._rootBabylonMesh);
  104926. return rootNode;
  104927. };
  104928. GLTFLoader.prototype._loadNodesAsync = function (nodes) {
  104929. var promises = new Array();
  104930. for (var _i = 0, nodes_1 = nodes; _i < nodes_1.length; _i++) {
  104931. var node = nodes_1[_i];
  104932. promises.push(this._loadNodeAsync("#/nodes/" + node._index, node));
  104933. }
  104934. promises.push(this._loadAnimationsAsync());
  104935. return Promise.all(promises).then(function () { });
  104936. };
  104937. /** @hidden */
  104938. GLTFLoader.prototype._loadSceneAsync = function (context, scene) {
  104939. var promise = GLTF2.GLTFLoaderExtension._LoadSceneAsync(this, context, scene);
  104940. if (promise) {
  104941. return promise;
  104942. }
  104943. var promises = new Array();
  104944. for (var _i = 0, _a = scene.nodes; _i < _a.length; _i++) {
  104945. var index = _a[_i];
  104946. var node = GLTFLoader._GetProperty(context + "/nodes/" + index, this._gltf.nodes, index);
  104947. promises.push(this._loadNodeAsync("#/nodes/" + node._index, node));
  104948. }
  104949. promises.push(this._loadAnimationsAsync());
  104950. return Promise.all(promises).then(function () { });
  104951. };
  104952. GLTFLoader.prototype._forEachPrimitive = function (node, callback) {
  104953. if (node._primitiveBabylonMeshes) {
  104954. for (var _i = 0, _a = node._primitiveBabylonMeshes; _i < _a.length; _i++) {
  104955. var babylonMesh = _a[_i];
  104956. callback(babylonMesh);
  104957. }
  104958. }
  104959. else {
  104960. callback(node._babylonMesh);
  104961. }
  104962. };
  104963. GLTFLoader.prototype._getMeshes = function () {
  104964. var meshes = new Array();
  104965. // Root mesh is always first.
  104966. meshes.push(this._rootBabylonMesh);
  104967. var nodes = this._gltf.nodes;
  104968. if (nodes) {
  104969. for (var _i = 0, nodes_2 = nodes; _i < nodes_2.length; _i++) {
  104970. var node = nodes_2[_i];
  104971. if (node._babylonMesh) {
  104972. meshes.push(node._babylonMesh);
  104973. }
  104974. if (node._primitiveBabylonMeshes) {
  104975. for (var _a = 0, _b = node._primitiveBabylonMeshes; _a < _b.length; _a++) {
  104976. var babylonMesh = _b[_a];
  104977. meshes.push(babylonMesh);
  104978. }
  104979. }
  104980. }
  104981. }
  104982. return meshes;
  104983. };
  104984. GLTFLoader.prototype._getSkeletons = function () {
  104985. var skeletons = new Array();
  104986. var skins = this._gltf.skins;
  104987. if (skins) {
  104988. for (var _i = 0, skins_1 = skins; _i < skins_1.length; _i++) {
  104989. var skin = skins_1[_i];
  104990. if (skin._babylonSkeleton) {
  104991. skeletons.push(skin._babylonSkeleton);
  104992. }
  104993. }
  104994. }
  104995. return skeletons;
  104996. };
  104997. GLTFLoader.prototype._getAnimationGroups = function () {
  104998. var animationGroups = new Array();
  104999. var animations = this._gltf.animations;
  105000. if (animations) {
  105001. for (var _i = 0, animations_1 = animations; _i < animations_1.length; _i++) {
  105002. var animation = animations_1[_i];
  105003. if (animation._babylonAnimationGroup) {
  105004. animationGroups.push(animation._babylonAnimationGroup);
  105005. }
  105006. }
  105007. }
  105008. return animationGroups;
  105009. };
  105010. GLTFLoader.prototype._startAnimations = function () {
  105011. switch (this.animationStartMode) {
  105012. case BABYLON.GLTFLoaderAnimationStartMode.NONE: {
  105013. // do nothing
  105014. break;
  105015. }
  105016. case BABYLON.GLTFLoaderAnimationStartMode.FIRST: {
  105017. var babylonAnimationGroups = this._getAnimationGroups();
  105018. if (babylonAnimationGroups.length !== 0) {
  105019. babylonAnimationGroups[0].start(true);
  105020. }
  105021. break;
  105022. }
  105023. case BABYLON.GLTFLoaderAnimationStartMode.ALL: {
  105024. var babylonAnimationGroups = this._getAnimationGroups();
  105025. for (var _i = 0, babylonAnimationGroups_1 = babylonAnimationGroups; _i < babylonAnimationGroups_1.length; _i++) {
  105026. var babylonAnimationGroup = babylonAnimationGroups_1[_i];
  105027. babylonAnimationGroup.start(true);
  105028. }
  105029. break;
  105030. }
  105031. default: {
  105032. BABYLON.Tools.Error("Invalid animation start mode (" + this.animationStartMode + ")");
  105033. return;
  105034. }
  105035. }
  105036. };
  105037. /** @hidden */
  105038. GLTFLoader.prototype._loadNodeAsync = function (context, node) {
  105039. var promise = GLTF2.GLTFLoaderExtension._LoadNodeAsync(this, context, node);
  105040. if (promise) {
  105041. return promise;
  105042. }
  105043. if (node._babylonMesh) {
  105044. throw new Error(context + ": Invalid recursive node hierarchy");
  105045. }
  105046. var promises = new Array();
  105047. var babylonMesh = new BABYLON.Mesh(node.name || "node" + node._index, this._babylonScene, node._parent._babylonMesh);
  105048. node._babylonMesh = babylonMesh;
  105049. node._babylonAnimationTargets = node._babylonAnimationTargets || [];
  105050. node._babylonAnimationTargets.push(babylonMesh);
  105051. GLTFLoader._LoadTransform(node, babylonMesh);
  105052. if (node.mesh != undefined) {
  105053. var mesh = GLTFLoader._GetProperty(context + "/mesh", this._gltf.meshes, node.mesh);
  105054. promises.push(this._loadMeshAsync("#/meshes/" + mesh._index, node, mesh, babylonMesh));
  105055. }
  105056. if (node.camera != undefined) {
  105057. var camera = GLTFLoader._GetProperty(context + "/camera", this._gltf.cameras, node.camera);
  105058. this._loadCamera("#/cameras/" + camera._index, camera, babylonMesh);
  105059. }
  105060. if (node.children) {
  105061. for (var _i = 0, _a = node.children; _i < _a.length; _i++) {
  105062. var index = _a[_i];
  105063. var childNode = GLTFLoader._GetProperty(context + "/children/" + index, this._gltf.nodes, index);
  105064. promises.push(this._loadNodeAsync("#/nodes/" + index, childNode));
  105065. }
  105066. }
  105067. this.onMeshLoadedObservable.notifyObservers(babylonMesh);
  105068. return Promise.all(promises).then(function () { });
  105069. };
  105070. GLTFLoader.prototype._loadMeshAsync = function (context, node, mesh, babylonMesh) {
  105071. var _this = this;
  105072. var promises = new Array();
  105073. var primitives = mesh.primitives;
  105074. if (!primitives || primitives.length === 0) {
  105075. throw new Error(context + ": Primitives are missing");
  105076. }
  105077. GLTF2._ArrayItem.Assign(primitives);
  105078. if (primitives.length === 1) {
  105079. var primitive = primitives[0];
  105080. promises.push(this._loadPrimitiveAsync(context + "/primitives/" + primitive._index, node, mesh, primitive, babylonMesh));
  105081. }
  105082. else {
  105083. node._primitiveBabylonMeshes = [];
  105084. for (var _i = 0, primitives_1 = primitives; _i < primitives_1.length; _i++) {
  105085. var primitive = primitives_1[_i];
  105086. var primitiveBabylonMesh = new BABYLON.Mesh((mesh.name || babylonMesh.name) + "_" + primitive._index, this._babylonScene, babylonMesh);
  105087. node._primitiveBabylonMeshes.push(primitiveBabylonMesh);
  105088. promises.push(this._loadPrimitiveAsync(context + "/primitives/" + primitive._index, node, mesh, primitive, primitiveBabylonMesh));
  105089. this.onMeshLoadedObservable.notifyObservers(babylonMesh);
  105090. }
  105091. }
  105092. if (node.skin != undefined) {
  105093. var skin = GLTFLoader._GetProperty(context + "/skin", this._gltf.skins, node.skin);
  105094. promises.push(this._loadSkinAsync("#/skins/" + skin._index, node, mesh, skin));
  105095. }
  105096. return Promise.all(promises).then(function () {
  105097. _this._forEachPrimitive(node, function (babylonMesh) {
  105098. babylonMesh._refreshBoundingInfo(true);
  105099. });
  105100. });
  105101. };
  105102. GLTFLoader.prototype._loadPrimitiveAsync = function (context, node, mesh, primitive, babylonMesh) {
  105103. var _this = this;
  105104. var promises = new Array();
  105105. this._createMorphTargets(context, node, mesh, primitive, babylonMesh);
  105106. promises.push(this._loadVertexDataAsync(context, primitive, babylonMesh).then(function (babylonGeometry) {
  105107. return _this._loadMorphTargetsAsync(context, primitive, babylonMesh, babylonGeometry).then(function () {
  105108. babylonGeometry.applyToMesh(babylonMesh);
  105109. });
  105110. }));
  105111. var babylonDrawMode = GLTFLoader._GetDrawMode(context, primitive.mode);
  105112. if (primitive.material == undefined) {
  105113. babylonMesh.material = this._getDefaultMaterial(babylonDrawMode);
  105114. }
  105115. else {
  105116. var material = GLTFLoader._GetProperty(context + "/material}", this._gltf.materials, primitive.material);
  105117. promises.push(this._loadMaterialAsync("#/materials/" + material._index, material, babylonMesh, babylonDrawMode, function (babylonMaterial) {
  105118. babylonMesh.material = babylonMaterial;
  105119. }));
  105120. }
  105121. return Promise.all(promises).then(function () { });
  105122. };
  105123. GLTFLoader.prototype._loadVertexDataAsync = function (context, primitive, babylonMesh) {
  105124. var _this = this;
  105125. var promise = GLTF2.GLTFLoaderExtension._LoadVertexDataAsync(this, context, primitive, babylonMesh);
  105126. if (promise) {
  105127. return promise;
  105128. }
  105129. var attributes = primitive.attributes;
  105130. if (!attributes) {
  105131. throw new Error(context + ": Attributes are missing");
  105132. }
  105133. var promises = new Array();
  105134. var babylonGeometry = new BABYLON.Geometry(babylonMesh.name, this._babylonScene);
  105135. if (primitive.indices == undefined) {
  105136. babylonMesh.isUnIndexed = true;
  105137. }
  105138. else {
  105139. var accessor = GLTFLoader._GetProperty(context + "/indices", this._gltf.accessors, primitive.indices);
  105140. promises.push(this._loadIndicesAccessorAsync("#/accessors/" + accessor._index, accessor).then(function (data) {
  105141. babylonGeometry.setIndices(data);
  105142. }));
  105143. }
  105144. var loadAttribute = function (attribute, kind, callback) {
  105145. if (attributes[attribute] == undefined) {
  105146. return;
  105147. }
  105148. babylonMesh._delayInfo = babylonMesh._delayInfo || [];
  105149. if (babylonMesh._delayInfo.indexOf(kind) === -1) {
  105150. babylonMesh._delayInfo.push(kind);
  105151. }
  105152. var accessor = GLTFLoader._GetProperty(context + "/attributes/" + attribute, _this._gltf.accessors, attributes[attribute]);
  105153. promises.push(_this._loadVertexAccessorAsync("#/accessors/" + accessor._index, accessor, kind).then(function (babylonVertexBuffer) {
  105154. babylonGeometry.setVerticesBuffer(babylonVertexBuffer, accessor.count);
  105155. }));
  105156. if (callback) {
  105157. callback(accessor);
  105158. }
  105159. };
  105160. loadAttribute("POSITION", BABYLON.VertexBuffer.PositionKind);
  105161. loadAttribute("NORMAL", BABYLON.VertexBuffer.NormalKind);
  105162. loadAttribute("TANGENT", BABYLON.VertexBuffer.TangentKind);
  105163. loadAttribute("TEXCOORD_0", BABYLON.VertexBuffer.UVKind);
  105164. loadAttribute("TEXCOORD_1", BABYLON.VertexBuffer.UV2Kind);
  105165. loadAttribute("JOINTS_0", BABYLON.VertexBuffer.MatricesIndicesKind);
  105166. loadAttribute("WEIGHTS_0", BABYLON.VertexBuffer.MatricesWeightsKind);
  105167. loadAttribute("COLOR_0", BABYLON.VertexBuffer.ColorKind, function (accessor) {
  105168. if (accessor.type === "VEC4" /* VEC4 */) {
  105169. babylonMesh.hasVertexAlpha = true;
  105170. }
  105171. });
  105172. return Promise.all(promises).then(function () {
  105173. return babylonGeometry;
  105174. });
  105175. };
  105176. GLTFLoader.prototype._createMorphTargets = function (context, node, mesh, primitive, babylonMesh) {
  105177. if (!primitive.targets) {
  105178. return;
  105179. }
  105180. if (node._numMorphTargets == undefined) {
  105181. node._numMorphTargets = primitive.targets.length;
  105182. }
  105183. else if (primitive.targets.length !== node._numMorphTargets) {
  105184. throw new Error(context + ": Primitives do not have the same number of targets");
  105185. }
  105186. babylonMesh.morphTargetManager = new BABYLON.MorphTargetManager();
  105187. for (var index = 0; index < primitive.targets.length; index++) {
  105188. var weight = node.weights ? node.weights[index] : mesh.weights ? mesh.weights[index] : 0;
  105189. babylonMesh.morphTargetManager.addTarget(new BABYLON.MorphTarget("morphTarget" + index, weight));
  105190. // TODO: tell the target whether it has positions, normals, tangents
  105191. }
  105192. };
  105193. GLTFLoader.prototype._loadMorphTargetsAsync = function (context, primitive, babylonMesh, babylonGeometry) {
  105194. if (!primitive.targets) {
  105195. return Promise.resolve();
  105196. }
  105197. var promises = new Array();
  105198. var morphTargetManager = babylonMesh.morphTargetManager;
  105199. for (var index = 0; index < morphTargetManager.numTargets; index++) {
  105200. var babylonMorphTarget = morphTargetManager.getTarget(index);
  105201. promises.push(this._loadMorphTargetVertexDataAsync(context + "/targets/" + index, babylonGeometry, primitive.targets[index], babylonMorphTarget));
  105202. }
  105203. return Promise.all(promises).then(function () { });
  105204. };
  105205. GLTFLoader.prototype._loadMorphTargetVertexDataAsync = function (context, babylonGeometry, attributes, babylonMorphTarget) {
  105206. var _this = this;
  105207. var promises = new Array();
  105208. var loadAttribute = function (attribute, kind, setData) {
  105209. if (attributes[attribute] == undefined) {
  105210. return;
  105211. }
  105212. var babylonVertexBuffer = babylonGeometry.getVertexBuffer(kind);
  105213. if (!babylonVertexBuffer) {
  105214. return;
  105215. }
  105216. var accessor = GLTFLoader._GetProperty(context + "/" + attribute, _this._gltf.accessors, attributes[attribute]);
  105217. promises.push(_this._loadFloatAccessorAsync("#/accessors/" + accessor._index, accessor).then(function (data) {
  105218. setData(babylonVertexBuffer, data);
  105219. }));
  105220. };
  105221. loadAttribute("POSITION", BABYLON.VertexBuffer.PositionKind, function (babylonVertexBuffer, data) {
  105222. babylonVertexBuffer.forEach(data.length, function (value, index) {
  105223. data[index] += value;
  105224. });
  105225. babylonMorphTarget.setPositions(data);
  105226. });
  105227. loadAttribute("NORMAL", BABYLON.VertexBuffer.NormalKind, function (babylonVertexBuffer, data) {
  105228. babylonVertexBuffer.forEach(data.length, function (value, index) {
  105229. data[index] += value;
  105230. });
  105231. babylonMorphTarget.setNormals(data);
  105232. });
  105233. loadAttribute("TANGENT", BABYLON.VertexBuffer.TangentKind, function (babylonVertexBuffer, data) {
  105234. var dataIndex = 0;
  105235. babylonVertexBuffer.forEach(data.length, function (value, index) {
  105236. // Tangent data for morph targets is stored as xyz delta.
  105237. // The vertexData.tangent is stored as xyzw.
  105238. // So we need to skip every fourth vertexData.tangent.
  105239. if (((index + 1) % 4) !== 0) {
  105240. data[dataIndex++] += value;
  105241. }
  105242. });
  105243. babylonMorphTarget.setTangents(data);
  105244. });
  105245. return Promise.all(promises).then(function () { });
  105246. };
  105247. GLTFLoader._LoadTransform = function (node, babylonNode) {
  105248. var position = BABYLON.Vector3.Zero();
  105249. var rotation = BABYLON.Quaternion.Identity();
  105250. var scaling = BABYLON.Vector3.One();
  105251. if (node.matrix) {
  105252. var matrix = BABYLON.Matrix.FromArray(node.matrix);
  105253. matrix.decompose(scaling, rotation, position);
  105254. }
  105255. else {
  105256. if (node.translation)
  105257. position = BABYLON.Vector3.FromArray(node.translation);
  105258. if (node.rotation)
  105259. rotation = BABYLON.Quaternion.FromArray(node.rotation);
  105260. if (node.scale)
  105261. scaling = BABYLON.Vector3.FromArray(node.scale);
  105262. }
  105263. babylonNode.position = position;
  105264. babylonNode.rotationQuaternion = rotation;
  105265. babylonNode.scaling = scaling;
  105266. };
  105267. GLTFLoader.prototype._loadSkinAsync = function (context, node, mesh, skin) {
  105268. var _this = this;
  105269. var assignSkeleton = function (skeleton) {
  105270. _this._forEachPrimitive(node, function (babylonMesh) {
  105271. babylonMesh.skeleton = skeleton;
  105272. });
  105273. // Ignore the TRS of skinned nodes.
  105274. // See https://github.com/KhronosGroup/glTF/tree/master/specification/2.0#skins (second implementation note)
  105275. node._babylonMesh.parent = _this._rootBabylonMesh;
  105276. node._babylonMesh.position = BABYLON.Vector3.Zero();
  105277. node._babylonMesh.rotationQuaternion = BABYLON.Quaternion.Identity();
  105278. node._babylonMesh.scaling = BABYLON.Vector3.One();
  105279. };
  105280. if (skin._loaded) {
  105281. return skin._loaded.then(function () {
  105282. assignSkeleton(skin._babylonSkeleton);
  105283. });
  105284. }
  105285. var skeletonId = "skeleton" + skin._index;
  105286. var babylonSkeleton = new BABYLON.Skeleton(skin.name || skeletonId, skeletonId, this._babylonScene);
  105287. skin._babylonSkeleton = babylonSkeleton;
  105288. this._loadBones(context, skin);
  105289. assignSkeleton(babylonSkeleton);
  105290. return (skin._loaded = this._loadSkinInverseBindMatricesDataAsync(context, skin).then(function (inverseBindMatricesData) {
  105291. _this._updateBoneMatrices(babylonSkeleton, inverseBindMatricesData);
  105292. }));
  105293. };
  105294. GLTFLoader.prototype._loadBones = function (context, skin) {
  105295. var babylonBones = {};
  105296. for (var _i = 0, _a = skin.joints; _i < _a.length; _i++) {
  105297. var index = _a[_i];
  105298. var node = GLTFLoader._GetProperty(context + "/joints/" + index, this._gltf.nodes, index);
  105299. this._loadBone(node, skin, babylonBones);
  105300. }
  105301. };
  105302. GLTFLoader.prototype._loadBone = function (node, skin, babylonBones) {
  105303. var babylonBone = babylonBones[node._index];
  105304. if (babylonBone) {
  105305. return babylonBone;
  105306. }
  105307. var babylonParentBone = null;
  105308. if (node._parent._babylonMesh !== this._rootBabylonMesh) {
  105309. babylonParentBone = this._loadBone(node._parent, skin, babylonBones);
  105310. }
  105311. var boneIndex = skin.joints.indexOf(node._index);
  105312. babylonBone = new BABYLON.Bone(node.name || "joint" + node._index, skin._babylonSkeleton, babylonParentBone, this._getNodeMatrix(node), null, null, boneIndex);
  105313. babylonBones[node._index] = babylonBone;
  105314. node._babylonAnimationTargets = node._babylonAnimationTargets || [];
  105315. node._babylonAnimationTargets.push(babylonBone);
  105316. return babylonBone;
  105317. };
  105318. GLTFLoader.prototype._loadSkinInverseBindMatricesDataAsync = function (context, skin) {
  105319. if (skin.inverseBindMatrices == undefined) {
  105320. return Promise.resolve(null);
  105321. }
  105322. var accessor = GLTFLoader._GetProperty(context + "/inverseBindMatrices", this._gltf.accessors, skin.inverseBindMatrices);
  105323. return this._loadFloatAccessorAsync("#/accessors/" + accessor._index, accessor);
  105324. };
  105325. GLTFLoader.prototype._updateBoneMatrices = function (babylonSkeleton, inverseBindMatricesData) {
  105326. for (var _i = 0, _a = babylonSkeleton.bones; _i < _a.length; _i++) {
  105327. var babylonBone = _a[_i];
  105328. var baseMatrix = BABYLON.Matrix.Identity();
  105329. var boneIndex = babylonBone._index;
  105330. if (inverseBindMatricesData && boneIndex !== -1) {
  105331. BABYLON.Matrix.FromArrayToRef(inverseBindMatricesData, boneIndex * 16, baseMatrix);
  105332. baseMatrix.invertToRef(baseMatrix);
  105333. }
  105334. var babylonParentBone = babylonBone.getParent();
  105335. if (babylonParentBone) {
  105336. baseMatrix.multiplyToRef(babylonParentBone.getInvertedAbsoluteTransform(), baseMatrix);
  105337. }
  105338. babylonBone.updateMatrix(baseMatrix, false, false);
  105339. babylonBone._updateDifferenceMatrix(undefined, false);
  105340. }
  105341. };
  105342. GLTFLoader.prototype._getNodeMatrix = function (node) {
  105343. return node.matrix ?
  105344. BABYLON.Matrix.FromArray(node.matrix) :
  105345. 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());
  105346. };
  105347. GLTFLoader.prototype._loadCamera = function (context, camera, babylonMesh) {
  105348. var babylonCamera = new BABYLON.FreeCamera(camera.name || "camera" + camera._index, BABYLON.Vector3.Zero(), this._babylonScene, false);
  105349. babylonCamera.parent = babylonMesh;
  105350. babylonCamera.rotation = new BABYLON.Vector3(0, Math.PI, 0);
  105351. switch (camera.type) {
  105352. case "perspective" /* PERSPECTIVE */: {
  105353. var perspective = camera.perspective;
  105354. if (!perspective) {
  105355. throw new Error(context + ": Camera perspective properties are missing");
  105356. }
  105357. babylonCamera.fov = perspective.yfov;
  105358. babylonCamera.minZ = perspective.znear;
  105359. babylonCamera.maxZ = perspective.zfar || Number.MAX_VALUE;
  105360. break;
  105361. }
  105362. case "orthographic" /* ORTHOGRAPHIC */: {
  105363. if (!camera.orthographic) {
  105364. throw new Error(context + ": Camera orthographic properties are missing");
  105365. }
  105366. babylonCamera.mode = BABYLON.Camera.ORTHOGRAPHIC_CAMERA;
  105367. babylonCamera.orthoLeft = -camera.orthographic.xmag;
  105368. babylonCamera.orthoRight = camera.orthographic.xmag;
  105369. babylonCamera.orthoBottom = -camera.orthographic.ymag;
  105370. babylonCamera.orthoTop = camera.orthographic.ymag;
  105371. babylonCamera.minZ = camera.orthographic.znear;
  105372. babylonCamera.maxZ = camera.orthographic.zfar;
  105373. break;
  105374. }
  105375. default: {
  105376. throw new Error(context + ": Invalid camera type (" + camera.type + ")");
  105377. }
  105378. }
  105379. this.onCameraLoadedObservable.notifyObservers(babylonCamera);
  105380. };
  105381. GLTFLoader.prototype._loadAnimationsAsync = function () {
  105382. var animations = this._gltf.animations;
  105383. if (!animations) {
  105384. return Promise.resolve();
  105385. }
  105386. var promises = new Array();
  105387. for (var index = 0; index < animations.length; index++) {
  105388. var animation = animations[index];
  105389. promises.push(this._loadAnimationAsync("#/animations/" + index, animation));
  105390. }
  105391. return Promise.all(promises).then(function () { });
  105392. };
  105393. GLTFLoader.prototype._loadAnimationAsync = function (context, animation) {
  105394. var babylonAnimationGroup = new BABYLON.AnimationGroup(animation.name || "animation" + animation._index, this._babylonScene);
  105395. animation._babylonAnimationGroup = babylonAnimationGroup;
  105396. var promises = new Array();
  105397. GLTF2._ArrayItem.Assign(animation.channels);
  105398. GLTF2._ArrayItem.Assign(animation.samplers);
  105399. for (var _i = 0, _a = animation.channels; _i < _a.length; _i++) {
  105400. var channel = _a[_i];
  105401. promises.push(this._loadAnimationChannelAsync(context + "/channels/" + channel._index, context, animation, channel, babylonAnimationGroup));
  105402. }
  105403. return Promise.all(promises).then(function () {
  105404. babylonAnimationGroup.normalize();
  105405. });
  105406. };
  105407. GLTFLoader.prototype._loadAnimationChannelAsync = function (context, animationContext, animation, channel, babylonAnimationGroup) {
  105408. var _this = this;
  105409. var targetNode = GLTFLoader._GetProperty(context + "/target/node", this._gltf.nodes, channel.target.node);
  105410. // Ignore animations that have no animation targets.
  105411. if ((channel.target.path === "weights" /* WEIGHTS */ && !targetNode._numMorphTargets) ||
  105412. (channel.target.path !== "weights" /* WEIGHTS */ && !targetNode._babylonAnimationTargets)) {
  105413. return Promise.resolve();
  105414. }
  105415. // Ignore animations targeting TRS of skinned nodes.
  105416. // See https://github.com/KhronosGroup/glTF/tree/master/specification/2.0#skins (second implementation note)
  105417. if (targetNode.skin != undefined && channel.target.path !== "weights" /* WEIGHTS */) {
  105418. return Promise.resolve();
  105419. }
  105420. var sampler = GLTFLoader._GetProperty(context + "/sampler", animation.samplers, channel.sampler);
  105421. return this._loadAnimationSamplerAsync(animationContext + "/samplers/" + channel.sampler, sampler).then(function (data) {
  105422. var targetPath;
  105423. var animationType;
  105424. switch (channel.target.path) {
  105425. case "translation" /* TRANSLATION */: {
  105426. targetPath = "position";
  105427. animationType = BABYLON.Animation.ANIMATIONTYPE_VECTOR3;
  105428. break;
  105429. }
  105430. case "rotation" /* ROTATION */: {
  105431. targetPath = "rotationQuaternion";
  105432. animationType = BABYLON.Animation.ANIMATIONTYPE_QUATERNION;
  105433. break;
  105434. }
  105435. case "scale" /* SCALE */: {
  105436. targetPath = "scaling";
  105437. animationType = BABYLON.Animation.ANIMATIONTYPE_VECTOR3;
  105438. break;
  105439. }
  105440. case "weights" /* WEIGHTS */: {
  105441. targetPath = "influence";
  105442. animationType = BABYLON.Animation.ANIMATIONTYPE_FLOAT;
  105443. break;
  105444. }
  105445. default: {
  105446. throw new Error(context + ": Invalid target path (" + channel.target.path + ")");
  105447. }
  105448. }
  105449. var outputBufferOffset = 0;
  105450. var getNextOutputValue;
  105451. switch (targetPath) {
  105452. case "position": {
  105453. getNextOutputValue = function () {
  105454. var value = BABYLON.Vector3.FromArray(data.output, outputBufferOffset);
  105455. outputBufferOffset += 3;
  105456. return value;
  105457. };
  105458. break;
  105459. }
  105460. case "rotationQuaternion": {
  105461. getNextOutputValue = function () {
  105462. var value = BABYLON.Quaternion.FromArray(data.output, outputBufferOffset);
  105463. outputBufferOffset += 4;
  105464. return value;
  105465. };
  105466. break;
  105467. }
  105468. case "scaling": {
  105469. getNextOutputValue = function () {
  105470. var value = BABYLON.Vector3.FromArray(data.output, outputBufferOffset);
  105471. outputBufferOffset += 3;
  105472. return value;
  105473. };
  105474. break;
  105475. }
  105476. case "influence": {
  105477. getNextOutputValue = function () {
  105478. var value = new Array(targetNode._numMorphTargets);
  105479. for (var i = 0; i < targetNode._numMorphTargets; i++) {
  105480. value[i] = data.output[outputBufferOffset++];
  105481. }
  105482. return value;
  105483. };
  105484. break;
  105485. }
  105486. }
  105487. var getNextKey;
  105488. switch (data.interpolation) {
  105489. case "STEP" /* STEP */: {
  105490. getNextKey = function (frameIndex) { return ({
  105491. frame: data.input[frameIndex],
  105492. value: getNextOutputValue(),
  105493. interpolation: BABYLON.AnimationKeyInterpolation.STEP
  105494. }); };
  105495. break;
  105496. }
  105497. case "LINEAR" /* LINEAR */: {
  105498. getNextKey = function (frameIndex) { return ({
  105499. frame: data.input[frameIndex],
  105500. value: getNextOutputValue()
  105501. }); };
  105502. break;
  105503. }
  105504. case "CUBICSPLINE" /* CUBICSPLINE */: {
  105505. getNextKey = function (frameIndex) { return ({
  105506. frame: data.input[frameIndex],
  105507. inTangent: getNextOutputValue(),
  105508. value: getNextOutputValue(),
  105509. outTangent: getNextOutputValue()
  105510. }); };
  105511. break;
  105512. }
  105513. }
  105514. var keys = new Array(data.input.length);
  105515. for (var frameIndex = 0; frameIndex < data.input.length; frameIndex++) {
  105516. keys[frameIndex] = getNextKey(frameIndex);
  105517. }
  105518. if (targetPath === "influence") {
  105519. var _loop_1 = function (targetIndex) {
  105520. var animationName = babylonAnimationGroup.name + "_channel" + babylonAnimationGroup.targetedAnimations.length;
  105521. var babylonAnimation = new BABYLON.Animation(animationName, targetPath, 1, animationType);
  105522. babylonAnimation.setKeys(keys.map(function (key) { return ({
  105523. frame: key.frame,
  105524. inTangent: key.inTangent ? key.inTangent[targetIndex] : undefined,
  105525. value: key.value[targetIndex],
  105526. outTangent: key.outTangent ? key.outTangent[targetIndex] : undefined
  105527. }); }));
  105528. var morphTargets = new Array();
  105529. _this._forEachPrimitive(targetNode, function (babylonMesh) {
  105530. var morphTarget = babylonMesh.morphTargetManager.getTarget(targetIndex);
  105531. morphTarget.animations.push(babylonAnimation);
  105532. morphTargets.push(morphTarget);
  105533. });
  105534. babylonAnimationGroup.addTargetedAnimation(babylonAnimation, morphTargets);
  105535. };
  105536. for (var targetIndex = 0; targetIndex < targetNode._numMorphTargets; targetIndex++) {
  105537. _loop_1(targetIndex);
  105538. }
  105539. }
  105540. else {
  105541. var animationName = babylonAnimationGroup.name + "_channel" + babylonAnimationGroup.targetedAnimations.length;
  105542. var babylonAnimation = new BABYLON.Animation(animationName, targetPath, 1, animationType);
  105543. babylonAnimation.setKeys(keys);
  105544. if (targetNode._babylonAnimationTargets) {
  105545. for (var _i = 0, _a = targetNode._babylonAnimationTargets; _i < _a.length; _i++) {
  105546. var babylonAnimationTarget = _a[_i];
  105547. babylonAnimationTarget.animations.push(babylonAnimation);
  105548. }
  105549. babylonAnimationGroup.addTargetedAnimation(babylonAnimation, targetNode._babylonAnimationTargets);
  105550. }
  105551. }
  105552. });
  105553. };
  105554. GLTFLoader.prototype._loadAnimationSamplerAsync = function (context, sampler) {
  105555. if (sampler._data) {
  105556. return sampler._data;
  105557. }
  105558. var interpolation = sampler.interpolation || "LINEAR" /* LINEAR */;
  105559. switch (interpolation) {
  105560. case "STEP" /* STEP */:
  105561. case "LINEAR" /* LINEAR */:
  105562. case "CUBICSPLINE" /* CUBICSPLINE */: {
  105563. break;
  105564. }
  105565. default: {
  105566. throw new Error(context + ": Invalid interpolation (" + sampler.interpolation + ")");
  105567. }
  105568. }
  105569. var inputAccessor = GLTFLoader._GetProperty(context + "/input", this._gltf.accessors, sampler.input);
  105570. var outputAccessor = GLTFLoader._GetProperty(context + "/output", this._gltf.accessors, sampler.output);
  105571. sampler._data = Promise.all([
  105572. this._loadFloatAccessorAsync("#/accessors/" + inputAccessor._index, inputAccessor),
  105573. this._loadFloatAccessorAsync("#/accessors/" + outputAccessor._index, outputAccessor)
  105574. ]).then(function (_a) {
  105575. var inputData = _a[0], outputData = _a[1];
  105576. return {
  105577. input: inputData,
  105578. interpolation: interpolation,
  105579. output: outputData,
  105580. };
  105581. });
  105582. return sampler._data;
  105583. };
  105584. GLTFLoader.prototype._loadBufferAsync = function (context, buffer) {
  105585. if (buffer._data) {
  105586. return buffer._data;
  105587. }
  105588. if (!buffer.uri) {
  105589. throw new Error(context + ": Uri is missing");
  105590. }
  105591. buffer._data = this._loadUriAsync(context, buffer.uri);
  105592. return buffer._data;
  105593. };
  105594. /** @hidden */
  105595. GLTFLoader.prototype._loadBufferViewAsync = function (context, bufferView) {
  105596. if (bufferView._data) {
  105597. return bufferView._data;
  105598. }
  105599. var buffer = GLTFLoader._GetProperty(context + "/buffer", this._gltf.buffers, bufferView.buffer);
  105600. bufferView._data = this._loadBufferAsync("#/buffers/" + buffer._index, buffer).then(function (data) {
  105601. try {
  105602. return new Uint8Array(data.buffer, data.byteOffset + (bufferView.byteOffset || 0), bufferView.byteLength);
  105603. }
  105604. catch (e) {
  105605. throw new Error(context + ": " + e.message);
  105606. }
  105607. });
  105608. return bufferView._data;
  105609. };
  105610. GLTFLoader.prototype._loadIndicesAccessorAsync = function (context, accessor) {
  105611. if (accessor.type !== "SCALAR" /* SCALAR */) {
  105612. throw new Error(context + ": Invalid type " + accessor.type);
  105613. }
  105614. if (accessor.componentType !== 5121 /* UNSIGNED_BYTE */ &&
  105615. accessor.componentType !== 5123 /* UNSIGNED_SHORT */ &&
  105616. accessor.componentType !== 5125 /* UNSIGNED_INT */) {
  105617. throw new Error(context + ": Invalid component type " + accessor.componentType);
  105618. }
  105619. if (accessor._data) {
  105620. return accessor._data;
  105621. }
  105622. var bufferView = GLTFLoader._GetProperty(context + "/bufferView", this._gltf.bufferViews, accessor.bufferView);
  105623. accessor._data = this._loadBufferViewAsync("#/bufferViews/" + bufferView._index, bufferView).then(function (data) {
  105624. return GLTFLoader._GetTypedArray(context, accessor.componentType, data, accessor.byteOffset, accessor.count);
  105625. });
  105626. return accessor._data;
  105627. };
  105628. GLTFLoader.prototype._loadFloatAccessorAsync = function (context, accessor) {
  105629. // TODO: support normalized and stride
  105630. var _this = this;
  105631. if (accessor.componentType !== 5126 /* FLOAT */) {
  105632. throw new Error("Invalid component type " + accessor.componentType);
  105633. }
  105634. if (accessor._data) {
  105635. return accessor._data;
  105636. }
  105637. var numComponents = GLTFLoader._GetNumComponents(context, accessor.type);
  105638. var length = numComponents * accessor.count;
  105639. if (accessor.bufferView == undefined) {
  105640. accessor._data = Promise.resolve(new Float32Array(length));
  105641. }
  105642. else {
  105643. var bufferView = GLTFLoader._GetProperty(context + "/bufferView", this._gltf.bufferViews, accessor.bufferView);
  105644. accessor._data = this._loadBufferViewAsync("#/bufferViews/" + bufferView._index, bufferView).then(function (data) {
  105645. return GLTFLoader._GetTypedArray(context, accessor.componentType, data, accessor.byteOffset, length);
  105646. });
  105647. }
  105648. if (accessor.sparse) {
  105649. var sparse_1 = accessor.sparse;
  105650. accessor._data = accessor._data.then(function (data) {
  105651. var indicesBufferView = GLTFLoader._GetProperty(context + "/sparse/indices/bufferView", _this._gltf.bufferViews, sparse_1.indices.bufferView);
  105652. var valuesBufferView = GLTFLoader._GetProperty(context + "/sparse/values/bufferView", _this._gltf.bufferViews, sparse_1.values.bufferView);
  105653. return Promise.all([
  105654. _this._loadBufferViewAsync("#/bufferViews/" + indicesBufferView._index, indicesBufferView),
  105655. _this._loadBufferViewAsync("#/bufferViews/" + valuesBufferView._index, valuesBufferView)
  105656. ]).then(function (_a) {
  105657. var indicesData = _a[0], valuesData = _a[1];
  105658. var indices = GLTFLoader._GetTypedArray(context + "/sparse/indices", sparse_1.indices.componentType, indicesData, sparse_1.indices.byteOffset, sparse_1.count);
  105659. var values = GLTFLoader._GetTypedArray(context + "/sparse/values", accessor.componentType, valuesData, sparse_1.values.byteOffset, numComponents * sparse_1.count);
  105660. var valuesIndex = 0;
  105661. for (var indicesIndex = 0; indicesIndex < indices.length; indicesIndex++) {
  105662. var dataIndex = indices[indicesIndex] * numComponents;
  105663. for (var componentIndex = 0; componentIndex < numComponents; componentIndex++) {
  105664. data[dataIndex++] = values[valuesIndex++];
  105665. }
  105666. }
  105667. return data;
  105668. });
  105669. });
  105670. }
  105671. return accessor._data;
  105672. };
  105673. /** @hidden */
  105674. GLTFLoader.prototype._loadVertexBufferViewAsync = function (context, bufferView, kind) {
  105675. var _this = this;
  105676. if (bufferView._babylonBuffer) {
  105677. return bufferView._babylonBuffer;
  105678. }
  105679. bufferView._babylonBuffer = this._loadBufferViewAsync(context, bufferView).then(function (data) {
  105680. return new BABYLON.Buffer(_this._babylonScene.getEngine(), data, false);
  105681. });
  105682. return bufferView._babylonBuffer;
  105683. };
  105684. GLTFLoader.prototype._loadVertexAccessorAsync = function (context, accessor, kind) {
  105685. var _this = this;
  105686. if (accessor._babylonVertexBuffer) {
  105687. return accessor._babylonVertexBuffer;
  105688. }
  105689. if (accessor.sparse) {
  105690. accessor._babylonVertexBuffer = this._loadFloatAccessorAsync(context, accessor).then(function (data) {
  105691. return new BABYLON.VertexBuffer(_this._babylonScene.getEngine(), data, kind, false);
  105692. });
  105693. }
  105694. else {
  105695. var bufferView_1 = GLTFLoader._GetProperty(context + "/bufferView", this._gltf.bufferViews, accessor.bufferView);
  105696. accessor._babylonVertexBuffer = this._loadVertexBufferViewAsync("#/bufferViews/" + bufferView_1._index, bufferView_1, kind).then(function (buffer) {
  105697. var size = GLTFLoader._GetNumComponents(context, accessor.type);
  105698. return new BABYLON.VertexBuffer(_this._babylonScene.getEngine(), buffer, kind, false, false, bufferView_1.byteStride, false, accessor.byteOffset, size, accessor.componentType, accessor.normalized, true);
  105699. });
  105700. }
  105701. return accessor._babylonVertexBuffer;
  105702. };
  105703. GLTFLoader.prototype._getDefaultMaterial = function (drawMode) {
  105704. var babylonMaterial = this._defaultBabylonMaterials[drawMode];
  105705. if (!babylonMaterial) {
  105706. babylonMaterial = this._createMaterial("__gltf_default", drawMode);
  105707. babylonMaterial.transparencyMode = BABYLON.PBRMaterial.PBRMATERIAL_OPAQUE;
  105708. babylonMaterial.metallic = 1;
  105709. babylonMaterial.roughness = 1;
  105710. this.onMaterialLoadedObservable.notifyObservers(babylonMaterial);
  105711. }
  105712. return babylonMaterial;
  105713. };
  105714. GLTFLoader.prototype._loadMaterialMetallicRoughnessPropertiesAsync = function (context, material, babylonMaterial) {
  105715. var promises = new Array();
  105716. // Ensure metallic workflow
  105717. babylonMaterial.metallic = 1;
  105718. babylonMaterial.roughness = 1;
  105719. var properties = material.pbrMetallicRoughness;
  105720. if (properties) {
  105721. if (properties.baseColorFactor) {
  105722. babylonMaterial.albedoColor = BABYLON.Color3.FromArray(properties.baseColorFactor);
  105723. babylonMaterial.alpha = properties.baseColorFactor[3];
  105724. }
  105725. else {
  105726. babylonMaterial.albedoColor = BABYLON.Color3.White();
  105727. }
  105728. babylonMaterial.metallic = properties.metallicFactor == undefined ? 1 : properties.metallicFactor;
  105729. babylonMaterial.roughness = properties.roughnessFactor == undefined ? 1 : properties.roughnessFactor;
  105730. if (properties.baseColorTexture) {
  105731. promises.push(this._loadTextureAsync(context + "/baseColorTexture", properties.baseColorTexture, function (texture) {
  105732. babylonMaterial.albedoTexture = texture;
  105733. }));
  105734. }
  105735. if (properties.metallicRoughnessTexture) {
  105736. promises.push(this._loadTextureAsync(context + "/metallicRoughnessTexture", properties.metallicRoughnessTexture, function (texture) {
  105737. babylonMaterial.metallicTexture = texture;
  105738. }));
  105739. babylonMaterial.useMetallnessFromMetallicTextureBlue = true;
  105740. babylonMaterial.useRoughnessFromMetallicTextureGreen = true;
  105741. babylonMaterial.useRoughnessFromMetallicTextureAlpha = false;
  105742. }
  105743. }
  105744. this._loadMaterialAlphaProperties(context, material, babylonMaterial);
  105745. return Promise.all(promises).then(function () { });
  105746. };
  105747. /** @hidden */
  105748. GLTFLoader.prototype._loadMaterialAsync = function (context, material, babylonMesh, babylonDrawMode, assign) {
  105749. var promise = GLTF2.GLTFLoaderExtension._LoadMaterialAsync(this, context, material, babylonMesh, babylonDrawMode, assign);
  105750. if (promise) {
  105751. return promise;
  105752. }
  105753. material._babylonData = material._babylonData || {};
  105754. var babylonData = material._babylonData[babylonDrawMode];
  105755. if (!babylonData) {
  105756. var promises = new Array();
  105757. var name_3 = material.name || "materialSG_" + material._index;
  105758. var babylonMaterial = this._createMaterial(name_3, babylonDrawMode);
  105759. promises.push(this._loadMaterialBasePropertiesAsync(context, material, babylonMaterial));
  105760. promises.push(this._loadMaterialMetallicRoughnessPropertiesAsync(context, material, babylonMaterial));
  105761. this.onMaterialLoadedObservable.notifyObservers(babylonMaterial);
  105762. babylonData = {
  105763. material: babylonMaterial,
  105764. meshes: [],
  105765. loaded: Promise.all(promises).then(function () { })
  105766. };
  105767. material._babylonData[babylonDrawMode] = babylonData;
  105768. }
  105769. babylonData.meshes.push(babylonMesh);
  105770. assign(babylonData.material);
  105771. return babylonData.loaded;
  105772. };
  105773. /** @hidden */
  105774. GLTFLoader.prototype._createMaterial = function (name, drawMode) {
  105775. var babylonMaterial = new BABYLON.PBRMaterial(name, this._babylonScene);
  105776. babylonMaterial.sideOrientation = this._babylonScene.useRightHandedSystem ? BABYLON.Material.CounterClockWiseSideOrientation : BABYLON.Material.ClockWiseSideOrientation;
  105777. babylonMaterial.fillMode = drawMode;
  105778. babylonMaterial.enableSpecularAntiAliasing = true;
  105779. return babylonMaterial;
  105780. };
  105781. /** @hidden */
  105782. GLTFLoader.prototype._loadMaterialBasePropertiesAsync = function (context, material, babylonMaterial) {
  105783. var promises = new Array();
  105784. babylonMaterial.emissiveColor = material.emissiveFactor ? BABYLON.Color3.FromArray(material.emissiveFactor) : new BABYLON.Color3(0, 0, 0);
  105785. if (material.doubleSided) {
  105786. babylonMaterial.backFaceCulling = false;
  105787. babylonMaterial.twoSidedLighting = true;
  105788. }
  105789. if (material.normalTexture) {
  105790. promises.push(this._loadTextureAsync(context + "/normalTexture", material.normalTexture, function (texture) {
  105791. babylonMaterial.bumpTexture = texture;
  105792. }));
  105793. babylonMaterial.invertNormalMapX = !this._babylonScene.useRightHandedSystem;
  105794. babylonMaterial.invertNormalMapY = this._babylonScene.useRightHandedSystem;
  105795. if (material.normalTexture.scale != undefined) {
  105796. babylonMaterial.bumpTexture.level = material.normalTexture.scale;
  105797. }
  105798. }
  105799. if (material.occlusionTexture) {
  105800. promises.push(this._loadTextureAsync(context + "/occlusionTexture", material.occlusionTexture, function (texture) {
  105801. babylonMaterial.ambientTexture = texture;
  105802. }));
  105803. babylonMaterial.useAmbientInGrayScale = true;
  105804. if (material.occlusionTexture.strength != undefined) {
  105805. babylonMaterial.ambientTextureStrength = material.occlusionTexture.strength;
  105806. }
  105807. }
  105808. if (material.emissiveTexture) {
  105809. promises.push(this._loadTextureAsync(context + "/emissiveTexture", material.emissiveTexture, function (texture) {
  105810. babylonMaterial.emissiveTexture = texture;
  105811. }));
  105812. }
  105813. return Promise.all(promises).then(function () { });
  105814. };
  105815. /** @hidden */
  105816. GLTFLoader.prototype._loadMaterialAlphaProperties = function (context, material, babylonMaterial) {
  105817. var alphaMode = material.alphaMode || "OPAQUE" /* OPAQUE */;
  105818. switch (alphaMode) {
  105819. case "OPAQUE" /* OPAQUE */: {
  105820. babylonMaterial.transparencyMode = BABYLON.PBRMaterial.PBRMATERIAL_OPAQUE;
  105821. break;
  105822. }
  105823. case "MASK" /* MASK */: {
  105824. babylonMaterial.transparencyMode = BABYLON.PBRMaterial.PBRMATERIAL_ALPHATEST;
  105825. babylonMaterial.alphaCutOff = (material.alphaCutoff == undefined ? 0.5 : material.alphaCutoff);
  105826. if (babylonMaterial.albedoTexture) {
  105827. babylonMaterial.albedoTexture.hasAlpha = true;
  105828. }
  105829. break;
  105830. }
  105831. case "BLEND" /* BLEND */: {
  105832. babylonMaterial.transparencyMode = BABYLON.PBRMaterial.PBRMATERIAL_ALPHABLEND;
  105833. if (babylonMaterial.albedoTexture) {
  105834. babylonMaterial.albedoTexture.hasAlpha = true;
  105835. babylonMaterial.useAlphaFromAlbedoTexture = true;
  105836. }
  105837. break;
  105838. }
  105839. default: {
  105840. throw new Error(context + ": Invalid alpha mode (" + material.alphaMode + ")");
  105841. }
  105842. }
  105843. };
  105844. /** @hidden */
  105845. GLTFLoader.prototype._loadTextureAsync = function (context, textureInfo, assign) {
  105846. var _this = this;
  105847. var texture = GLTFLoader._GetProperty(context + "/index", this._gltf.textures, textureInfo.index);
  105848. context = "#/textures/" + textureInfo.index;
  105849. var promises = new Array();
  105850. var sampler = (texture.sampler == undefined ? this._defaultSampler : GLTFLoader._GetProperty(context + "/sampler", this._gltf.samplers, texture.sampler));
  105851. var samplerData = this._loadSampler("#/samplers/" + sampler._index, sampler);
  105852. var deferred = new BABYLON.Deferred();
  105853. var babylonTexture = new BABYLON.Texture(null, this._babylonScene, samplerData.noMipMaps, false, samplerData.samplingMode, function () {
  105854. if (!_this._disposed) {
  105855. deferred.resolve();
  105856. }
  105857. }, function (message, exception) {
  105858. if (!_this._disposed) {
  105859. deferred.reject(new Error(context + ": " + ((exception && exception.message) ? exception.message : message || "Failed to load texture")));
  105860. }
  105861. });
  105862. promises.push(deferred.promise);
  105863. babylonTexture.name = texture.name || "texture" + texture._index;
  105864. babylonTexture.wrapU = samplerData.wrapU;
  105865. babylonTexture.wrapV = samplerData.wrapV;
  105866. babylonTexture.coordinatesIndex = textureInfo.texCoord || 0;
  105867. var image = GLTFLoader._GetProperty(context + "/source", this._gltf.images, texture.source);
  105868. promises.push(this._loadImageAsync("#/images/" + image._index, image).then(function (objectURL) {
  105869. babylonTexture.updateURL(objectURL);
  105870. }));
  105871. assign(babylonTexture);
  105872. this.onTextureLoadedObservable.notifyObservers(babylonTexture);
  105873. return Promise.all(promises).then(function () { });
  105874. };
  105875. GLTFLoader.prototype._loadSampler = function (context, sampler) {
  105876. if (!sampler._data) {
  105877. sampler._data = {
  105878. noMipMaps: (sampler.minFilter === 9728 /* NEAREST */ || sampler.minFilter === 9729 /* LINEAR */),
  105879. samplingMode: GLTFLoader._GetTextureSamplingMode(context, sampler.magFilter, sampler.minFilter),
  105880. wrapU: GLTFLoader._GetTextureWrapMode(context, sampler.wrapS),
  105881. wrapV: GLTFLoader._GetTextureWrapMode(context, sampler.wrapT)
  105882. };
  105883. }
  105884. ;
  105885. return sampler._data;
  105886. };
  105887. GLTFLoader.prototype._loadImageAsync = function (context, image) {
  105888. if (image._objectURL) {
  105889. return image._objectURL;
  105890. }
  105891. var promise;
  105892. if (image.uri) {
  105893. promise = this._loadUriAsync(context, image.uri);
  105894. }
  105895. else {
  105896. var bufferView = GLTFLoader._GetProperty(context + "/bufferView", this._gltf.bufferViews, image.bufferView);
  105897. promise = this._loadBufferViewAsync("#/bufferViews/" + bufferView._index, bufferView);
  105898. }
  105899. image._objectURL = promise.then(function (data) {
  105900. return URL.createObjectURL(new Blob([data], { type: image.mimeType }));
  105901. });
  105902. return image._objectURL;
  105903. };
  105904. /** @hidden */
  105905. GLTFLoader.prototype._loadUriAsync = function (context, uri) {
  105906. var _this = this;
  105907. var promise = GLTF2.GLTFLoaderExtension._LoadUriAsync(this, context, uri);
  105908. if (promise) {
  105909. return promise;
  105910. }
  105911. if (!GLTFLoader._ValidateUri(uri)) {
  105912. throw new Error(context + ": Uri '" + uri + "' is invalid");
  105913. }
  105914. if (BABYLON.Tools.IsBase64(uri)) {
  105915. return Promise.resolve(new Uint8Array(BABYLON.Tools.DecodeBase64(uri)));
  105916. }
  105917. return this.preprocessUrlAsync(this._rootUrl + uri).then(function (url) {
  105918. return new Promise(function (resolve, reject) {
  105919. if (!_this._disposed) {
  105920. var request_1 = BABYLON.Tools.LoadFile(url, function (data) {
  105921. if (!_this._disposed) {
  105922. resolve(new Uint8Array(data));
  105923. }
  105924. }, function (event) {
  105925. if (!_this._disposed) {
  105926. try {
  105927. if (request_1 && _this._state === BABYLON.GLTFLoaderState.LOADING) {
  105928. request_1._lengthComputable = event.lengthComputable;
  105929. request_1._loaded = event.loaded;
  105930. request_1._total = event.total;
  105931. _this._onProgress();
  105932. }
  105933. }
  105934. catch (e) {
  105935. reject(e);
  105936. }
  105937. }
  105938. }, _this._babylonScene.database, true, function (request, exception) {
  105939. if (!_this._disposed) {
  105940. reject(new BABYLON.LoadFileError(context + ": Failed to load '" + uri + "'" + (request ? ": " + request.status + " " + request.statusText : ""), request));
  105941. }
  105942. });
  105943. _this._requests.push(request_1);
  105944. }
  105945. });
  105946. });
  105947. };
  105948. GLTFLoader.prototype._onProgress = function () {
  105949. if (!this._progressCallback) {
  105950. return;
  105951. }
  105952. var lengthComputable = true;
  105953. var loaded = 0;
  105954. var total = 0;
  105955. for (var _i = 0, _a = this._requests; _i < _a.length; _i++) {
  105956. var request = _a[_i];
  105957. if (request._lengthComputable === undefined || request._loaded === undefined || request._total === undefined) {
  105958. return;
  105959. }
  105960. lengthComputable = lengthComputable && request._lengthComputable;
  105961. loaded += request._loaded;
  105962. total += request._total;
  105963. }
  105964. this._progressCallback(new BABYLON.SceneLoaderProgressEvent(lengthComputable, loaded, lengthComputable ? total : 0));
  105965. };
  105966. /** @hidden */
  105967. GLTFLoader._GetProperty = function (context, array, index) {
  105968. if (!array || index == undefined || !array[index]) {
  105969. throw new Error(context + ": Failed to find index (" + index + ")");
  105970. }
  105971. return array[index];
  105972. };
  105973. GLTFLoader._GetTextureWrapMode = function (context, mode) {
  105974. // Set defaults if undefined
  105975. mode = mode == undefined ? 10497 /* REPEAT */ : mode;
  105976. switch (mode) {
  105977. case 33071 /* CLAMP_TO_EDGE */: return BABYLON.Texture.CLAMP_ADDRESSMODE;
  105978. case 33648 /* MIRRORED_REPEAT */: return BABYLON.Texture.MIRROR_ADDRESSMODE;
  105979. case 10497 /* REPEAT */: return BABYLON.Texture.WRAP_ADDRESSMODE;
  105980. default:
  105981. BABYLON.Tools.Warn(context + ": Invalid texture wrap mode (" + mode + ")");
  105982. return BABYLON.Texture.WRAP_ADDRESSMODE;
  105983. }
  105984. };
  105985. GLTFLoader._GetTextureSamplingMode = function (context, magFilter, minFilter) {
  105986. // Set defaults if undefined
  105987. magFilter = magFilter == undefined ? 9729 /* LINEAR */ : magFilter;
  105988. minFilter = minFilter == undefined ? 9987 /* LINEAR_MIPMAP_LINEAR */ : minFilter;
  105989. if (magFilter === 9729 /* LINEAR */) {
  105990. switch (minFilter) {
  105991. case 9728 /* NEAREST */: return BABYLON.Texture.LINEAR_NEAREST;
  105992. case 9729 /* LINEAR */: return BABYLON.Texture.LINEAR_LINEAR;
  105993. case 9984 /* NEAREST_MIPMAP_NEAREST */: return BABYLON.Texture.LINEAR_NEAREST_MIPNEAREST;
  105994. case 9985 /* LINEAR_MIPMAP_NEAREST */: return BABYLON.Texture.LINEAR_LINEAR_MIPNEAREST;
  105995. case 9986 /* NEAREST_MIPMAP_LINEAR */: return BABYLON.Texture.LINEAR_NEAREST_MIPLINEAR;
  105996. case 9987 /* LINEAR_MIPMAP_LINEAR */: return BABYLON.Texture.LINEAR_LINEAR_MIPLINEAR;
  105997. default:
  105998. BABYLON.Tools.Warn(context + ": Invalid texture minification filter (" + minFilter + ")");
  105999. return BABYLON.Texture.LINEAR_LINEAR_MIPLINEAR;
  106000. }
  106001. }
  106002. else {
  106003. if (magFilter !== 9728 /* NEAREST */) {
  106004. BABYLON.Tools.Warn(context + ": Invalid texture magnification filter (" + magFilter + ")");
  106005. }
  106006. switch (minFilter) {
  106007. case 9728 /* NEAREST */: return BABYLON.Texture.NEAREST_NEAREST;
  106008. case 9729 /* LINEAR */: return BABYLON.Texture.NEAREST_LINEAR;
  106009. case 9984 /* NEAREST_MIPMAP_NEAREST */: return BABYLON.Texture.NEAREST_NEAREST_MIPNEAREST;
  106010. case 9985 /* LINEAR_MIPMAP_NEAREST */: return BABYLON.Texture.NEAREST_LINEAR_MIPNEAREST;
  106011. case 9986 /* NEAREST_MIPMAP_LINEAR */: return BABYLON.Texture.NEAREST_NEAREST_MIPLINEAR;
  106012. case 9987 /* LINEAR_MIPMAP_LINEAR */: return BABYLON.Texture.NEAREST_LINEAR_MIPLINEAR;
  106013. default:
  106014. BABYLON.Tools.Warn(context + ": Invalid texture minification filter (" + minFilter + ")");
  106015. return BABYLON.Texture.NEAREST_NEAREST_MIPNEAREST;
  106016. }
  106017. }
  106018. };
  106019. GLTFLoader._GetTypedArray = function (context, componentType, bufferView, byteOffset, length) {
  106020. var buffer = bufferView.buffer;
  106021. byteOffset = bufferView.byteOffset + (byteOffset || 0);
  106022. try {
  106023. switch (componentType) {
  106024. case 5120 /* BYTE */: return new Int8Array(buffer, byteOffset, length);
  106025. case 5121 /* UNSIGNED_BYTE */: return new Uint8Array(buffer, byteOffset, length);
  106026. case 5122 /* SHORT */: return new Int16Array(buffer, byteOffset, length);
  106027. case 5123 /* UNSIGNED_SHORT */: return new Uint16Array(buffer, byteOffset, length);
  106028. case 5125 /* UNSIGNED_INT */: return new Uint32Array(buffer, byteOffset, length);
  106029. case 5126 /* FLOAT */: return new Float32Array(buffer, byteOffset, length);
  106030. default: throw new Error("Invalid component type " + componentType);
  106031. }
  106032. }
  106033. catch (e) {
  106034. throw new Error(context + ": " + e);
  106035. }
  106036. };
  106037. GLTFLoader._GetNumComponents = function (context, type) {
  106038. switch (type) {
  106039. case "SCALAR": return 1;
  106040. case "VEC2": return 2;
  106041. case "VEC3": return 3;
  106042. case "VEC4": return 4;
  106043. case "MAT2": return 4;
  106044. case "MAT3": return 9;
  106045. case "MAT4": return 16;
  106046. }
  106047. throw new Error(context + ": Invalid type (" + type + ")");
  106048. };
  106049. GLTFLoader._ValidateUri = function (uri) {
  106050. return (BABYLON.Tools.IsBase64(uri) || uri.indexOf("..") === -1);
  106051. };
  106052. GLTFLoader._GetDrawMode = function (context, mode) {
  106053. if (mode == undefined) {
  106054. mode = 4 /* TRIANGLES */;
  106055. }
  106056. switch (mode) {
  106057. case 0 /* POINTS */: return BABYLON.Material.PointListDrawMode;
  106058. case 1 /* LINES */: return BABYLON.Material.LineListDrawMode;
  106059. case 2 /* LINE_LOOP */: return BABYLON.Material.LineLoopDrawMode;
  106060. case 3 /* LINE_STRIP */: return BABYLON.Material.LineStripDrawMode;
  106061. case 4 /* TRIANGLES */: return BABYLON.Material.TriangleFillMode;
  106062. case 5 /* TRIANGLE_STRIP */: return BABYLON.Material.TriangleStripDrawMode;
  106063. case 6 /* TRIANGLE_FAN */: return BABYLON.Material.TriangleFanDrawMode;
  106064. }
  106065. throw new Error(context + ": Invalid mesh primitive mode (" + mode + ")");
  106066. };
  106067. GLTFLoader.prototype._compileMaterialsAsync = function () {
  106068. var promises = new Array();
  106069. if (this._gltf.materials) {
  106070. for (var _i = 0, _a = this._gltf.materials; _i < _a.length; _i++) {
  106071. var material = _a[_i];
  106072. if (material._babylonData) {
  106073. for (var babylonDrawMode in material._babylonData) {
  106074. var babylonData = material._babylonData[babylonDrawMode];
  106075. for (var _b = 0, _c = babylonData.meshes; _b < _c.length; _b++) {
  106076. var babylonMesh = _c[_b];
  106077. // Ensure nonUniformScaling is set if necessary.
  106078. babylonMesh.computeWorldMatrix(true);
  106079. var babylonMaterial = babylonData.material;
  106080. promises.push(babylonMaterial.forceCompilationAsync(babylonMesh));
  106081. if (this.useClipPlane) {
  106082. promises.push(babylonMaterial.forceCompilationAsync(babylonMesh, { clipPlane: true }));
  106083. }
  106084. }
  106085. }
  106086. }
  106087. }
  106088. }
  106089. return Promise.all(promises).then(function () { });
  106090. };
  106091. GLTFLoader.prototype._compileShadowGeneratorsAsync = function () {
  106092. var promises = new Array();
  106093. var lights = this._babylonScene.lights;
  106094. for (var _i = 0, lights_1 = lights; _i < lights_1.length; _i++) {
  106095. var light = lights_1[_i];
  106096. var generator = light.getShadowGenerator();
  106097. if (generator) {
  106098. promises.push(generator.forceCompilationAsync());
  106099. }
  106100. }
  106101. return Promise.all(promises).then(function () { });
  106102. };
  106103. GLTFLoader.prototype._clear = function () {
  106104. for (var _i = 0, _a = this._requests; _i < _a.length; _i++) {
  106105. var request = _a[_i];
  106106. request.abort();
  106107. }
  106108. this._requests.length = 0;
  106109. if (this._gltf && this._gltf.images) {
  106110. for (var _b = 0, _c = this._gltf.images; _b < _c.length; _b++) {
  106111. var image = _c[_b];
  106112. if (image._objectURL) {
  106113. image._objectURL.then(function (value) {
  106114. URL.revokeObjectURL(value);
  106115. });
  106116. image._objectURL = undefined;
  106117. }
  106118. }
  106119. }
  106120. delete this._gltf;
  106121. delete this._babylonScene;
  106122. this._completePromises.length = 0;
  106123. for (var name_4 in this._extensions) {
  106124. this._extensions[name_4].dispose();
  106125. }
  106126. this._extensions = {};
  106127. delete this._rootBabylonMesh;
  106128. delete this._progressCallback;
  106129. this.onMeshLoadedObservable.clear();
  106130. this.onTextureLoadedObservable.clear();
  106131. this.onMaterialLoadedObservable.clear();
  106132. this.onCameraLoadedObservable.clear();
  106133. };
  106134. /** @hidden */
  106135. GLTFLoader.prototype._applyExtensions = function (actionAsync) {
  106136. for (var _i = 0, _a = GLTFLoader._ExtensionNames; _i < _a.length; _i++) {
  106137. var name_5 = _a[_i];
  106138. var extension = this._extensions[name_5];
  106139. if (extension.enabled) {
  106140. var promise = actionAsync(extension);
  106141. if (promise) {
  106142. return promise;
  106143. }
  106144. }
  106145. }
  106146. return null;
  106147. };
  106148. GLTFLoader._ExtensionNames = new Array();
  106149. GLTFLoader._ExtensionFactories = {};
  106150. return GLTFLoader;
  106151. }());
  106152. GLTF2.GLTFLoader = GLTFLoader;
  106153. BABYLON.GLTFFileLoader.CreateGLTFLoaderV2 = function () { return new GLTFLoader(); };
  106154. })(GLTF2 = BABYLON.GLTF2 || (BABYLON.GLTF2 = {}));
  106155. })(BABYLON || (BABYLON = {}));
  106156. //# sourceMappingURL=babylon.glTFLoader.js.map
  106157. var BABYLON;
  106158. (function (BABYLON) {
  106159. var GLTF2;
  106160. (function (GLTF2) {
  106161. /**
  106162. * Abstract class that can be implemented to extend existing glTF loader behavior.
  106163. */
  106164. var GLTFLoaderExtension = /** @class */ (function () {
  106165. function GLTFLoaderExtension(loader) {
  106166. this.enabled = true;
  106167. this._loader = loader;
  106168. }
  106169. GLTFLoaderExtension.prototype.dispose = function () {
  106170. delete this._loader;
  106171. };
  106172. // #region Overridable Methods
  106173. /** Override this method to modify the default behavior for loading scenes. */
  106174. GLTFLoaderExtension.prototype._loadSceneAsync = function (context, node) { return null; };
  106175. /** Override this method to modify the default behavior for loading nodes. */
  106176. GLTFLoaderExtension.prototype._loadNodeAsync = function (context, node) { return null; };
  106177. /** Override this method to modify the default behavior for loading mesh primitive vertex data. */
  106178. GLTFLoaderExtension.prototype._loadVertexDataAsync = function (context, primitive, babylonMesh) { return null; };
  106179. /** Override this method to modify the default behavior for loading materials. */
  106180. GLTFLoaderExtension.prototype._loadMaterialAsync = function (context, material, babylonMesh, babylonDrawMode, assign) { return null; };
  106181. /** Override this method to modify the default behavior for loading uris. */
  106182. GLTFLoaderExtension.prototype._loadUriAsync = function (context, uri) { return null; };
  106183. // #endregion
  106184. /** Helper method called by a loader extension to load an glTF extension. */
  106185. GLTFLoaderExtension.prototype._loadExtensionAsync = function (context, property, actionAsync) {
  106186. if (!property.extensions) {
  106187. return null;
  106188. }
  106189. var extensions = property.extensions;
  106190. var extension = extensions[this.name];
  106191. if (!extension) {
  106192. return null;
  106193. }
  106194. // Clear out the extension before executing the action to avoid recursing into the same property.
  106195. delete extensions[this.name];
  106196. try {
  106197. return actionAsync(context + "/extensions/" + this.name, extension);
  106198. }
  106199. finally {
  106200. // Restore the extension after executing the action.
  106201. extensions[this.name] = extension;
  106202. }
  106203. };
  106204. /** Helper method called by the loader to allow extensions to override loading scenes. */
  106205. GLTFLoaderExtension._LoadSceneAsync = function (loader, context, scene) {
  106206. return loader._applyExtensions(function (extension) { return extension._loadSceneAsync(context, scene); });
  106207. };
  106208. /** Helper method called by the loader to allow extensions to override loading nodes. */
  106209. GLTFLoaderExtension._LoadNodeAsync = function (loader, context, node) {
  106210. return loader._applyExtensions(function (extension) { return extension._loadNodeAsync(context, node); });
  106211. };
  106212. /** Helper method called by the loader to allow extensions to override loading mesh primitive vertex data. */
  106213. GLTFLoaderExtension._LoadVertexDataAsync = function (loader, context, primitive, babylonMesh) {
  106214. return loader._applyExtensions(function (extension) { return extension._loadVertexDataAsync(context, primitive, babylonMesh); });
  106215. };
  106216. /** Helper method called by the loader to allow extensions to override loading materials. */
  106217. GLTFLoaderExtension._LoadMaterialAsync = function (loader, context, material, babylonMesh, babylonDrawMode, assign) {
  106218. return loader._applyExtensions(function (extension) { return extension._loadMaterialAsync(context, material, babylonMesh, babylonDrawMode, assign); });
  106219. };
  106220. /** Helper method called by the loader to allow extensions to override loading uris. */
  106221. GLTFLoaderExtension._LoadUriAsync = function (loader, context, uri) {
  106222. return loader._applyExtensions(function (extension) { return extension._loadUriAsync(context, uri); });
  106223. };
  106224. return GLTFLoaderExtension;
  106225. }());
  106226. GLTF2.GLTFLoaderExtension = GLTFLoaderExtension;
  106227. })(GLTF2 = BABYLON.GLTF2 || (BABYLON.GLTF2 = {}));
  106228. })(BABYLON || (BABYLON = {}));
  106229. //# sourceMappingURL=babylon.glTFLoaderExtension.js.map
  106230. var BABYLON;
  106231. (function (BABYLON) {
  106232. var GLTF2;
  106233. (function (GLTF2) {
  106234. var Extensions;
  106235. (function (Extensions) {
  106236. var NAME = "MSFT_lod";
  106237. /**
  106238. * [Specification](https://github.com/KhronosGroup/glTF/tree/master/extensions/2.0/Vendor/MSFT_lod)
  106239. */
  106240. var MSFT_lod = /** @class */ (function (_super) {
  106241. __extends(MSFT_lod, _super);
  106242. function MSFT_lod() {
  106243. var _this = _super !== null && _super.apply(this, arguments) || this;
  106244. _this.name = NAME;
  106245. /**
  106246. * Maximum number of LODs to load, starting from the lowest LOD.
  106247. */
  106248. _this.maxLODsToLoad = Number.MAX_VALUE;
  106249. _this._loadingNodeLOD = null;
  106250. _this._loadNodeSignals = {};
  106251. _this._loadingMaterialLOD = null;
  106252. _this._loadMaterialSignals = {};
  106253. return _this;
  106254. }
  106255. MSFT_lod.prototype._loadNodeAsync = function (context, node) {
  106256. var _this = this;
  106257. return this._loadExtensionAsync(context, node, function (extensionContext, extension) {
  106258. var firstPromise;
  106259. var nodeLODs = _this._getLODs(extensionContext, node, _this._loader._gltf.nodes, extension.ids);
  106260. var _loop_1 = function (indexLOD) {
  106261. var nodeLOD = nodeLODs[indexLOD];
  106262. if (indexLOD !== 0) {
  106263. _this._loadingNodeLOD = nodeLOD;
  106264. if (!_this._loadNodeSignals[nodeLOD._index]) {
  106265. _this._loadNodeSignals[nodeLOD._index] = new BABYLON.Deferred();
  106266. }
  106267. }
  106268. var promise = _this._loader._loadNodeAsync("#/nodes/" + nodeLOD._index, nodeLOD).then(function () {
  106269. if (indexLOD !== 0) {
  106270. var previousNodeLOD = nodeLODs[indexLOD - 1];
  106271. if (previousNodeLOD._babylonMesh) {
  106272. previousNodeLOD._babylonMesh.dispose(false, true);
  106273. delete previousNodeLOD._babylonMesh;
  106274. }
  106275. }
  106276. if (indexLOD !== nodeLODs.length - 1) {
  106277. var nodeIndex = nodeLODs[indexLOD + 1]._index;
  106278. if (_this._loadNodeSignals[nodeIndex]) {
  106279. _this._loadNodeSignals[nodeIndex].resolve();
  106280. delete _this._loadNodeSignals[nodeIndex];
  106281. }
  106282. }
  106283. });
  106284. if (indexLOD === 0) {
  106285. firstPromise = promise;
  106286. }
  106287. else {
  106288. _this._loader._completePromises.push(promise);
  106289. _this._loadingNodeLOD = null;
  106290. }
  106291. };
  106292. for (var indexLOD = 0; indexLOD < nodeLODs.length; indexLOD++) {
  106293. _loop_1(indexLOD);
  106294. }
  106295. return firstPromise;
  106296. });
  106297. };
  106298. MSFT_lod.prototype._loadMaterialAsync = function (context, material, babylonMesh, babylonDrawMode, assign) {
  106299. var _this = this;
  106300. // Don't load material LODs if already loading a node LOD.
  106301. if (this._loadingNodeLOD) {
  106302. return null;
  106303. }
  106304. return this._loadExtensionAsync(context, material, function (extensionContext, extension) {
  106305. var firstPromise;
  106306. var materialLODs = _this._getLODs(extensionContext, material, _this._loader._gltf.materials, extension.ids);
  106307. var _loop_2 = function (indexLOD) {
  106308. var materialLOD = materialLODs[indexLOD];
  106309. if (indexLOD !== 0) {
  106310. _this._loadingMaterialLOD = materialLOD;
  106311. if (!_this._loadMaterialSignals[materialLOD._index]) {
  106312. _this._loadMaterialSignals[materialLOD._index] = new BABYLON.Deferred();
  106313. }
  106314. }
  106315. var promise = _this._loader._loadMaterialAsync("#/materials/" + materialLOD._index, materialLOD, babylonMesh, babylonDrawMode, indexLOD === 0 ? assign : function () { }).then(function () {
  106316. if (indexLOD !== 0) {
  106317. var babylonDataLOD = materialLOD._babylonData;
  106318. assign(babylonDataLOD[babylonDrawMode].material);
  106319. var previousBabylonDataLOD = materialLODs[indexLOD - 1]._babylonData;
  106320. if (previousBabylonDataLOD[babylonDrawMode]) {
  106321. previousBabylonDataLOD[babylonDrawMode].material.dispose();
  106322. delete previousBabylonDataLOD[babylonDrawMode];
  106323. }
  106324. }
  106325. if (indexLOD !== materialLODs.length - 1) {
  106326. var materialIndex = materialLODs[indexLOD + 1]._index;
  106327. if (_this._loadMaterialSignals[materialIndex]) {
  106328. _this._loadMaterialSignals[materialIndex].resolve();
  106329. delete _this._loadMaterialSignals[materialIndex];
  106330. }
  106331. }
  106332. });
  106333. if (indexLOD === 0) {
  106334. firstPromise = promise;
  106335. }
  106336. else {
  106337. _this._loader._completePromises.push(promise);
  106338. _this._loadingMaterialLOD = null;
  106339. }
  106340. };
  106341. for (var indexLOD = 0; indexLOD < materialLODs.length; indexLOD++) {
  106342. _loop_2(indexLOD);
  106343. }
  106344. return firstPromise;
  106345. });
  106346. };
  106347. MSFT_lod.prototype._loadUriAsync = function (context, uri) {
  106348. var _this = this;
  106349. // Defer the loading of uris if loading a material or node LOD.
  106350. if (this._loadingMaterialLOD) {
  106351. var index = this._loadingMaterialLOD._index;
  106352. return this._loadMaterialSignals[index].promise.then(function () {
  106353. return _this._loader._loadUriAsync(context, uri);
  106354. });
  106355. }
  106356. else if (this._loadingNodeLOD) {
  106357. var index = this._loadingNodeLOD._index;
  106358. return this._loadNodeSignals[index].promise.then(function () {
  106359. return _this._loader._loadUriAsync(context, uri);
  106360. });
  106361. }
  106362. return null;
  106363. };
  106364. /**
  106365. * Gets an array of LOD properties from lowest to highest.
  106366. */
  106367. MSFT_lod.prototype._getLODs = function (context, property, array, ids) {
  106368. if (this.maxLODsToLoad <= 0) {
  106369. throw new Error("maxLODsToLoad must be greater than zero");
  106370. }
  106371. var properties = new Array();
  106372. for (var i = ids.length - 1; i >= 0; i--) {
  106373. properties.push(GLTF2.GLTFLoader._GetProperty(context + "/ids/" + ids[i], array, ids[i]));
  106374. if (properties.length === this.maxLODsToLoad) {
  106375. return properties;
  106376. }
  106377. }
  106378. properties.push(property);
  106379. return properties;
  106380. };
  106381. return MSFT_lod;
  106382. }(GLTF2.GLTFLoaderExtension));
  106383. Extensions.MSFT_lod = MSFT_lod;
  106384. GLTF2.GLTFLoader._Register(NAME, function (loader) { return new MSFT_lod(loader); });
  106385. })(Extensions = GLTF2.Extensions || (GLTF2.Extensions = {}));
  106386. })(GLTF2 = BABYLON.GLTF2 || (BABYLON.GLTF2 = {}));
  106387. })(BABYLON || (BABYLON = {}));
  106388. //# sourceMappingURL=MSFT_lod.js.map
  106389. var BABYLON;
  106390. (function (BABYLON) {
  106391. var GLTF2;
  106392. (function (GLTF2) {
  106393. var Extensions;
  106394. (function (Extensions) {
  106395. var NAME = "MSFT_minecraftMesh";
  106396. /** @hidden */
  106397. var MSFT_minecraftMesh = /** @class */ (function (_super) {
  106398. __extends(MSFT_minecraftMesh, _super);
  106399. function MSFT_minecraftMesh(loader) {
  106400. var _this = _super.call(this, loader) || this;
  106401. _this.name = NAME;
  106402. _this._onMaterialLoaded = function (material) {
  106403. if (material.needAlphaBlending()) {
  106404. material.forceDepthWrite = true;
  106405. material.separateCullingPass = true;
  106406. }
  106407. material.backFaceCulling = material.forceDepthWrite;
  106408. material.twoSidedLighting = true;
  106409. };
  106410. var meshes = loader._gltf.meshes;
  106411. if (meshes && meshes.length) {
  106412. for (var _i = 0, meshes_1 = meshes; _i < meshes_1.length; _i++) {
  106413. var mesh = meshes_1[_i];
  106414. if (mesh && mesh.extras && mesh.extras.MSFT_minecraftMesh) {
  106415. _this._loader.onMaterialLoadedObservable.add(_this._onMaterialLoaded);
  106416. break;
  106417. }
  106418. }
  106419. }
  106420. return _this;
  106421. }
  106422. return MSFT_minecraftMesh;
  106423. }(GLTF2.GLTFLoaderExtension));
  106424. Extensions.MSFT_minecraftMesh = MSFT_minecraftMesh;
  106425. GLTF2.GLTFLoader._Register(NAME, function (loader) { return new MSFT_minecraftMesh(loader); });
  106426. })(Extensions = GLTF2.Extensions || (GLTF2.Extensions = {}));
  106427. })(GLTF2 = BABYLON.GLTF2 || (BABYLON.GLTF2 = {}));
  106428. })(BABYLON || (BABYLON = {}));
  106429. //# sourceMappingURL=MSFT_minecraftMesh.js.map
  106430. var BABYLON;
  106431. (function (BABYLON) {
  106432. var GLTF2;
  106433. (function (GLTF2) {
  106434. var Extensions;
  106435. (function (Extensions) {
  106436. var NAME = "MSFT_sRGBFactors";
  106437. /** @hidden */
  106438. var MSFT_sRGBFactors = /** @class */ (function (_super) {
  106439. __extends(MSFT_sRGBFactors, _super);
  106440. function MSFT_sRGBFactors(loader) {
  106441. var _this = _super.call(this, loader) || this;
  106442. _this.name = NAME;
  106443. _this._onMaterialLoaded = function (material) {
  106444. if (!material.albedoTexture) {
  106445. material.albedoColor.toLinearSpaceToRef(material.albedoColor);
  106446. }
  106447. if (!material.reflectivityTexture) {
  106448. material.reflectivityColor.toLinearSpaceToRef(material.reflectivityColor);
  106449. }
  106450. };
  106451. var materials = loader._gltf.materials;
  106452. if (materials && materials.length) {
  106453. for (var _i = 0, materials_1 = materials; _i < materials_1.length; _i++) {
  106454. var material = materials_1[_i];
  106455. if (material && material.extras && material.extras.MSFT_sRGBFactors) {
  106456. _this._loader.onMaterialLoadedObservable.add(_this._onMaterialLoaded);
  106457. break;
  106458. }
  106459. }
  106460. }
  106461. return _this;
  106462. }
  106463. return MSFT_sRGBFactors;
  106464. }(GLTF2.GLTFLoaderExtension));
  106465. Extensions.MSFT_sRGBFactors = MSFT_sRGBFactors;
  106466. GLTF2.GLTFLoader._Register(NAME, function (loader) { return new MSFT_sRGBFactors(loader); });
  106467. })(Extensions = GLTF2.Extensions || (GLTF2.Extensions = {}));
  106468. })(GLTF2 = BABYLON.GLTF2 || (BABYLON.GLTF2 = {}));
  106469. })(BABYLON || (BABYLON = {}));
  106470. //# sourceMappingURL=MSFT_sRGBFactors.js.map
  106471. var BABYLON;
  106472. (function (BABYLON) {
  106473. var GLTF2;
  106474. (function (GLTF2) {
  106475. var Extensions;
  106476. (function (Extensions) {
  106477. var NAME = "KHR_draco_mesh_compression";
  106478. /**
  106479. * [Specification](https://github.com/KhronosGroup/glTF/tree/master/extensions/2.0/Khronos/KHR_draco_mesh_compression)
  106480. */
  106481. var KHR_draco_mesh_compression = /** @class */ (function (_super) {
  106482. __extends(KHR_draco_mesh_compression, _super);
  106483. function KHR_draco_mesh_compression(loader) {
  106484. var _this = _super.call(this, loader) || this;
  106485. _this.name = NAME;
  106486. _this._dracoCompression = null;
  106487. // Disable extension if decoder is not available.
  106488. if (!BABYLON.DracoCompression.DecoderAvailable) {
  106489. _this.enabled = false;
  106490. }
  106491. return _this;
  106492. }
  106493. KHR_draco_mesh_compression.prototype.dispose = function () {
  106494. if (this._dracoCompression) {
  106495. this._dracoCompression.dispose();
  106496. }
  106497. _super.prototype.dispose.call(this);
  106498. };
  106499. KHR_draco_mesh_compression.prototype._loadVertexDataAsync = function (context, primitive, babylonMesh) {
  106500. var _this = this;
  106501. return this._loadExtensionAsync(context, primitive, function (extensionContext, extension) {
  106502. if (primitive.mode != undefined) {
  106503. if (primitive.mode !== 5 /* TRIANGLE_STRIP */ &&
  106504. primitive.mode !== 4 /* TRIANGLES */) {
  106505. throw new Error(context + ": Unsupported mode " + primitive.mode);
  106506. }
  106507. // TODO: handle triangle strips
  106508. if (primitive.mode === 5 /* TRIANGLE_STRIP */) {
  106509. throw new Error(context + ": Mode " + primitive.mode + " is not currently supported");
  106510. }
  106511. }
  106512. var attributes = {};
  106513. var loadAttribute = function (name, kind) {
  106514. var uniqueId = extension.attributes[name];
  106515. if (uniqueId == undefined) {
  106516. return;
  106517. }
  106518. babylonMesh._delayInfo = babylonMesh._delayInfo || [];
  106519. if (babylonMesh._delayInfo.indexOf(kind) === -1) {
  106520. babylonMesh._delayInfo.push(kind);
  106521. }
  106522. attributes[kind] = uniqueId;
  106523. };
  106524. loadAttribute("POSITION", BABYLON.VertexBuffer.PositionKind);
  106525. loadAttribute("NORMAL", BABYLON.VertexBuffer.NormalKind);
  106526. loadAttribute("TANGENT", BABYLON.VertexBuffer.TangentKind);
  106527. loadAttribute("TEXCOORD_0", BABYLON.VertexBuffer.UVKind);
  106528. loadAttribute("TEXCOORD_1", BABYLON.VertexBuffer.UV2Kind);
  106529. loadAttribute("JOINTS_0", BABYLON.VertexBuffer.MatricesIndicesKind);
  106530. loadAttribute("WEIGHTS_0", BABYLON.VertexBuffer.MatricesWeightsKind);
  106531. loadAttribute("COLOR_0", BABYLON.VertexBuffer.ColorKind);
  106532. var bufferView = GLTF2.GLTFLoader._GetProperty(extensionContext, _this._loader._gltf.bufferViews, extension.bufferView);
  106533. if (!bufferView._dracoBabylonGeometry) {
  106534. bufferView._dracoBabylonGeometry = _this._loader._loadBufferViewAsync("#/bufferViews/" + bufferView._index, bufferView).then(function (data) {
  106535. if (!_this._dracoCompression) {
  106536. _this._dracoCompression = new BABYLON.DracoCompression();
  106537. }
  106538. return _this._dracoCompression.decodeMeshAsync(data, attributes).then(function (babylonVertexData) {
  106539. var babylonGeometry = new BABYLON.Geometry(babylonMesh.name, _this._loader._babylonScene);
  106540. babylonVertexData.applyToGeometry(babylonGeometry);
  106541. return babylonGeometry;
  106542. }).catch(function (error) {
  106543. throw new Error(context + ": " + error.message);
  106544. });
  106545. });
  106546. }
  106547. return bufferView._dracoBabylonGeometry;
  106548. });
  106549. };
  106550. return KHR_draco_mesh_compression;
  106551. }(GLTF2.GLTFLoaderExtension));
  106552. Extensions.KHR_draco_mesh_compression = KHR_draco_mesh_compression;
  106553. GLTF2.GLTFLoader._Register(NAME, function (loader) { return new KHR_draco_mesh_compression(loader); });
  106554. })(Extensions = GLTF2.Extensions || (GLTF2.Extensions = {}));
  106555. })(GLTF2 = BABYLON.GLTF2 || (BABYLON.GLTF2 = {}));
  106556. })(BABYLON || (BABYLON = {}));
  106557. //# sourceMappingURL=KHR_draco_mesh_compression.js.map
  106558. var BABYLON;
  106559. (function (BABYLON) {
  106560. var GLTF2;
  106561. (function (GLTF2) {
  106562. var Extensions;
  106563. (function (Extensions) {
  106564. var NAME = "KHR_materials_pbrSpecularGlossiness";
  106565. /**
  106566. * [Specification](https://github.com/KhronosGroup/glTF/tree/master/extensions/2.0/Khronos/KHR_materials_pbrSpecularGlossiness)
  106567. */
  106568. var KHR_materials_pbrSpecularGlossiness = /** @class */ (function (_super) {
  106569. __extends(KHR_materials_pbrSpecularGlossiness, _super);
  106570. function KHR_materials_pbrSpecularGlossiness() {
  106571. var _this = _super !== null && _super.apply(this, arguments) || this;
  106572. _this.name = NAME;
  106573. return _this;
  106574. }
  106575. KHR_materials_pbrSpecularGlossiness.prototype._loadMaterialAsync = function (context, material, babylonMesh, babylonDrawMode, assign) {
  106576. var _this = this;
  106577. return this._loadExtensionAsync(context, material, function (extensionContext, extension) {
  106578. material._babylonData = material._babylonData || {};
  106579. var babylonData = material._babylonData[babylonDrawMode];
  106580. if (!babylonData) {
  106581. var promises = new Array();
  106582. var name_1 = material.name || "materialSG_" + material._index;
  106583. var babylonMaterial = _this._loader._createMaterial(name_1, babylonDrawMode);
  106584. promises.push(_this._loader._loadMaterialBasePropertiesAsync(context, material, babylonMaterial));
  106585. promises.push(_this._loadSpecularGlossinessPropertiesAsync(extensionContext, material, extension, babylonMaterial));
  106586. _this._loader.onMaterialLoadedObservable.notifyObservers(babylonMaterial);
  106587. babylonData = {
  106588. material: babylonMaterial,
  106589. meshes: [],
  106590. loaded: Promise.all(promises).then(function () { })
  106591. };
  106592. material._babylonData[babylonDrawMode] = babylonData;
  106593. }
  106594. babylonData.meshes.push(babylonMesh);
  106595. assign(babylonData.material);
  106596. return babylonData.loaded;
  106597. });
  106598. };
  106599. KHR_materials_pbrSpecularGlossiness.prototype._loadSpecularGlossinessPropertiesAsync = function (context, material, properties, babylonMaterial) {
  106600. var promises = new Array();
  106601. if (properties.diffuseFactor) {
  106602. babylonMaterial.albedoColor = BABYLON.Color3.FromArray(properties.diffuseFactor);
  106603. babylonMaterial.alpha = properties.diffuseFactor[3];
  106604. }
  106605. else {
  106606. babylonMaterial.albedoColor = BABYLON.Color3.White();
  106607. }
  106608. babylonMaterial.reflectivityColor = properties.specularFactor ? BABYLON.Color3.FromArray(properties.specularFactor) : BABYLON.Color3.White();
  106609. babylonMaterial.microSurface = properties.glossinessFactor == undefined ? 1 : properties.glossinessFactor;
  106610. if (properties.diffuseTexture) {
  106611. promises.push(this._loader._loadTextureAsync(context + "/diffuseTexture", properties.diffuseTexture, function (texture) {
  106612. babylonMaterial.albedoTexture = texture;
  106613. }));
  106614. }
  106615. if (properties.specularGlossinessTexture) {
  106616. promises.push(this._loader._loadTextureAsync(context + "/specularGlossinessTexture", properties.specularGlossinessTexture, function (texture) {
  106617. babylonMaterial.reflectivityTexture = texture;
  106618. }));
  106619. babylonMaterial.reflectivityTexture.hasAlpha = true;
  106620. babylonMaterial.useMicroSurfaceFromReflectivityMapAlpha = true;
  106621. }
  106622. this._loader._loadMaterialAlphaProperties(context, material, babylonMaterial);
  106623. return Promise.all(promises).then(function () { });
  106624. };
  106625. return KHR_materials_pbrSpecularGlossiness;
  106626. }(GLTF2.GLTFLoaderExtension));
  106627. Extensions.KHR_materials_pbrSpecularGlossiness = KHR_materials_pbrSpecularGlossiness;
  106628. GLTF2.GLTFLoader._Register(NAME, function (loader) { return new KHR_materials_pbrSpecularGlossiness(loader); });
  106629. })(Extensions = GLTF2.Extensions || (GLTF2.Extensions = {}));
  106630. })(GLTF2 = BABYLON.GLTF2 || (BABYLON.GLTF2 = {}));
  106631. })(BABYLON || (BABYLON = {}));
  106632. //# sourceMappingURL=KHR_materials_pbrSpecularGlossiness.js.map
  106633. var BABYLON;
  106634. (function (BABYLON) {
  106635. var GLTF2;
  106636. (function (GLTF2) {
  106637. var Extensions;
  106638. (function (Extensions) {
  106639. var NAME = "KHR_materials_unlit";
  106640. /**
  106641. * [Specification](https://github.com/donmccurdy/glTF/tree/feat-khr-materials-cmnConstant/extensions/2.0/Khronos/KHR_materials_unlit) (Experimental)
  106642. */
  106643. var KHR_materials_unlit = /** @class */ (function (_super) {
  106644. __extends(KHR_materials_unlit, _super);
  106645. function KHR_materials_unlit() {
  106646. var _this = _super !== null && _super.apply(this, arguments) || this;
  106647. _this.name = NAME;
  106648. return _this;
  106649. }
  106650. KHR_materials_unlit.prototype._loadMaterialAsync = function (context, material, babylonMesh, babylonDrawMode, assign) {
  106651. var _this = this;
  106652. return this._loadExtensionAsync(context, material, function () {
  106653. material._babylonData = material._babylonData || {};
  106654. var babylonData = material._babylonData[babylonDrawMode];
  106655. if (!babylonData) {
  106656. var name_1 = material.name || "materialUnlit_" + material._index;
  106657. var babylonMaterial = _this._loader._createMaterial(name_1, babylonDrawMode);
  106658. babylonMaterial.unlit = true;
  106659. var promise = _this._loadUnlitPropertiesAsync(context, material, babylonMaterial);
  106660. _this._loader.onMaterialLoadedObservable.notifyObservers(babylonMaterial);
  106661. babylonData = {
  106662. material: babylonMaterial,
  106663. meshes: [],
  106664. loaded: promise
  106665. };
  106666. material._babylonData[babylonDrawMode] = babylonData;
  106667. }
  106668. babylonData.meshes.push(babylonMesh);
  106669. assign(babylonData.material);
  106670. return babylonData.loaded;
  106671. });
  106672. };
  106673. KHR_materials_unlit.prototype._loadUnlitPropertiesAsync = function (context, material, babylonMaterial) {
  106674. var promises = new Array();
  106675. // Ensure metallic workflow
  106676. babylonMaterial.metallic = 1;
  106677. babylonMaterial.roughness = 1;
  106678. var properties = material.pbrMetallicRoughness;
  106679. if (properties) {
  106680. if (properties.baseColorFactor) {
  106681. babylonMaterial.albedoColor = BABYLON.Color3.FromArray(properties.baseColorFactor);
  106682. babylonMaterial.alpha = properties.baseColorFactor[3];
  106683. }
  106684. else {
  106685. babylonMaterial.albedoColor = BABYLON.Color3.White();
  106686. }
  106687. if (properties.baseColorTexture) {
  106688. promises.push(this._loader._loadTextureAsync(context + "/baseColorTexture", properties.baseColorTexture, function (texture) {
  106689. babylonMaterial.albedoTexture = texture;
  106690. }));
  106691. }
  106692. }
  106693. if (material.doubleSided) {
  106694. babylonMaterial.backFaceCulling = false;
  106695. babylonMaterial.twoSidedLighting = true;
  106696. }
  106697. this._loader._loadMaterialAlphaProperties(context, material, babylonMaterial);
  106698. return Promise.all(promises).then(function () { });
  106699. };
  106700. return KHR_materials_unlit;
  106701. }(GLTF2.GLTFLoaderExtension));
  106702. Extensions.KHR_materials_unlit = KHR_materials_unlit;
  106703. GLTF2.GLTFLoader._Register(NAME, function (loader) { return new KHR_materials_unlit(loader); });
  106704. })(Extensions = GLTF2.Extensions || (GLTF2.Extensions = {}));
  106705. })(GLTF2 = BABYLON.GLTF2 || (BABYLON.GLTF2 = {}));
  106706. })(BABYLON || (BABYLON = {}));
  106707. var BABYLON;
  106708. (function (BABYLON) {
  106709. var GLTF2;
  106710. (function (GLTF2) {
  106711. var Extensions;
  106712. (function (Extensions) {
  106713. var NAME = "KHR_lights";
  106714. var LightType;
  106715. (function (LightType) {
  106716. LightType["AMBIENT"] = "ambient";
  106717. LightType["DIRECTIONAL"] = "directional";
  106718. LightType["POINT"] = "point";
  106719. LightType["SPOT"] = "spot";
  106720. })(LightType || (LightType = {}));
  106721. /**
  106722. * [Specification](https://github.com/MiiBond/glTF/tree/khr_lights_v1/extensions/Khronos/KHR_lights) (Experimental)
  106723. */
  106724. var KHR_lights = /** @class */ (function (_super) {
  106725. __extends(KHR_lights, _super);
  106726. function KHR_lights() {
  106727. var _this = _super !== null && _super.apply(this, arguments) || this;
  106728. _this.name = NAME;
  106729. return _this;
  106730. }
  106731. KHR_lights.prototype._loadSceneAsync = function (context, scene) {
  106732. var _this = this;
  106733. return this._loadExtensionAsync(context, scene, function (extensionContext, extension) {
  106734. var promise = _this._loader._loadSceneAsync(extensionContext, scene);
  106735. var light = GLTF2.GLTFLoader._GetProperty(extensionContext, _this._lights, extension.light);
  106736. if (light.type !== LightType.AMBIENT) {
  106737. throw new Error(extensionContext + ": Only ambient lights are allowed on a scene");
  106738. }
  106739. _this._loader._babylonScene.ambientColor = light.color ? BABYLON.Color3.FromArray(light.color) : BABYLON.Color3.Black();
  106740. return promise;
  106741. });
  106742. };
  106743. KHR_lights.prototype._loadNodeAsync = function (context, node) {
  106744. var _this = this;
  106745. return this._loadExtensionAsync(context, node, function (extensionContext, extension) {
  106746. var promise = _this._loader._loadNodeAsync(extensionContext, node);
  106747. var babylonLight;
  106748. var light = GLTF2.GLTFLoader._GetProperty(extensionContext, _this._lights, extension.light);
  106749. var name = node._babylonMesh.name;
  106750. switch (light.type) {
  106751. case LightType.AMBIENT: {
  106752. throw new Error(extensionContext + ": Ambient lights are not allowed on a node");
  106753. }
  106754. case LightType.DIRECTIONAL: {
  106755. babylonLight = new BABYLON.DirectionalLight(name, BABYLON.Vector3.Forward(), _this._loader._babylonScene);
  106756. break;
  106757. }
  106758. case LightType.POINT: {
  106759. babylonLight = new BABYLON.PointLight(name, BABYLON.Vector3.Zero(), _this._loader._babylonScene);
  106760. break;
  106761. }
  106762. case LightType.SPOT: {
  106763. var spotLight = light;
  106764. // TODO: support inner and outer cone angles
  106765. //const innerConeAngle = spotLight.innerConeAngle || 0;
  106766. var outerConeAngle = spotLight.outerConeAngle || Math.PI / 4;
  106767. babylonLight = new BABYLON.SpotLight(name, BABYLON.Vector3.Zero(), BABYLON.Vector3.Forward(), outerConeAngle, 2, _this._loader._babylonScene);
  106768. break;
  106769. }
  106770. default: {
  106771. throw new Error(extensionContext + ": Invalid light type (" + light.type + ")");
  106772. }
  106773. }
  106774. babylonLight.diffuse = light.color ? BABYLON.Color3.FromArray(light.color) : BABYLON.Color3.White();
  106775. babylonLight.intensity = light.intensity == undefined ? 1 : light.intensity;
  106776. babylonLight.parent = node._babylonMesh;
  106777. return promise;
  106778. });
  106779. };
  106780. Object.defineProperty(KHR_lights.prototype, "_lights", {
  106781. get: function () {
  106782. var extensions = this._loader._gltf.extensions;
  106783. if (!extensions || !extensions[this.name]) {
  106784. throw new Error("#/extensions: '" + this.name + "' not found");
  106785. }
  106786. var extension = extensions[this.name];
  106787. return extension.lights;
  106788. },
  106789. enumerable: true,
  106790. configurable: true
  106791. });
  106792. return KHR_lights;
  106793. }(GLTF2.GLTFLoaderExtension));
  106794. Extensions.KHR_lights = KHR_lights;
  106795. GLTF2.GLTFLoader._Register(NAME, function (loader) { return new KHR_lights(loader); });
  106796. })(Extensions = GLTF2.Extensions || (GLTF2.Extensions = {}));
  106797. })(GLTF2 = BABYLON.GLTF2 || (BABYLON.GLTF2 = {}));
  106798. })(BABYLON || (BABYLON = {}));
  106799. return BABYLON;
  106800. });
  106801. /***/ }),
  106802. /* 35 */
  106803. /***/ (function(module, exports, __webpack_require__) {
  106804. /*!
  106805. * PEP v0.4.3 | https://github.com/jquery/PEP
  106806. * Copyright jQuery Foundation and other contributors | http://jquery.org/license
  106807. */
  106808. !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);
  106809. // define inherited MouseEvent properties
  106810. // skip bubbles and cancelable since they're set above in initEvent()
  106811. for(var d,e=2;e<m.length;e++)d=m[e],c[d]=b[d]||n[e];c.buttons=b.buttons||0;
  106812. // Spec requires that pointers without pressure specified use 0.5 for down
  106813. // state and 0 for up state.
  106814. var f=0;
  106815. // add x/y properties aliased to clientX/Y
  106816. // define the properties of the PointerEvent interface
  106817. 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(){
  106818. // only activate if this platform does not have pointer events
  106819. 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}})}/**
  106820. * This is the constructor for new PointerEvents.
  106821. *
  106822. * New Pointer Events must be given a type, and an optional dictionary of
  106823. * initialization properties.
  106824. *
  106825. * Due to certain platform requirements, events returned from the constructor
  106826. * identify as MouseEvents.
  106827. *
  106828. * @constructor
  106829. * @param {String} inType The type of the event to create.
  106830. * @param {Object} [inDict] An optional dictionary of initial event properties.
  106831. * @return {Event} A new PointerEvent of type `inType`, initialized with properties from `inDict`.
  106832. */
  106833. 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},
  106834. // return value, key, map
  106835. forEach:function(a,b){return this.array.forEach(function(c,d){a.call(b,c,d,this)},this)}};var q=[
  106836. // MouseEvent
  106837. "bubbles","cancelable","view","detail","screenX","screenY","clientX","clientY","ctrlKey","altKey","shiftKey","metaKey","button","relatedTarget",
  106838. // DOM Level 3
  106839. "buttons",
  106840. // PointerEvent
  106841. "pointerId","width","height","pressure","tiltX","tiltY","pointerType","hwTimestamp","isPrimary",
  106842. // event instance
  106843. "type","target","currentTarget","which","pageX","pageY","timeStamp"],r=[
  106844. // MouseEvent
  106845. !1,!1,null,null,0,0,0,0,!1,!1,!1,!1,0,null,
  106846. // DOM Level 3
  106847. 0,
  106848. // PointerEvent
  106849. 0,0,0,0,0,0,"",0,!1,
  106850. // event instance
  106851. "",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),
  106852. // Scope objects for native events.
  106853. // This exists for ease of testing.
  106854. eventSources:Object.create(null),eventSourceList:[],/**
  106855. * Add a new event source that will generate pointer events.
  106856. *
  106857. * `inSource` must contain an array of event names named `events`, and
  106858. * functions with the names specified in the `events` array.
  106859. * @param {string} name A name for the event source
  106860. * @param {Object} source A new source of platform events.
  106861. */
  106862. 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++)
  106863. // call eventsource register
  106864. b.register.call(b,a)},unregister:function(a){for(var b,c=this.eventSourceList.length,d=0;d<c&&(b=this.eventSourceList[d]);d++)
  106865. // call eventsource register
  106866. b.unregister.call(b,a)},contains:/*scope.external.contains || */function(a,b){try{return a.contains(b)}catch(c){
  106867. // most likely: https://bugzilla.mozilla.org/show_bug.cgi?id=208427
  106868. return!1}},
  106869. // EVENTS
  106870. 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)},
  106871. // LISTENER LOGIC
  106872. eventHandler:function(a){
  106873. // This is used to prevent multiple dispatch of pointerevents from
  106874. // platform events. This can happen when two elements in different scopes
  106875. // are set up to create pointer events, which is relevant to Shadow DOM.
  106876. if(!a._handledByPE){var b=a.type,c=this.eventMap&&this.eventMap[b];c&&c(a),a._handledByPE=!0}},
  106877. // set up event listeners
  106878. listen:function(a,b){b.forEach(function(b){this.addEvent(a,b)},this)},
  106879. // remove event listeners
  106880. 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)},
  106881. // EVENT CREATION AND TRACKING
  106882. /**
  106883. * Creates a new Event of type `inType`, based on the information in
  106884. * `inEvent`.
  106885. *
  106886. * @param {string} inType A string representing the type of event to create
  106887. * @param {Event} inEvent A platform event with a target
  106888. * @return {Event} A PointerEvent of type `inType`
  106889. */
  106890. makeEvent:function(b,c){
  106891. // relatedTarget must be null if pointer is captured
  106892. 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},
  106893. // make and dispatch an event in one call
  106894. fireEvent:function(a,b){var c=this.makeEvent(a,b);return this.dispatchEvent(c)},/**
  106895. * Returns a snapshot of inEvent, with writable properties.
  106896. *
  106897. * @param {Event} inEvent An event that contains properties to copy.
  106898. * @return {Object} An object containing shallow copies of `inEvent`'s
  106899. * properties.
  106900. */
  106901. 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],
  106902. // Work around SVGInstanceElement shadow tree
  106903. // Return the <use> element that is represented by the instance for Safari, Chrome, IE.
  106904. // This is the behavior implemented by Firefox.
  106905. !t||"target"!==b&&"relatedTarget"!==b||c[b]instanceof SVGElementInstance&&(c[b]=c[b].correspondingUseElement);
  106906. // keep the semantics of preventDefault
  106907. 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){
  106908. // Order of conditions due to document.contains() missing in IE.
  106909. for(var d=a.target,e=[];d!==document&&!d.contains(a.relatedTarget);)
  106910. // Touch: Do not propagate if node is detached.
  106911. 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)}},/**
  106912. * Dispatches the event to its target.
  106913. *
  106914. * @param {Event} inEvent The event to be dispatched.
  106915. * @return {Boolean} True if an event handler returns true, false otherwise.
  106916. */
  106917. 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(
  106918. // is element a shadow host?
  106919. e=this.targetingShadow(f);e;){if(
  106920. // find the the element inside the shadow root
  106921. d=e.elementFromPoint(b,c)){
  106922. // shadowed element may contain a shadow root
  106923. var g=this.targetingShadow(d);return this.searchRoot(g,b,c)||d}
  106924. // check for older shadows
  106925. e=this.olderShadow(e)}
  106926. // light dom element is the target
  106927. return f}},owner:function(a){
  106928. // walk up until you hit the shadow root or document
  106929. for(var b=a;b.parentNode;)b=b.parentNode;
  106930. // the owner element is expected to be a Document or ShadowRoot
  106931. 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);
  106932. // if x, y is not in this root, fall back to document search
  106933. 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){
  106934. // Only watch scopes that can target find, as these are top-level.
  106935. // Otherwise we can see duplicate additions and removals that add noise.
  106936. //
  106937. // TODO(dfreedman): For some instances with ShadowDOMPolyfill, we can see
  106938. // a removal without an insertion when a node is redistributed among
  106939. // shadows. Since it all ends up correct in the document, watching only
  106940. // the document will yield the correct mutations to watch.
  106941. 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))},
  106942. // register all touch-action = none nodes on document load
  106943. 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){
  106944. // find children with touch-action
  106945. var b=x(a,this.findElements,this);
  106946. // flatten the list
  106947. // make sure the added nodes are accounted for
  106948. 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){}
  106949. // handler block for native mouse events
  106950. 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:[],
  106951. // collide with the global mouse listener
  106952. 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++){
  106953. // simulated mouse events will be swallowed near a primary touchend
  106954. 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);
  106955. // Update buttons state after possible out-of-document mouseup.
  106956. 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];
  106957. // Produces wrong state of buttons in Browsers without `buttons` support
  106958. // when a mouse button that was pressed outside the document is released
  106959. // inside and other buttons are still pressed down.
  106960. c.buttons=b?b.buttons&~d:0,a.buttons=c.buttons}H.set(this.POINTER_ID,a),
  106961. // Support: Firefox <=44 only
  106962. // FF Ubuntu includes the lifted button in the `buttons` property on
  106963. // mouseup.
  106964. // https://bugzilla.mozilla.org/show_bug.cgi?id=1223366
  106965. 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),
  106966. // set touch-action on shadows as well
  106967. 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),
  106968. // remove touch-action from shadow
  106969. 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);
  106970. // simply update scrollType if listeners are already established
  106971. 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){
  106972. // set primary touch if there no pointers, or the only pointer is the mouse
  106973. (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,
  106974. // forward modifier keys
  106975. c.altKey=b.altKey,c.ctrlKey=b.ctrlKey,c.metaKey=b.metaKey,c.shiftKey=b.shiftKey;
  106976. // forward touch preventDefaults
  106977. 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))},
  106978. // For single axis scrollers, determines whether the element should emit
  106979. // pointer events or behave as a scroller
  106980. shouldScroll:function(a){if(this.firstXY){var b,c=a.currentTarget._scrollType;if("none"===c)
  106981. // this element is a touch-action: none, should never scroll
  106982. b=!1;else if("XY"===c)
  106983. // this element should always scroll
  106984. 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]);
  106985. // if delta in the scroll axis > delta other axis, scroll instead of
  106986. // making events
  106987. 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},
  106988. // In some instances, a touchstart can happen without a touchend. This
  106989. // leaves the pointermap in a broken state.
  106990. // Therefore, on every touchstart, we remove the touches that did not fire a
  106991. // touchend event.
  106992. // To keep state globally consistent, we fire a
  106993. // pointercancel for this "abandoned" touch
  106994. vacuumTouches:function(a){var b=a.touches;
  106995. // pointermap.size should be < tl.length here, as the touchstart has not
  106996. // been processed yet.
  106997. if(R.size>=b.length){var c=[];R.forEach(function(a,d){
  106998. // Never remove pointerId == 1, which is mouse.
  106999. // Touch identifiers are 2 smaller than their pointerId, which is the
  107000. // index in pointermap.
  107001. 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);
  107002. // a finger drifted off the screen, ignore it
  107003. if(c){var d=c.out,e=c.outTarget;u.move(b),d&&e!==b.target&&(d.relatedTarget=b.target,b.relatedTarget=e,
  107004. // recover from retargeting by shadow
  107005. d.target=e,b.target?(u.leaveOut(d),u.enterOver(b)):(
  107006. // clean up case when finger leaves the screen
  107007. 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)},
  107008. // prevent synth mouse events from creating pointer events
  107009. dedupSynthMouse:function(a){var b=N.lastTouches,c=a.changedTouches[0];
  107010. // only the primary finger will synth mouse events
  107011. if(this.isPrimaryTouch(c)){
  107012. // remember x/y of last touch
  107013. 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});
  107014. /***/ }),
  107015. /* 36 */
  107016. /***/ (function(module, exports, __webpack_require__) {
  107017. "use strict";
  107018. Object.defineProperty(exports, "__esModule", { value: true });
  107019. var defaultViewer_1 = __webpack_require__(5);
  107020. var mappers_1 = __webpack_require__(1);
  107021. /**
  107022. * Select all HTML tags on the page that match the selector and initialize a viewer
  107023. *
  107024. * @param selector the selector to initialize the viewer on (default is 'babylon')
  107025. */
  107026. function InitTags(selector) {
  107027. if (selector === void 0) { selector = 'babylon'; }
  107028. var elements = document.querySelectorAll(selector);
  107029. for (var i = 0; i < elements.length; ++i) {
  107030. var element = elements.item(i);
  107031. // get the html configuration
  107032. var configMapper = mappers_1.mapperManager.getMapper('dom');
  107033. var config = configMapper.map(element);
  107034. var viewer = new defaultViewer_1.DefaultViewer(element, config);
  107035. }
  107036. }
  107037. exports.InitTags = InitTags;
  107038. /***/ })
  107039. /******/ ]);
  107040. return BabylonViewer;
  107041. });